<!--DO NOT EDIT: GENERATED BY merge-element-specs.xsl--><!--DO NOT EDIT: GENERATED BY merge-element-specs.xsl--><!--DO NOT EDIT: GENERATED BY merge-element-specs.xsl--><!--DO NOT EDIT: GENERATED BY merge-element-specs.xsl--><!--DO NOT EDIT: GENERATED BY merge-element-specs.xsl--><!--DO NOT EDIT: GENERATED BY merge-element-specs.xsl--><!--DO NOT EDIT: GENERATED BY merge-element-specs.xsl--><!--DO NOT EDIT: GENERATED BY merge-element-specs.xsl--><!--DO NOT EDIT: GENERATED BY merge-element-specs.xsl--><!--DO NOT EDIT: GENERATED BY merge-element-specs.xsl--><!--DO NOT EDIT: GENERATED BY merge-element-specs.xsl--><!--DO NOT EDIT: GENERATED BY merge-element-specs.xsl--><!--DO NOT EDIT: GENERATED BY merge-element-specs.xsl--><!--DO NOT EDIT: GENERATED BY merge-element-specs.xsl--><!--DO NOT EDIT: GENERATED BY merge-element-specs.xsl--><!--DO NOT EDIT: GENERATED BY merge-element-specs.xsl--><!--DO NOT EDIT: GENERATED BY merge-element-specs.xsl--><!--DO NOT EDIT: GENERATED BY merge-element-specs.xsl--><!--DO NOT EDIT: GENERATED BY merge-element-specs.xsl--><!--DO NOT EDIT: GENERATED BY merge-element-specs.xsl--><spec w3c-doctype="rec" status="int-review"><header><title>XSL Transformations (XSLT)</title><version>Version 4.0</version><w3c-designation>REC-xslt-40</w3c-designation><w3c-doctype>W3C Editor's Draft</w3c-doctype><pubdate><day>7</day><month>February</month><year>2026</year></pubdate><publoc>
         <loc xmlns:xlink="http://www.w3.org/1999/xlink" href="https://qt4cg.org/specifications/xslt-40/" xlink:type="simple" xlink:show="replace" xlink:actuate="onRequest">https://qt4cg.org/specifications/xslt-40/</loc>
      </publoc><altlocs><loc xmlns:xlink="http://www.w3.org/1999/xlink" href="xslt-40.xml" xlink:type="simple" xlink:show="replace" xlink:actuate="onRequest">Specification in XML format</loc><loc xmlns:xlink="http://www.w3.org/1999/xlink" href="schema-for-xslt40.xsd" xlink:type="simple" xlink:show="replace" xlink:actuate="onRequest">XSD 1.1 Schema for XSLT 4.0 Stylesheets (non-normative)</loc><loc xmlns:xlink="http://www.w3.org/1999/xlink" href="schema-for-xslt40.rnc" xlink:type="simple" xlink:show="replace" xlink:actuate="onRequest">Relax-NG Schema for XSLT 4.0 Stylesheets (non-normative)</loc><loc xmlns:xlink="http://www.w3.org/1999/xlink" href="xml-to-json.xsl" xlink:type="simple" xlink:show="replace" xlink:actuate="onRequest">Stylesheet for XML-to-JSON conversion (non-normative)</loc></altlocs><latestloc>
         <loc xmlns:xlink="http://www.w3.org/1999/xlink" href="https://qt4cg.org/specifications/xslt-40/" xlink:type="simple" xlink:show="replace" xlink:actuate="onRequest"/>
      </latestloc><prevrec doc="XSL Transformations (XSLT)">
    <loc xmlns:xlink="http://www.w3.org/1999/xlink" href="https://www.w3.org/TR/xslt-30/" xlink:type="simple" xlink:show="replace" xlink:actuate="onRequest">https://www.w3.org/TR/xslt-30/</loc>
  </prevrec><authlist><author><name>Michael Kay</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><status><p><emph>This section describes the status of this document at the time of its publication.
               Other documents may supersede this document.</emph></p><p>This document is a working draft developed and maintained by a W3C Community Group,
            the <loc xmlns:xlink="http://www.w3.org/1999/xlink" href="https://www.w3.org/community/xslt-40/" xlink:type="simple" xlink:show="replace" xlink:actuate="onRequest">XQuery and XSLT Extensions Community Group</loc>
            unofficially known as QT4CG (where "QT" denotes Query and Transformation). This draft
            is work in progress and should not be considered either stable or complete.
            Standard W3C copyright and patent conditions apply.</p><p>The community group welcomes comments on the specification. Comments are best submitted
         as issues on the group's <loc xmlns:xlink="http://www.w3.org/1999/xlink" href="https://github.com/qt4cg/qtspecs/issues" xlink:type="simple" xlink:show="replace" xlink:actuate="onRequest">GitHub repository</loc>.</p><p>The community group maintains two extensive test suites, 
            one oriented to XQuery and XPath, the other to XSLT.
         These can be found at <loc xmlns:xlink="http://www.w3.org/1999/xlink" href="https://github.com/qt4cg/qt4tests" xlink:type="simple" xlink:show="replace" xlink:actuate="onRequest">qt4tests</loc> and
         <loc xmlns:xlink="http://www.w3.org/1999/xlink" href="https://github.com/qt4cg/xslt40-test" xlink:type="simple" xlink:show="replace" xlink:actuate="onRequest">xslt40-test</loc> respectively. New tests,
         or suggestions for correcting existing tests, are welcome. The test suites include extensive metadata
         describing the conditions for applicability of each test case as well as the expected results. They
         do not include any test drivers for executing the tests: each implementation is expected to provide
         its own test driver.</p><note role="dedication" id="dedication"><p>The publications of this community group 
<loc xmlns:xlink="http://www.w3.org/1999/xlink" href="../xquery-40/xpath-40.html#dedication" xlink:type="simple" xlink:show="replace" xlink:actuate="onRequest">are dedicated</loc> to our co-chair,
Michael Sperberg-McQueen (1954–2024).</p></note></status><abstract><p>This specification defines the syntax and semantics of XSLT 4.0, a language designed
               primarily for transforming XML documents into other XML documents, but
               also offering support for other data formats including JSON, HTML, and CSV.</p><p>XSLT 4.0 is a revised version of the XSLT 3.0 Recommendation <bibref ref="xslt-30"/>
            published on 8 June 2017. Changes are presented in <specref ref="whats-new-in-xslt4"/>. </p><p>XSLT 4.0 is designed to be used in conjunction with XPath 4.0, which is defined in
               <bibref ref="xpath-40"/>. XSLT shares the same data model as XPath 4.0, which is
            defined in <bibref ref="xpath-datamodel-40"/>, and it uses the library of functions and
            operators defined in <bibref ref="xpath-functions-40"/>. XPath 4.0 and the underlying
            function library introduce a number of enhancements, for example the availability of
            union and record types. </p><p>
            <emph>This document contains hyperlinks to specific sections or definitions within other
               documents in this family of specifications. These links are indicated visually by a
               superscript identifying the target specification: for example XP for XPath 4.0,
               DM for the XDM data model version 4.0, FO for Functions and Operators version
               4.0, SG for XSLT Streaming version 4.0.</emph>
         </p><p>An optional feature of the XSLT language is support for streamed transformations.
         The XSLT 4.0 specification has been modularized so that streaming is now described
         in a separate specification document. This has been done in order to make the
         specifications more manageable, both for editors and readers: it does not alter
         the status of streaming as an optional feature, available in some processors
         and not others.</p></abstract><langusage><language id="EN">English</language></langusage><revisiondesc><slist><sitem>((not used)).</sitem></slist></revisiondesc></header><body><div1 id="introduction"><head>Introduction</head><div2 id="what-is-xslt"><head>What is XSLT?</head><p>XSLT is a programming language designed principally to transform data.</p><p>A transformation in the XSLT language is expressed in the
               form of a <term>stylesheet</term>. A stylesheet is made up of one or more well-formed
               XML <bibref ref="REC-xml"/> documents conforming to the Namespaces in XML
               Recommendation <bibref ref="xml-names"/>. </p><p>A stylesheet generally includes elements that are defined by XSLT as well as elements
               that are not defined by XSLT. XSLT-defined elements are distinguished by use of the
               namespace <code nobreak="false">http://www.w3.org/1999/XSL/Transform</code> (see <specref ref="xslt-namespace"/>), which is referred to in this specification as the
                  <termref def="dt-xslt-namespace">XSLT namespace</termref>. Thus this specification
               is a definition of the syntax and semantics of the XSLT namespace.</p><p>The term <termref def="dt-stylesheet">stylesheet</termref> reflects the fact that one
               of the important roles of XSLT is to add styling information to an XML source
               document, by transforming it into a document consisting of XSL formatting objects
               (see <bibref ref="xsl11"/>), or into another presentation-oriented format such as
               HTML, XHTML, or SVG. However, XSLT is used for a wide range of transformation tasks,
               not exclusively for formatting and presentation applications.</p><p>A transformation expressed in XSLT describes rules for transforming input data into output data. The inputs and outputs
                  will all be instances of the XDM data model, described in <bibref ref="xpath-datamodel-40"/>. In the simplest and most common case, the input is
                  an XML document referred to as the source document or <termref def="dt-source-tree">source tree</termref>, and the output is an XML document
                  referred to as the <termref def="dt-result-tree">result tree</termref>. It is also possible to process multiple source
                  documents, to generate multiple result documents, and to handle formats other than
                  XML.</p><p>The transformation is achieved by a set of
                  <termref def="dt-template-rule">template rules</termref>. A template rule
               associates a <termref def="dt-pattern">pattern</termref>, which typically matches nodes in the source document, with a
                  <termref def="dt-sequence-constructor">sequence constructor</termref>. In many
               cases, evaluating the sequence constructor will cause new nodes to be constructed,
               which can be used to produce part of a result tree. The structure of the result trees
               can be completely different from the structure of the source trees. In constructing a
               result tree, nodes from the source trees can be filtered and reordered, and arbitrary
               structure can be added. Because <termref def="dt-pattern">pattern</termref>s can
               point to nodes according to typological features, a <termref def="dt-stylesheet">stylesheet</termref> 
               can be applicable to a wide class of source documents that have similar tree structures.</p><p>Stylesheets are modular; they may contain several packages developed
               independently of each other, and each package may consist of several stylesheet
               modules. </p><p><termdef id="dt-stylesheet" term="stylesheet">A
                     <term>stylesheet</term> consists of one or more packages: specifically, one
                     <termref def="dt-top-level-package">top-level package</termref> and zero or
                  more <termref def="dt-library-package">library packages</termref>.</termdef></p><p><termdef id="dt-top-level-package" term="top-level package">For a given transformation, one <termref def="dt-package">package</termref> functions as the <term>top-level package</term>. The
                  complete <termref def="dt-stylesheet">stylesheet</termref> is assembled by finding
                  the packages referenced directly or indirectly from the top-level package using
                     <elcode>xsl:use-package</elcode> declarations: see <specref ref="package-dependencies"/>.</termdef></p><p><termdef id="dt-library-package" term="library package">Every <termref def="dt-package">package</termref> within a <termref def="dt-stylesheet">stylesheet</termref>, other than the <termref def="dt-top-level-package">top-level package</termref>, is referred to as a
                     <term>library package</term>.</termdef></p><p><termdef id="dt-principal-stylesheet-module" term="principal stylesheet module">Within a <termref def="dt-package">package</termref>, one <termref def="dt-stylesheet-module"/> functions as the
                     <term>principal stylesheet module</term>. The complete package is assembled by
                  finding the stylesheet modules referenced directly or indirectly from the
                  principal stylesheet module using <elcode>xsl:include</elcode> and
                     <elcode>xsl:import</elcode> elements: see <specref ref="include"/> and <specref ref="import"/>.</termdef></p></div2><div2 id="whats-new-in-xslt4"><head>What’s New in XSLT 4.0?</head><changes><change>If a section of this specification has been updated since version 3.0,
                   an overview of the changes is provided, along with links to
                   navigate to the next or previous change.</change><change>Sections with significant changes are marked with a ✭ symbol in the
                   table of contents.</change></changes><p>XSLT 4.0 is a revised version of the XSLT 3.0 Recommendation <bibref ref="xslt-30"/>
               published on 8 June 2017.</p><p>The changes in this version of the language are relatively minor usability enhancements. There
               are no changes to the data model or processing model. Instead, the specification attempts to fill
               a number of gaps in functionality resulting from feedback from XSLT 3.0 users. The main areas
               covered are:</p><ulist><item><p>Enhancements to the type system to allow more expressive constraints, especially
                  for maps and atomic items.</p></item><item><p>Additional functionality for processing arrays.</p></item><item><p>Exploitation of the power afforded by first-class function items.</p></item></ulist><p>XSLT 4.0 also includes optional facilities to serialize the results of a transformation,
               by means of an interface to the serialization component described in 
               <bibref ref="xslt-xquery-serialization-40"/>.
            </p><p>XSLT 4.0 requires support for XPath 4.0.</p><p>A full list of changes is at <specref ref="changes-since-3.0"/>.</p></div2></div1><div1 id="concepts"><head>Concepts</head><div2 id="terminology"><head>Terminology</head><changes><change issue="1337" PR="1361" date="2024-08-02">
                  The term <term>atomic value</term> has been replaced by <term>atomic item</term>.
               </change></changes><p>For a full glossary of terms, see <specref ref="glossary"/>.</p><p>
               <termdef id="dt-processor" term="processor">The software responsible for transforming
                  source trees into result trees using an XSLT stylesheet is referred to as the
                     <term>processor</term>. This is sometimes expanded to <emph>XSLT
                     processor</emph> to avoid any confusion with other processors, for example an
                  XML processor.</termdef>
            </p><p>
               <termdef id="dt-implementation" term="implementation">A specific product that
                  performs the functions of an <termref def="dt-processor">XSLT processor</termref>
                  is referred to as an <term>implementation</term>.</termdef></p><p>
               <termdef id="dt-tree" term="tree">The term <term>tree</term> is used (as in <bibref ref="xpath-datamodel-40"/>) to refer to the aggregate consisting of a
                  parentless node together with all its descendant nodes, plus all their attributes
                  and namespaces.</termdef>
            </p><note><p>The use of the term <term>tree</term> in this document in phrases such as <term>source
                     tree</term>, <term>result tree</term>, and <term>temporary tree</term> does not imply the use
                     of a data structure in memory that holds the entire contents of the document at
                     one time. It implies rather a logical view of the XML input and output in which
                     elements have a hierarchic relationship to each other. When a source document
                     is being processed in a streaming manner, access to the nodes in this tree is
                     constrained, but it is still viewed and described as a tree.</p></note><p>The output of a transformation consists of the
               following:</p><olist><item><p><termdef id="dt-principal-result" term="principal result">A <term>principal
                           result</term>: this can be any sequence of items (as defined in <bibref ref="xpath-datamodel-40"/>).</termdef> The principal result is the value
                     returned by the function or template in the stylesheet that is nominated as the
                     entry point, as described in <specref ref="initiating"/>.</p></item><item><p><termdef id="dt-secondary-result" term="secondary result">Zero or more
                           <term>secondary results</term>: each secondary result can be any sequence
                        of items (as defined in <bibref ref="xpath-datamodel-40"/>).</termdef> A
                     secondary result is the value returned by evaluating the body of an
                        <elcode>xsl:result-document</elcode> instruction.</p></item><item><p>Zero or more messages. Messages are generated by the
                        <elcode>xsl:message</elcode> and <elcode>xsl:assert</elcode> instructions, and are described in <specref ref="message"/> and <specref ref="assertions"/>.</p></item><item><p>Static or dynamic errors: see <specref ref="errors"/>. </p></item></olist><p>The <termref def="dt-principal-result"/> and the <termref def="dt-secondary-result">secondary results</termref> may be post-processed as
               described in <specref ref="post-processing"/>.</p><p>
               <termdef id="dt-result-tree" term="result tree">The term <term>result tree</term> is
                  used to refer to any <termref def="dt-tree">tree</termref> constructed by <termref def="dt-instruction">instructions</termref> in the stylesheet. A result tree is
                  either a <termref def="dt-final-result-tree">final result tree</termref> or a
                     <termref def="dt-temporary-tree">temporary tree</termref>.</termdef>
            </p><p>
               <termdef id="dt-final-result-tree" term="final result tree">A <term>final result
                     tree</term> is a <termref def="dt-result-tree">result tree</termref> that forms
                  part of the output of a transformation: specifically, a tree built by post-processing the items in the <termref def="dt-principal-result"/> or in a <termref def="dt-secondary-result"/>. Once created, the contents of a final result tree are not
                  accessible within the stylesheet itself.</termdef>
                Any final result tree
                  <rfc2119>may</rfc2119> be serialized as described in <specref ref="serialization"/>.</p><p>
               <termdef id="dt-source-tree" term="source tree">The term <term>source tree</term>
                  means any tree provided as input to the transformation. This includes the document
                  containing the <termref def="dt-global-context-item"/> if any, documents containing
                     nodes present in the <termref def="dt-initial-match-selection"/>,
                  documents containing nodes supplied as the values of <termref def="dt-stylesheet-parameter">stylesheet parameters</termref>, documents
                  obtained from the results of functions such as <function>document</function>,
                     <xfunction>doc</xfunction>, and <xfunction>collection</xfunction>, documents read using the <elcode>xsl:source-document</elcode>
                     instruction, and documents returned by extension functions or
                  extension instructions. In the context of a particular XSLT instruction, the term
                     <term>source tree</term> means any tree provided as input to that instruction;
                  this may be a source tree of the transformation as a whole, or it may be a
                     <termref def="dt-temporary-tree">temporary tree</termref> produced during the
                  course of the transformation.</termdef>
            </p><p>
               <termdef id="dt-temporary-tree" term="temporary tree">The term <term>temporary
                     tree</term> means any tree that is neither a <termref def="dt-source-tree">source tree</termref> nor a <termref def="dt-final-result-tree">final result
                     tree</termref>.</termdef> Temporary trees are used to hold intermediate results
               during the execution of the transformation.</p><p>Unless otherwise stated, the term “tree” refers to a tree rooted
                  at a parentless node: that is, the term does not include subtrees of larger trees.
                  Every node therefore belongs to exactly one tree.</p><p>In this specification the phrases <rfc2119>must</rfc2119>, <rfc2119>must
                  not</rfc2119>, <rfc2119>should</rfc2119>, <rfc2119>should not</rfc2119>,
                  <rfc2119>may</rfc2119>, <rfc2119>required</rfc2119>, and
                  <rfc2119>recommended</rfc2119>, when used in normative
                  text and rendered in small capitals, are to be interpreted as described in
                  <bibref ref="rfc2119"/>.</p><p>Where the phrase <rfc2119>must</rfc2119>, <rfc2119>must not</rfc2119>, or
                  <rfc2119>required</rfc2119> relates to the behavior of the XSLT processor, then an
               implementation is not conformant unless it behaves as specified, subject to the more
               detailed rules in <specref ref="conformance"/>. </p><p>Where the phrase <rfc2119>must</rfc2119>, <rfc2119>must not</rfc2119>, or
                  <rfc2119>required</rfc2119> relates to a stylesheet then the processor
                  <rfc2119>must</rfc2119> enforce this constraint on stylesheets by raising an
               error if the constraint is not satisfied.</p><p>Where the phrase <rfc2119>should</rfc2119>, <rfc2119>should not</rfc2119>, or
                  <rfc2119>recommended</rfc2119> relates to a stylesheet then a processor
                  <rfc2119>may</rfc2119> produce warning messages if the constraint is not
               satisfied, but <rfc2119>must not</rfc2119> treat this as an error.</p><p>
               <termdef id="dt-implementation-defined" term="implementation-defined">In this
                  specification, the term <term>implementation-defined</term> refers to a feature
                  where the implementation is allowed some flexibility, and where the choices made
                  by the implementation <rfc2119>must</rfc2119> be described in documentation that
                  accompanies any conformance claim.</termdef>
            </p><p>
               <termdef id="dt-implementation-dependent" term="implementation-dependent">The term
                     <term>implementation-dependent</term> refers to a feature where the behavior
                     <rfc2119>may</rfc2119> vary from one implementation to another, and where the
                  vendor is not expected to provide a full specification of the behavior.</termdef>
               (This might apply, for example, to limits on the size of source documents that can be
               transformed.)</p><p>In all cases where this specification leaves the behavior implementation-defined or
               implementation-dependent, the implementation has the option of providing mechanisms
               that allow the user to influence the behavior.</p><p>A paragraph labeled as a <term>Note</term> or described as an <term>example</term> is
               non-normative.</p><p>Many terms used in this document are defined in the XPath specification <bibref ref="xpath-40"/> or the XDM specification <bibref ref="xpath-datamodel-40"/>.
               Particular attention is drawn to the following:</p><ulist><item><p>
                     <termdef id="dt-atomization" term="atomize">The term <term>atomization</term>
                        is defined in <xspecref spec="XP40" ref="id-atomization"/>. It is a process that takes as input a sequence of
                        items, and returns a sequence of
                        atomic items, in which the nodes are replaced by their typed values as
                        defined in <bibref ref="xpath-datamodel-40"/>. 
                        <phrase diff="del" at="2022-01-01">If the XPath 3.1 feature is implemented,
                        then</phrase> Arrays (see <specref ref="arrays"/>) are atomized by atomizing their
                        members, recursively.</termdef> For some items (for example, elements with element-only
                     content, function items, and maps, atomization
                     raises a <termref def="dt-dynamic-error">dynamic error</termref>.</p></item><item><p>
                     <termdef id="dt-typed-value" term="typed value">The term <term>typed
                           value</term> is defined in <xspecref spec="DM40" ref="dm-typed-value"/>.
                        Every node, other than an element whose type
                           annotation identifies it as having element-only content, has a
                           <termref def="dt-string-value">typed value</termref>. For example, the
                           <termref def="dt-typed-value">typed value</termref> of an attribute of
                        type <code nobreak="false">xs:IDREFS</code> is a sequence of zero or more
                           <code nobreak="false">xs:IDREF</code> values.</termdef>
                  </p></item><item><p>
                     <termdef id="dt-string-value" term="string value">The term <term>string
                           value</term> is defined in
                           <xspecref spec="DM40" ref="dm-string-value"/>. Every node has a <termref def="dt-string-value">string value</termref>. For example, the <termref def="dt-string-value">string value</termref> of an element is the concatenation of the
                           <termref def="dt-string-value">string values</termref> of all its
                        descendant text nodes.</termdef>
                  </p></item><item><p>
                     <termdef id="dt-xpath-compat-mode" term="XPath 1.0 compatibility mode">The term
                           <term>XPath 1.0 compatibility mode</term> is defined in 
                        <xspecref spec="XP40" ref="static_context"/>. This is a setting in the static
                        context of an XPath expression; it has two values, <code nobreak="false">true</code> and
                           <code nobreak="false">false</code>. When the value is set to <code nobreak="false">true</code>, the semantics of
                        function calls and certain other operations are adjusted to give a greater
                        degree of backwards compatibility between XPath
                        <phrase diff="chg" at="2023-02-24">4.0</phrase> and XPath 1.0.</termdef>
                  </p></item><item><p>
                     <termdef id="dt-function-definition" term="function definition">The term
                        <term>function definition</term> is defined in <xspecref spec="XP40" ref="static_context"/>. 
                        It is the definition of a function that can be called statically from within an XPath
                        expression: in the case of XSLT it typically means either a <termref def="dt-stylesheet-function"/>,
                        or a built-in function such as those defined in <bibref ref="xpath-functions-40"/></termdef>
                  </p></item><item><p>
                     <termdef id="dt-arity-range" term="arity range">A <termref def="dt-function-definition"/>
                        has an <term>arity range</term>, which defines the minimum and maximum number of arguments
                        that must be supplied in a call to the function. The static context can contain multiple
                        <termref def="dt-function-definition">function definitions</termref> with the same name, 
                        provided that their <term>arity ranges</term> do not overlap.</termdef>
                      
                  </p></item></ulist></div2><div2 id="notation"><head>Notation</head><p>
               <termdef id="dt-xslt-element" term="XSLT element">An <term>XSLT element</term> is an
                  element in the <termref def="dt-xslt-namespace">XSLT namespace</termref> whose
                  syntax and semantics are defined in this specification.</termdef> For a
               non-normative list of XSLT elements, see <specref ref="element-syntax-summary"/>.</p><p>In this document the specification of each <termref def="dt-xslt-element">XSLT
                  element</termref> is preceded by a summary of its syntax in the form of a model
               for elements of that element type. A full list of all these specifications can be
               found in <specref ref="element-syntax-summary"/>. The meaning of the syntax summary
               notation is as follows:</p><ulist><item><p>An attribute that is <rfc2119>required</rfc2119> is shown with its name in
                     bold. An attribute that may be omitted is shown with a question mark following
                     its name.</p></item><item><p>An attribute that is <termref def="dt-deprecated">deprecated</termref> is shown
                     in a grayed font within square brackets.</p></item><item><p>The string that occurs in the place of an attribute value specifies the allowed
                     values of the attribute. If this is surrounded by curly brackets
                        (<code nobreak="false">{...}</code>), then the attribute value is treated as an <termref def="dt-attribute-value-template">attribute value template</termref>, and
                     the string occurring within curly brackets specifies the allowed values of the
                     result of evaluating the attribute value template. Alternative allowed values
                     are separated by <code nobreak="false">|</code>. A quoted string indicates a value equal to
                     that specific string. An unquoted, italicized name specifies a particular type
                     of value.</p><p>The types used, and their meanings, are as follows:</p><glist><gitem><label>
                           <code nobreak="false">boolean</code>
                        </label><def><p>One of the strings <code nobreak="false">"yes"</code>,
                              <code nobreak="false">"true"</code>, or <code nobreak="false">"1"</code> to indicate the value
                              <code nobreak="false">true</code>, or one of the strings <code nobreak="false">"no"</code>,
                              <code nobreak="false">"false"</code>, or <code nobreak="false">"0"</code> to indicate the value
                              <code nobreak="false">false</code>. Note: the values are synonyms; where this
                              specification uses a phrase such as “If <code nobreak="false">required='yes'</code> is
                              specified ...” this is to be interpreted as meaning “If the attribute
                              named <code nobreak="false">required</code> is present, and has the value
                              <code nobreak="false">yes</code>, <code nobreak="false">true</code>, or <code nobreak="false">1</code> (after
                              stripping leading and trailing whitespace) ...”.
                           </p></def></gitem><gitem><label><code nobreak="false">string</code></label><def><p>Any string.</p></def></gitem><gitem><label><code nobreak="false">expression</code></label><def><p>An XPath <termref def="dt-expression">expression</termref>.</p></def></gitem><gitem><label><code nobreak="false">pattern</code></label><def><p>A <termref def="dt-pattern">pattern</termref> as described in
                                 <specref ref="patterns"/>.</p></def></gitem><gitem><label><code nobreak="false">item-type</code></label><def><p>An <xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="XP40" ref="prod-xpath40-ItemType" xlink:type="simple">ItemType</xnt> as defined in the XPath
                              <phrase diff="chg" at="2022-01-01">4.0</phrase> specification.</p></def></gitem><gitem><label><code nobreak="false">sequence-type</code></label><def><p>A <xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="XP40" ref="prod-xpath40-SequenceType" xlink:type="simple">SequenceType</xnt>
                              as defined in the XPath <phrase diff="chg" at="2022-01-01">4.0</phrase> specification.</p></def></gitem><gitem><label><code nobreak="false">uri; uris</code></label><def><p>A URI, for example a namespace URI or a collation URI; a
                              whitespace-separated list of URIs.</p></def></gitem><gitem><label><code nobreak="false">qname</code></label><def><p>A <termref def="dt-lexical-qname">lexical QName</termref> as defined
                              in <specref ref="qname"/>.</p></def></gitem><gitem><label><code nobreak="false">eqname; eqnames</code></label><def><p>An <termref def="dt-eqname">EQName</termref> as defined in <specref ref="qname"/>; a whitespace-separated list of EQNames.</p></def></gitem><gitem><label><code nobreak="false">token; tokens</code></label><def><p>A string containing no significant whitespace; a whitespace-separated
                              list of such strings.</p></def></gitem><gitem><label><code nobreak="false">nmtoken; nmtokens</code></label><def><p>A string conforming to the XML schema rules for the type
                                 <code nobreak="false">xs:NMTOKEN</code>; a whitespace-separated list of such
                              strings.</p></def></gitem><gitem><label><code nobreak="false">char</code></label><def><p>A string comprising a single Unicode character.</p></def></gitem><gitem diff="add" at="2023-04-18"><label><code nobreak="false">language</code></label><def><p>A string in the value space of <code nobreak="false">xs:language</code>, or a zero-length string.</p></def></gitem><gitem><label><code nobreak="false">integer</code></label><def><p>An integer, that is, a string <phrase diff="chg" at="2022-11-01">that is castable to</phrase> the schema type
                                 <code nobreak="false">xs:integer</code>.</p></def></gitem><gitem><label><code nobreak="false">decimal</code></label><def><p>A decimal value, that is, a string <phrase diff="chg" at="2022-11-01">that is castable to</phrase> the schema
                              type <code nobreak="false">xs:decimal</code>.</p></def></gitem><gitem><label><code nobreak="false">ncname</code>; <phrase diff="add" at="2022-01-01"><code nobreak="false">ncnames</code></phrase></label><def><p>An unprefixed name: a string <phrase diff="chg" at="2022-11-01">that is castable to</phrase> the schema type
                                 <code nobreak="false">xs:NCName</code>; <phrase diff="add" at="2022-01-01">a whitespace-separated list of such strings</phrase>.</p></def></gitem><gitem><label><code nobreak="false">prefix</code><phrase diff="add" at="2023-04-18">; <code nobreak="false">prefixes</code></phrase></label><def><p>An <code nobreak="false">xs:NCName</code> representing a namespace prefix, which must
                              be in scope for the element on which it appears;
                              <phrase diff="add" at="2022-01-01">a whitespace-separated list of such strings</phrase>.</p></def></gitem><gitem><label><code nobreak="false">id</code></label><def><p>An <code nobreak="false">xs:NCName</code> used as a unique identifier for an element
                              in the containing XML document.</p></def></gitem></glist><p>Except where the set of allowed values of an attribute is specified using the
                     italicized name <emph>string</emph> or <emph>char</emph>, leading and trailing
                     whitespace in the attribute value is ignored. In the case of an <termref def="dt-attribute-value-template">attribute value template</termref>, this
                     applies to the <termref def="dt-effective-value">effective value</termref>
                     obtained when the attribute value template is expanded.</p><p>XPath comments (delimited by <code nobreak="false">(: ... :)</code>)
                  are permitted anywhere that inter-token whitespace is permitted in attributes whose
                  type is given as <emph>expression</emph>, <emph>pattern</emph>, <emph>item-type</emph>, 
                     or <emph>sequence-type</emph>, and are not permitted in attributes of other types
                     (other than within expressions enclosed by curly braces within an <termref def="dt-attribute-value-template"/>).</p></item><item diff="add" at="2023-07-04"><p>If an attribute has a simple default value, this is shown between tortoise-shell
                  brackets (for example <code nobreak="false">〔'no'〕</code>). Where no default is shown,
                  the consequence of omitting the attribute is explained in the prose narrative. 
                  Default values shown in the summary apply only where the attribute itself
                  is applicable; if an attribute is not permitted to appear in the particular context,
                  then its default value should be ignored. (For example, the <code nobreak="false">stable</code>
                     attribute of <elcode>xsl:sort</elcode> is shown as having a default value
                     of <code nobreak="false">'yes'</code>, but the attribute is allowed only on the
                     first of a sequence of adjacent <elcode>xsl:sort</elcode> elements.) 
                     The quotation marks around a default value are not part of the value.</p></item><item><p>Unless the element is <rfc2119>required</rfc2119> to be empty, the model
                     element contains a comment specifying the allowed content. The allowed content
                     is specified in a way similar to an element type declaration in XML;
                        <emph>sequence constructor</emph> means that any mixture of text nodes,
                        <termref def="dt-literal-result-element">literal result elements</termref>,
                        <termref def="dt-extension-instruction">extension instructions</termref>,
                     and <termref def="dt-xslt-element">XSLT elements</termref> from the <termref def="dt-instruction">instruction</termref> category is allowed;
                        <emph>other-declarations</emph> means that any mixture of XSLT elements from
                     the <termref def="dt-declaration">declaration</termref> category is allowed, together with <termref def="dt-data-element">user-defined data elements</termref>.</p></item><item><p>The element is prefaced by comments indicating if it belongs to the
                        <code nobreak="false">instruction</code> category or <code nobreak="false">declaration</code> category or
                     both. The category of an element affects only whether it is allowed in the
                     content of elements that allow a <termref def="dt-sequence-constructor">sequence constructor</termref> or <emph>other-declarations</emph>.</p></item></ulist><example><head>Syntax Notation</head><p>This example illustrates the notation used to describe <termref def="dt-xslt-element">XSLT elements</termref>.</p><e:element-syntax xmlns:e="http://www.w3.org/1999/XSL/Spec/ElementSyntax" name="example-element"><e:in-category name="instruction"/><e:attribute name="select" required="yes"><e:data-type name="expression"/></e:attribute><e:attribute name="debug"><e:data-type name="boolean"/></e:attribute><e:attribute name="validation" default="strict"><e:attribute-value-template><e:constant value="strict"/><e:constant value="lax"/></e:attribute-value-template></e:attribute><e:sequence><e:choice repeat="zero-or-more"><e:element name="variable"/><e:element name="param"/></e:choice><e:element name="sequence"/></e:sequence><e:allowed-parents><e:parent-category name="sequence-constructor"/></e:allowed-parents></e:element-syntax><p>This example defines a (non-existent) element <code nobreak="false">xsl:example-element</code>.
                  The element is classified as an instruction. It takes the following
                  attributes:</p><olist><item><p>A mandatory <code nobreak="false">select</code> attribute, whose value is an XPath <termref def="dt-expression">expression</termref></p></item><item><p>An optional <code nobreak="false">debug</code> attribute, whose
                        value <rfc2119>must</rfc2119> be <code nobreak="false">yes</code>, <code nobreak="false">true</code>, or
                           <code nobreak="false">1</code> to indicate <code nobreak="false">true</code>, or <code nobreak="false">no</code>,
                           <code nobreak="false">false</code>, or <code nobreak="false">0</code> to indicate <code nobreak="false">false</code>.</p></item><item><p>An optional <code nobreak="false">validation</code> attribute, whose value must be
                           <code nobreak="false">strict</code> or <code nobreak="false">lax</code>; the curly brackets indicate that
                        the value can be defined as an <termref def="dt-attribute-value-template">attribute value template</termref>, allowing a value such as
                           <code nobreak="false">validation="{ $val }"</code>, where the <termref def="dt-variable">variable</termref>
                        <code nobreak="false">val</code> is evaluated to yield <code nobreak="false">"strict"</code> or
                        <code nobreak="false">"lax"</code> at run-time. The value <code nobreak="false">strict</code> in tortoise-shell
                        brackets indicates the default value, if the attribute is not present.</p></item></olist><p>The content of an <code nobreak="false">xsl:example-element</code> instruction is defined to be a
                  sequence of zero or more <elcode>xsl:variable</elcode> and
                     <elcode>xsl:param</elcode> elements, followed by an
                     <elcode>xsl:sequence</elcode> element.</p></example><p>
               <error spec="XT" type="static" class="SE" code="0010"><p>It is a <termref def="dt-static-error">static error</termref> if an
                     XSLT-defined element is used in a context where it is not permitted, if a
                        <rfc2119>required</rfc2119> attribute is omitted, or if the content of the
                     element does not correspond to the content that is allowed for the element.</p></error>
            </p><p>The rules in the element syntax summary (both for the
               element structure and for its attributes) apply to the stylesheet content after
               preprocessing as described in <specref ref="preprocessing"/>.</p><p diff="add" at="2023-04-18"><termdef id="dt-effective-value" term="effective value">The <term>effective value</term>
            of an attribute or text node in the stylesheet is the value after any required expansion or normalization.</termdef></p><p diff="add" at="2023-04-18">More specifically, the effective value is the value after:</p><ulist diff="add" at="2023-04-18"><item><p>Expanding shadow attributes as described in <specref ref="shadow-attributes"/>;</p></item><item><p>Expanding defaults (for example, if an <elcode>xsl:message</elcode> instruction has
                  no <code nobreak="false">terminate</code> attribute, then the effective value of the <code nobreak="false">terminate</code> attribute
                  is <code nobreak="false">no</code>);</p></item><item><p>Stripping ignored whitespace (for example, the effective value of a boolean attribute written as
                  <code nobreak="false">terminate="  no  "</code> is <code nobreak="false">no</code>);</p></item><item><p>Replacing synonyms (for example in boolean attributes, <code nobreak="false">1</code> and <code nobreak="false">true</code>
                  are synonyms of <code nobreak="false">yes</code>);</p></item><item><p>Expanding <termref def="dt-attribute-value-template">attribute value templates</termref> and 
                  <termref def="dt-text-value-template">text value templates</termref>.</p></item><item><p>Applying rules from the static context: for example, the effective value of a <code nobreak="false">collation</code>
                  attribute is the value after expanding a relative URI against the static base URI.</p></item></ulist><p>Attributes are validated as follows. These rules apply to the value of the attribute
               after removing leading and trailing whitespace.</p><ulist><item><p>
                     <error spec="XT" type="static" class="SE" code="0020"><p>It is a <termref def="dt-static-error">static error</termref> if an
                           attribute (other than an attribute written using curly brackets in a
                           position where an <termref def="dt-attribute-value-template">attribute
                              value template</termref> is permitted) contains a value that is not
                           one of the permitted values for that attribute.</p></error>
                  </p></item><item><p>
                     <error spec="XT" type="dynamic" class="DE" code="0030"><p>It is a <termref def="dt-dynamic-error"> dynamic error</termref> if the <termref def="dt-effective-value">effective value</termref> of an attribute
                           written using curly brackets, in a position where an <termref def="dt-attribute-value-template">attribute value template</termref>
                           is permitted, is a value that is not one of the permitted values for that
                           attribute. If the processor is able to detect the error statically (for
                           example, when any XPath expressions within the curly brackets can be
                           evaluated statically), then the processor may optionally raise this as a
                           static error.</p></error>
                  </p></item></ulist><p>Special rules apply if the construct appears in part of the <termref def="dt-stylesheet">stylesheet</termref> that is processed with <termref def="dt-forwards-compatible-behavior"/>: see <specref ref="forwards"/>.</p><p>
               <termdef id="dt-deprecated" term="deprecated">Some constructs defined in this
                  specification are described as being <term>deprecated</term>. The use of this term
                  implies that stylesheet authors <rfc2119>should not</rfc2119> use the construct,
                  and that the construct may be removed in a later version of this
                  specification.</termdef></p><note><p>This specification includes a non-normative XML Schema for XSLT <termref def="dt-stylesheet-module">stylesheet modules</termref> (see <specref ref="schema-for-xslt"/>). The syntax summaries described in this section are
                  normative.</p></note><p>XSLT defines a set of standard functions which are additional to those defined in
                  <bibref ref="xpath-functions-40"/>. A list of these
                  functions appears in <specref ref="XSLT-defined-functions"/>. The
               signatures of these functions are described using the same notation as used in
                  <bibref ref="xpath-functions-40"/>. The names of many
                  of these functions are in the <termref def="dt-standard-function-namespace">standard function namespace</termref>.</p></div2><div2 id="initiating"><head>Initiating a Transformation</head><p>This document does not specify any application programming interfaces or other
               interfaces for initiating a transformation. This section, however, describes the
               information that is supplied when a transformation is initiated. Except where
               otherwise indicated, the information is <rfc2119>required</rfc2119>.</p><p>The execution of a stylesheet necessarily involves two activities: static analysis
               and dynamic evaluation. Static analysis consists of those tasks that can be performed
               by inspection of the stylesheet alone, including the
                  binding of <termref def="dt-static-variable">static variables</termref>,
               the evaluation of <code nobreak="false">[xsl:]use-when</code> expressions (see <specref ref="conditional-inclusion"/>) and shadow attributes
                  (see <specref ref="shadow-attributes"/>), and the detection of <termref def="dt-static-error">static errors</termref>. Dynamic evaluation consists of
               tasks which in general cannot be carried out until a source document is
               available.</p><p>Dynamic evaluation is further divided into two activities:
                  <term>priming</term> the stylesheet, and <term>invoking</term> a selected
               component. </p><ulist><item><p>Priming the stylesheet provides the dynamic context for evaluation, and
                     supplies all the information needed to establish the values of global
                     variables.</p></item><item><p>Invoking a component (such as a template or function) causes evaluation of that
                     template or function to produce a result, which is an arbitrary XDM value.</p><p><termdef id="dt-raw-result" term="raw result">The result of invoking the
                        selected component, after any required conversion to the declared result
                        type of the component, is referred to as the <term>raw
                        result</term>.</termdef></p><p>The <termref def="dt-raw-result"/> of the invocation
                  is the <termref def="dt-immediate-result"/> of evaluating the <termref def="dt-sequence-constructor"/>
                  contained in the target template or function, modified by applying the <termref def="dt-coercion-rules"/>
                     to convert the <termref def="dt-immediate-result"/> to the type declared in the <code nobreak="false">as</code>
                  attribute of the <elcode>xsl:template</elcode> or <elcode>xsl:function</elcode> declaration, if present.</p><p>This raw result may optionally be post-processed to construct a result tree, to
                     serialize the result, or both, as described in <specref ref="post-processing"/>.</p></item></ulist><p>Implementations <rfc2119>may</rfc2119> allow static analysis and dynamic evaluation
               to be initiated independently, so that the cost of static analysis can be amortized
               over multiple transformations using the same stylesheet. Implementations <rfc2119>may</rfc2119> also allow priming of a stylesheet and
                  invocation of components to be initiated independently, in which case a single act
                  of priming the stylesheet may be followed by a series of independent component
                  invocations. Although this specification does not require such a separation, this
                  section distinguishes information that is needed before static analysis can
                  proceed, information that is needed to prime the stylesheet, and information that
                  is needed when invoking components.</p><p>The language is designed to allow the static analysis of each
                  <termref def="dt-package"/> to be performed independently of other packages, with
               only basic knowledge of the properties of components made available by used packages.
               Beyond this, the specification leaves it to implementations to decide how to organize
               this process. When packages are not used explicitly, the entire stylesheet is treated
               as a single package.</p><div3 id="info-for-static-analysis"><head>Information needed for Static Analysis</head><p>The following information is needed prior to static analysis
                     of a package:</p><ulist><item><p>The location of the <termref def="dt-package-manifest"/>,
                        or in the absence of a package manifest, the <termref def="dt-stylesheet-module">stylesheet module</termref> that is to act as
                        the <termref def="dt-principal-stylesheet-module">principal stylesheet
                           module</termref>
                        of the <termref def="dt-package"/>. The complete <termref def="dt-package">package</termref> is
                        assembled by recursively expanding the <elcode>xsl:import</elcode> and
                           <elcode>xsl:include</elcode> declarations in the principal stylesheet
                        module, as described in <specref ref="include"/> and <specref ref="import"/>. </p></item><item><p>Information about the packages referenced from this
                        package using <elcode>xsl:use-package</elcode> declarations. The information
                        needed will include the names and signatures of public components exported
                        by the referenced package.</p></item><item><p>A set (possibly empty) of values for <termref def="dt-static-parameter">static parameters</termref> (see <specref ref="global-variables"/>). These values are available for use within
                           <termref def="dt-static-expression">static expressions</termref> (notably
                        in <code nobreak="false">[xsl:]use-when</code> expressions and shadow attributes) as well as
                        non-static expressions in the <termref def="dt-stylesheet">stylesheet</termref>. As a minimum, values <rfc2119>must</rfc2119> be
                        supplied for any static parameters declared with the attribute
                           <code nobreak="false">required="yes"</code>.</p></item></ulist><p>Conceptually, the output of the static analysis of a package is
                  an object which might be referred to (without constraining the implementation) as
                  a compiled package. Prior to dynamic evaluation, all the compiled packages needed
                  for execution must be checked for consistency, and component references must be
                  resolved. This process may be referred to, again without constraining the
                  implementation, as linking.</p></div3><div3 id="priming-stylesheet"><head>Priming a Stylesheet</head><p>The information needed when priming a stylesheet is as
                  follows:</p><ulist><item><p>A set (possibly empty) of values for non-static
                        <termref def="dt-stylesheet-parameter">stylesheet parameters</termref> (see
                           <specref ref="global-variables"/>). These values are available for use
                        within <termref def="dt-expression">expressions</termref> in the <termref def="dt-stylesheet">stylesheet</termref>. As a minimum, values
                           <rfc2119>must</rfc2119> be supplied for any parameters declared with the
                        attribute <code nobreak="false">required="yes"</code>.</p><p>A supplied value is converted if necessary to the declared
                        type of the stylesheet parameter using the <termref def="dt-coercion-rules"/>.</p><note><p>Non-static stylesheet parameters are implicitly
                           <code nobreak="false">public</code>, which ensures that all the parameters in the
                           stylesheet for which values can be supplied externally have distinct
                           names. Static parameters, by contrast,
                              are local to a package.</p></note></item><item><p>
                        <termdef id="dt-global-context-item" term="global context item">An item that is the <term>global
                                 context item</term> for the transformation acts
                           as the <termref def="dt-context-item"/> when evaluating
                            the <code nobreak="false">select</code> expression or <termref def="dt-sequence-constructor"/> of a
                                 <termref def="dt-global-variable"/> <phrase diff="chg" at="2022-01-01">whose declaration is</phrase>
                           within the <termref def="dt-top-level-package"/>, as described in <specref ref="focus"/>. The global context item may also be available in a <termref def="dt-named-template"/>
                        when the stylesheet is invoked as described in <specref ref="invoking-initial-template"/></termdef>.
                        </p><note><p>In previous releases of this specification, a single node was typically
                           supplied to represent the source document for the transformation. This
                           node was used as the target node for the implicit call on
                              <elcode>xsl:apply-templates</elcode> used to start the transformation
                           process (now called the <termref def="dt-initial-match-selection"/>), and
                           the root node of the containing tree was used as the context item for
                           evaluation of global variables (now called the <termref def="dt-global-context-item"/>). This relationship between the
                              <termref def="dt-initial-match-selection"/> and the <termref def="dt-global-context-item"/> is likely to be found for compatibility
                           reasons in a transformation API designed to work with earlier versions of
                           this specification, but it is no longer a necessary relationship; the two
                           values can in principle be completely independent of each other.</p><p>Stylesheet authors wanting to write code that can be invoked using legacy
                           APIs should not rely on the caller being able to supply different values
                           for the <termref def="dt-initial-match-selection"/> and the <termref def="dt-global-context-item"/>.</p><p diff="add" at="2023-10-30">In XPath 4.0, the concept of <termref def="dt-context-item"/>
                        has been generalized and is now referred to as the <xtermref spec="XP40" ref="dt-context-value"/>.
                        For XSLT 4.0, however, the <termref def="dt-global-context-item"/> is still constrained to be
                        either a single item, or absent.</p></note><p>The value given to the <termref def="dt-global-context-item"/>
                        (and the values given to <termref def="dt-stylesheet-parameter">stylesheet parameters</termref>)
                     cannot be nodes in a streamed document. This rule ensures that all global variables can freely
                     navigate within the relevant tree, with no constraints imposed by the streamability rules.</p><p>The <termref def="dt-global-context-item"/> is potentially
                        used when initializing global variables and parameters. If the
                        initialization of any <termref def="dt-global-variable">global
                           variables</termref> or <termref def="dt-stylesheet-parameter">parameter</termref> depends on the context item, a dynamic error can
                        occur if the context item is absent. It is <termref def="dt-implementation-defined"/> whether this error occurs during
                        priming of the stylesheet or subsequently when the variable is referenced;
                        and it is <termref def="dt-implementation-defined"/> whether the error
                        occurs at all if the variable or parameter is never referenced. The error
                        can be suppressed by use of <elcode>xsl:try</elcode> and
                           <elcode>xsl:catch</elcode> within the sequence constructor used to initialize the variable or parameter. It
                           cannot be suppressed by use of <elcode>xsl:try</elcode> around a
                           reference to the global variable.
                     </p><imp-def-feature id="idf-api-globalcontext">If the initialization of any
                           <termref def="dt-global-variable">global variables</termref> or <termref def="dt-stylesheet-parameter">parameter</termref> depends on the context
                        item, a dynamic error can occur if the context item is absent. It is
                           <termref def="dt-implementation-defined"/> whether this error occurs
                        during priming of the stylesheet or subsequently when the variable is
                        referenced; and it is <termref def="dt-implementation-defined"/> whether the
                        error occurs at all if the variable or parameter is never referenced. </imp-def-feature><p>In a <termref def="dt-library-package"/>,
                           the <termref def="dt-context-item">context item</termref>, <termref def="dt-context-position">context position</termref>, and <termref def="dt-context-size">context size</termref> used for evaluation of
                           global variables will be <termref def="dt-absent">absent</termref>, and
                           the evaluation of any expression that references these values will result
                           in a dynamic error. 
                        This will also be the case in the
                              <termref def="dt-top-level-package"/> if no <termref def="dt-global-context-item"/> is supplied.</p><note><p>If a context item is available within a global variable declaration, then
                           the <termref def="dt-context-position">context position</termref> and
                              <termref def="dt-context-size">context size</termref> will always be 1
                           (one).</p></note><note><p>For maximum reusability of code, it is best to avoid use of the context
                           item when initializing global variables and parameters. Instead, all
                           external information should be supplied using named <termref def="dt-stylesheet-parameter">stylesheet parameters</termref>,
                           ideally with namespaces, to avoid confusion and conflicts
                           in the information supplied externally to
                           different packages.</p><p>When a stylesheet parameter is defined in a library package, it is
                           possible for a using package to supply a value for the parameter by
                           overriding the parameter declaration within an
                              <elcode>xsl:override</elcode> element. If the using package is the
                              <termref def="dt-top-level-package"/> then the overriding declaration
                           can refer to the <termref def="dt-global-context-item"/>.</p></note></item><item><p>A mechanism for obtaining a document node and a media type, given an
                        absolute URI. The total set of available documents (modeled as a mapping
                        from URIs to document nodes) forms part of the context for evaluating XPath
                        expressions, specifically the <xfunction>doc</xfunction> function. The XSLT
                           <function>document</function> function additionally requires the media
                        type of the resource representation, for use in interpreting any fragment
                        identifier present within a URI Reference.</p><note><p>The set of documents that are available to the stylesheet is <termref def="dt-implementation-dependent">implementation-dependent</termref>,
                           as is the processing that is carried out to construct a tree representing
                           the resource retrieved using a given URI. Some possible ways of
                           constructing a document (specifically, rules for constructing a document
                           from an Infoset or from a PSVI) are described in <bibref ref="xpath-datamodel-40"/>.</p></note></item></ulist><p>Once a stylesheet is primed, the values of global variables
                  remain stable through all component invocations. In addition, priming a stylesheet
                  creates an <xtermref spec="FO40" ref="execution-scope">execution scope</xtermref>
                  during which the dynamic context and all calls
                     on <xtermref spec="FO40" ref="dt-deterministic">deterministic</xtermref>
                     functions remain stable; for example two calls on the
                     <xfunction>current-dateTime</xfunction> function within an execution scope are
                  defined to return the same result.</p><p>Parameters passed to the transformation by the client application when a stylesheet is primed are matched against
                     <termref def="dt-stylesheet-parameter">stylesheet parameters</termref> (see
                     <specref ref="global-variables"/>), not against the <termref def="dt-template-parameter">template parameters</termref> of any template
                  executed during the course of the transformation. </p><p>
                  <error spec="XT" type="dynamic" class="DE" code="0050"><p>It is a <termref def="dt-dynamic-error"> dynamic error</termref> if a
                        stylesheet declares a visible <termref def="dt-stylesheet-parameter">stylesheet parameter</termref>
                        that is <termref def="dt-explicitly-mandatory">explicitly</termref> or <termref def="dt-implicitly-mandatory">implicitly</termref> mandatory,
                        and no value for this parameter is supplied when the stylesheet is primed. A
                        stylesheet parameter is visible if it is not masked by another global
                        variable or parameter with the same name and higher <termref def="dt-import-precedence">import precedence</termref>. If the parameter is a <termref def="dt-static-parameter"/> then the value <rfc2119>must</rfc2119> be
                           supplied prior to the static analysis phase.</p></error>
               </p><imp-def-feature id="idf-api-input">The way in which an XSLT processor is invoked,
                  and the way in which values are supplied for the source document, starting node,
                     <termref def="dt-stylesheet-parameter">stylesheet parameters</termref>, and
                     <termref def="dt-base-output-uri">base output URI</termref>, are
                  implementation-defined.</imp-def-feature></div3><div3 id="invoking-initial-mode"><head>Apply-Templates Invocation</head><p><termdef id="dt-initial-match-selection" term="initial match selection">A stylesheet may be evaluated by supplying a
                     value to be processed, together with an <termref def="dt-initial-mode"/>. The
                     value (which can be any sequence of items) is referred to as the <term>initial
                        match selection</term>. The processing then corresponds to the effect of the
                        <elcode>xsl:apply-templates</elcode> instruction.</termdef></p><p>The <termref def="dt-initial-match-selection"/> will
                  often be a single document node, traditionally called the source document of the
                  transformation; but in general, it can be any sequence. If the initial match selection is the empty sequence, the result of the
                     transformation will be empty, since no template rules are
                  evaluated.</p><p>Processing proceeds by finding the <termref def="dt-template-rule">template rules</termref> that match the items in the
                     <termref def="dt-initial-match-selection"/>, and evaluating these template
                  rules with a <termref def="dt-focus"/> based on the <termref def="dt-initial-match-selection"/>. The template rules are evaluated in
                     <termref def="dt-final-output-state"/>.</p><p>The following information is needed when dynamic evaluation is
                  to start with a <termref def="dt-template-rule"/>:</p><ulist><item><p>The <termref def="dt-initial-match-selection"/>.
                        An API that chooses to maintain compatibility with previous versions of this
                        specification <rfc2119>should</rfc2119> allow a method of invocation in which a singleton node is
                        provided, which is then used in two ways: the node itself acts as the
                           <termref def="dt-initial-match-selection"/>, and the root node of the
                        containing tree acts as the <termref def="dt-global-context-item"/>. </p></item><item><p>Optionally, an initial <termref def="dt-mode">mode</termref>.</p><p><termdef id="dt-initial-mode" term="initial mode">The <term>initial mode</term>
                        is the <termref def="dt-mode">mode</termref> used to select <termref def="dt-template-rule">template rules</termref>
                     for processing items in the <termref def="dt-initial-match-selection"/> when
                     apply-templates invocation is used to initiate a transformation.</termdef></p><p>In searching
                           for the <termref def="dt-template-rule">template rule</termref> that best
                           matches the items in the <termref def="dt-initial-match-selection"/>, the processor
                           considers only those rules that apply to the <termref def="dt-initial-mode"/>.</p><p>If no <termref def="dt-initial-mode"/> is supplied explicitly, then the initial mode is that named in the
                              <code nobreak="false">default-mode</code> attribute of the (explicit or implicit) <elcode>xsl:package</elcode>
                              element of the <termref def="dt-top-level-package"/> or in
                           the absence of such an attribute, the <termref def="dt-unnamed-mode"/>.</p><p>
                        <error spec="XT" type="dynamic" class="DE" code="0044"><p>It is a <termref def="dt-dynamic-error">dynamic error</termref> if the
                              invocation of the <termref def="dt-stylesheet">stylesheet</termref>
                              specifies an <termref def="dt-initial-mode"/> when no <termref def="dt-initial-match-selection"/> is
                                 supplied (either explicitly, or defaulted to the <termref def="dt-global-context-item"/>).</p></error>
                     </p><p>A (named or unnamed) <termref def="dt-mode"/> <var>M</var> is <term>eligible as an initial mode</term> if one of the
                        following conditions applies, where <var>P</var> is the <termref def="dt-top-level-package"/> of the stylesheet:</p><olist><item><p><var>M</var> is explicitly declared in an <elcode>xsl:mode</elcode> declaration
                           within <var>P</var>, and has <code nobreak="false">public</code> or <code nobreak="false">final</code> <termref def="dt-visibility"/> (either by virtue
                           of its <code nobreak="false">visibility</code> attribute, or by virtue of an <elcode>xsl:expose</elcode> declaration).</p></item><item><p><var>M</var> is the unnamed mode.</p></item><item><p><var>M</var> is named in the <code nobreak="false">default-mode</code> attribute of the (explicit or implicit) 
                           <elcode>xsl:package</elcode> element of <var>P</var>.</p></item><item><p><var>M</var> is declared in a package used by <var>P</var>, and is given <code nobreak="false">public</code> or <code nobreak="false">final</code>
                           <termref def="dt-visibility"/> in <var>P</var> by means of an <elcode>xsl:accept</elcode> declaration.</p></item><item><p>The <termref def="dt-effective-value"/> of the <code nobreak="false">declared-modes</code> attribute of the explicit or implicit
                        <elcode>xsl:package</elcode> element of <var>P</var> is <code nobreak="false">no</code>, and <var>M</var> appears as 
                        a mode-name in the <code nobreak="false">mode</code> attribute of a <termref def="dt-template-rule"/> declared within <var>P</var>.</p></item></olist><p>
                        <error spec="XT" type="dynamic" class="DE" code="0045"><p>It is a <termref def="dt-dynamic-error">dynamic error</termref> if the
                              invocation of the <termref def="dt-stylesheet">stylesheet</termref>
                              specifies an <termref def="dt-initial-mode"/> and the
                              specified mode is not eligible as an initial mode (as defined above).</p></error>
                     </p></item><item><p>Parameters, which will be passed to the template rules
                        used to process items in the input sequence. The parameters consist of two
                        sets of (QName, value) pairs, one set for <termref def="dt-tunnel-parameter">tunnel parameters</termref> and one for non-tunnel parameters, in which
                        the QName identifies the name of a parameter and the value provides the
                        value of the parameter. Either or both sets of parameters may be empty. The
                        effect is the same as when a template is invoked using
                           <elcode>xsl:apply-templates</elcode> with an
                           <elcode>xsl:with-param</elcode> child specifying
                           <code nobreak="false">tunnel="yes"</code> or <code nobreak="false">tunnel="no"</code> as appropriate. If
                        a parameter is supplied that is not declared or used, the value is simply
                        ignored. These parameters are <emph>not</emph> used to set <termref def="dt-stylesheet-parameter">stylesheet parameters</termref>.</p><p>A supplied value is converted if necessary to the declared
                        type of the template parameter using the <termref def="dt-coercion-rules"/>.</p></item><item><p>Details of how the result of the initial template is to be returned.
                     For details, see <specref ref="post-processing"/></p></item></ulist><p>The <termref def="dt-raw-result"/> of the invocation is the
                  result of processing the supplied input sequence as if by a call on
                     <elcode>xsl:apply-templates</elcode> in the specified mode: specifically, each
                  item in the input sequence is processed by selecting and evaluating the best
                  matching template rule, and converting the result (if necessary) to the type
                  declared in the <code nobreak="false">as</code> attribute of that template using the <termref def="dt-coercion-rules"/>; and the results of processing each item
                  are then concatenated into a single sequence, respecting the order of items in the
                  input sequence.</p><note><p>The design of the API for invoking a transformation should provide some means
                     for users to designate the <termref def="dt-unnamed-mode"/> as the <termref def="dt-initial-mode"/> 
                     in cases where it is not the <termref def="dt-default-mode"/>.</p></note><p>It is a <termref def="dt-dynamic-error"/>
                  <errorref spec="XT" type="dynamic" class="DE" code="0700"/> if the <termref def="dt-template-rule"/> selected for processing any item in the <termref def="dt-initial-match-selection"/> defines a <termref def="dt-template-parameter"/> that specifies <code nobreak="false">required="yes"</code>
                  and no value is supplied for that
                  parameter.</p><note><p>A <termref def="dt-stylesheet">stylesheet</termref> can process further source
                     documents in addition to those supplied when the transformation is invoked.
                     These additional documents can be loaded using the functions
                        <function>document</function> (see <specref ref="func-document"/>); or
                     <xfunction>doc</xfunction>, <xfunction>unparsed-text</xfunction>, <xfunction>unparsed-text-lines</xfunction>, or <xfunction>collection</xfunction> (see <bibref ref="xpath-functions-40"/>); or using the
                           <elcode>xsl:source-document</elcode> instruction; alternatively, they can
                     be supplied as <termref def="dt-stylesheet-parameter">stylesheet
                        parameters</termref> (see <specref ref="global-variables"/>), or returned as
                     the result of an <termref def="dt-extension-function">extension
                        function</termref> (see <specref ref="extension-functions"/>).</p></note></div3><div3 id="invoking-initial-template"><head>Call-Template Invocation</head><p><termdef id="dt-initial-named-template" term="initial named template">A stylesheet may be evaluated by selecting a
                     named template to be evaluated; this is referred to as the <term>initial named
                        template</term>.</termdef> The effect is analogous to the effect of
                  executing an <elcode>xsl:call-template</elcode> instruction. The following
                  information is needed in this case:</p><ulist><item><p>Optionally, the name of the <termref def="dt-initial-named-template">initial
                           named template</termref> which is to be executed as the entry point to
                        the transformation. If no template name is
                           supplied, the default template name is
                           <code nobreak="false">xsl:initial-template</code>. The selected template
                           <rfc2119>must</rfc2119> exist within the <termref def="dt-stylesheet">stylesheet</termref>. </p></item><item><p>Optionally, a context item for evaluation of this named
                        template, defaulting to the <termref def="dt-global-context-item"/> if it
                        exists. This is constrained by any
                              <elcode>xsl:context-item</elcode> element appearing within the
                           selected <elcode>xsl:template</elcode> element. The initial named
                           template is evaluated with a <termref def="dt-singleton-focus"/> based on
                           this context item if it exists, or with an <termref def="dt-absent"/>
                           focus otherwise.</p><note diff="add" at="2023-10-30"><p>The context item for evaluation of the named
                     template must be either a single item or absent; it cannot be an arbitrary value.</p></note></item><item><p>Parameters, which will be passed to the selected template
                        rule. The parameters consist of two sets of (QName, value) pairs, one set
                        for <termref def="dt-tunnel-parameter">tunnel parameters</termref> and one
                        for non-tunnel parameters, in which the QName identifies the name of a
                        parameter and the value provides the value of the parameter. Either or both
                        sets of parameters may be empty. The effect is the same as when a template
                        is invoked using <elcode>xsl:call-template</elcode> with an
                           <elcode>xsl:with-param</elcode> child specifying
                           <code nobreak="false">tunnel="yes"</code> or <code nobreak="false">tunnel="no"</code> as appropriate. If
                        a parameter is supplied that is not declared or used, the value is simply
                        ignored. These parameters are <emph>not</emph> used to set <termref def="dt-stylesheet-parameter">stylesheet parameters</termref>.</p><p>A supplied value is converted if necessary to the declared
                        type of the template parameter using the <termref def="dt-coercion-rules"/>.</p></item><item><p>Details of how the result of the initial named template is to be returned.
                        For details, see <specref ref="post-processing"/></p></item></ulist><p>The <termref def="dt-raw-result"/> of the invocation is the
                  result of evaluating the <termref def="dt-initial-named-template"/>, after
                  conversion of the result to the type declared in the <code nobreak="false">as</code> attribute of
                  that template using the <termref def="dt-coercion-rules"/>, if such
                  conversion is necessary.</p><p>The <termref def="dt-initial-named-template"/> is
                  evaluated in <termref def="dt-final-output-state"/>.</p><p>
                  <error spec="XT" type="dynamic" class="DE" code="0040"><p>It is a <termref def="dt-dynamic-error"> dynamic error</termref> if the invocation of
                        the <termref def="dt-stylesheet">stylesheet</termref> specifies a template
                        name that does not match the <termref def="dt-expanded-qname">expanded
                           QName</termref> of a named template defined in the <termref def="dt-stylesheet">stylesheet</termref>, whose
                           visibility is <code nobreak="false">public</code> or <code nobreak="false">final</code>.</p></error>
               </p><note diff="add" at="2022-01-01"><p>When the top-level package is rooted at an <elcode>xsl:stylesheet</elcode> or 
                     <elcode>xsl:transform</elcode> element, named templates having no explicit 
                     <code nobreak="false">visibility</code> attribute are automatically exposed as public components. 
                     (This is a consequence of the transformation applied to a package written using 
                     “simplified syntax”, described in <specref ref="packages"/>.) </p></note><p> It is a <termref def="dt-dynamic-error"> dynamic error</termref>
                  <errorref spec="XT" type="dynamic" class="DE" code="0700"/> if the <termref def="dt-initial-named-template">initial named template</termref>, or any of the template rules invoked to
                  process items in the <termref def="dt-initial-match-selection"/>, defines a
                     <termref def="dt-template-parameter">template parameter</termref> that
                  specifies <code nobreak="false">required="yes"</code>
                  and no value is supplied for that parameter.
               </p></div3><div3 id="invoking-initial-function"><head>Function Call Invocation</head><p><termdef id="dt-initial-function" term="initial function">A stylesheet may be evaluated by calling a named
                        <termref def="dt-stylesheet-function"/>, referred to as the <term>initial
                        function</term>.</termdef> The following additional information is needed in
                  this case:</p><ulist><item><p>The name and arity of a <termref def="dt-stylesheet-function"/> which is to
                        be executed as the entry point to the transformation.</p><note><p>In the design of a concrete API, the arity may be inferred from the
                           length of the parameter list.</p></note></item><item><p>A list of values to act as parameters to the <termref def="dt-initial-function"/>. The number of values in the list must be the
                        same as the arity of the function.</p><p>A supplied value is converted if necessary to the declared
                        type of the function parameter using the <termref def="dt-coercion-rules"/>.</p></item><item><p>Details of how the result of the initial function is to be returned.
                        For details, see <specref ref="post-processing"/></p></item></ulist><p>The <termref def="dt-raw-result"/> of the invocation is the
                  result of evaluating the <termref def="dt-initial-function"/>, after conversion of
                  the result to the type declared in the <code nobreak="false">as</code> attribute of that function
                  using the <termref def="dt-coercion-rules"/>, if such conversion is
                  necessary.</p><note><p> The <termref def="dt-initial-function"/> (like all stylesheet functions) is
                     evaluated with an <termref def="dt-absent"/>
                     <termref def="dt-focus"/>.</p></note><p>If the <termref def="dt-initial-function"/> is 
                  <xtermref spec="SG40" ref="dt-declared-streamable"/>, a streaming processor <rfc2119>should</rfc2119> 
                  allow the value of the first argument to be supplied in streamable form, and if it is 
                  supplied in this form, then it <rfc2119>must</rfc2119> be processed using streaming.</p><p>
                  <error spec="XT" type="dynamic" class="DE" code="0041"><p>It is a <termref def="dt-dynamic-error"/> if the invocation of the <termref def="dt-stylesheet">stylesheet</termref> specifies a function name and
                        arity that does not match the <termref def="dt-expanded-qname">expanded
                           QName</termref> and arity of a named <termref def="dt-stylesheet-function"/> defined in the <termref def="dt-stylesheet">stylesheet</termref>, whose visibility is
                           <code nobreak="false">public</code> or <code nobreak="false">final</code>.</p></error>
               </p><p>When a transformation is invoked by calling an <termref def="dt-initial-function"/>, the entire transformation executes in <termref def="dt-temporary-output-state"/>, which means that calls on
                     <elcode>xsl:result-document</elcode> are not permitted.</p><p>[TODO: Generalize the above description to allow for the possibility of keyword-based and optional arguments.]</p></div3><div3 id="post-processing"><head>Post-processing the Raw Result</head><p>There are three ways the result of a transformation
               may be delivered. (This applies both to the principal result, described here, and
               also to secondary results, generated using <elcode>xsl:result-document</elcode>.)</p><olist><item><p>The <termref def="dt-raw-result"/> (a sequence of values) may be returned
                  directly to the calling application.</p></item><item><p>A result tree may be constructed from the <termref def="dt-raw-result"/>.
                     By default, a result tree is constructed if the <code nobreak="false">build-tree</code>
                     attribute of the unnamed <termref def="dt-output-definition"/>
                     has the <termref def="dt-effective-value"/> <code nobreak="false">yes</code>. An API for invoking transformations <rfc2119>may</rfc2119>
                     allow this setting to be overridden by the calling application. If result tree construction
                     is requested, it is performed as described in <specref ref="result-tree-construction"/>.
                   </p></item><item><p>Alternatively, the <termref def="dt-raw-result"/> may be serialized
                  as described in <specref ref="result-serialization"/>. The decision whether or not to
                  serialize the result is determined by the rules of transformation API provided by the
                  <termref def="dt-processor"/>, and is not influenced by anything in the stylesheet.</p></item></olist><note><p>This specification does not constrain the design of application programming
                     interfaces or the choice of defaults. In previous versions of this
                     specification, result tree construction was a mandatory process, while
                     serialization was optional. When invoking stylesheet functions directly,
                     however, result tree construction and serialization may be inappropriate as
                     defaults. These considerations may affect the design of APIs.</p><p>In previous versions of XSLT, results were delivered either
                  in serialized form (as a character or byte stream), or as a tree. In the latter case processors
                  typically would use either their own tree representation, or a standardized tree
                  representation such as the W3C Document Object Model (DOM) (see <bibref ref="DOM-Level-2-Core"/>),
                     adapted to the data structures offered by the programming language in which the API is defined.
                  To deliver a raw result, processors need to define a representation not only of XDM nodes but
                  also of sequences, atomic items, maps, arrays, and even functions. As with the return of a simple tree, 
                  this may involve a trade-off between strict fidelity to the XDM data model and usability in the particular 
                  programming language environment. It is <emph>not</emph> a requirement that an API should return results 
                     in a way that exposes every property of the XDM data model; for example there may be APIs that do not expose
                  the precise type annotation of a returned node or atomic item, or that fail to expose the base URI
                  or document URI of a node, or that provide no way of determining whether two nodes in the result
                  sequence are the same node in the sense of the XPath <code nobreak="false">is</code> operator.
                     The way in which maps, arrays, and functions 
                  are returned requires careful design choices. It is <rfc2119>recommended</rfc2119> that an API should be capable
                  of returning any XDM value without error, and that there should be minimal loss of information if
                  the raw results output by one transformation are subsequently used as input to another transformation.</p></note><div4 id="result-tree-construction"><head>Result Tree Construction</head><p>If a result tree is to be constructed from the <termref def="dt-raw-result"/>, then this is done
    by applying the rules for the process of <xtermref spec="SE40" ref="sequence-normalization"/> as defined in 
       <bibref ref="xslt-xquery-serialization-40"/>. This process takes as input the serialization parameters defined in the
    unnamed <termref def="dt-output-definition"/> of the <termref def="dt-top-level-package"/>; though the only parameter
    that is actually used by this process is <code nobreak="false">item-separator</code>. <phrase diff="del" at="2022-01-01">In particular, sequence normalization is carried
       out regardless of any <code nobreak="false">method</code> attribute in the unnamed <termref def="dt-output-definition"/>.</phrase>
    </p><p>The sequence normalization process either returns a document node, or raises
    a serialization error. The content of the document node is not necessarily well-formed (the document node may have any number
    of element or text nodes among its children).</p><note><p>More specifically, the process raises a serialization error if any item in the <termref def="dt-raw-result"/> is
    an attribute node, a namespace node, or a function (including a map, but not an array: arrays are flattened).</p></note><p>The tree that is constructed is referred to as a <termref def="dt-final-result-tree">final result tree</termref>.</p><p>If the <termref def="dt-raw-result"/> is the empty sequence, the <termref def="dt-final-result-tree"/> will consist
    of a document node with no children.</p><p>The base URI of the document node is set to the <termref def="dt-base-output-uri"/>.</p><note><p>The <code nobreak="false">item-separator</code> property has no effect if the raw result of the transformation is a sequence
       of length zero or one, which in practice will often be the case, especially in a traditional scenario such as
       transformation of an XML document to HTML.</p><p>If there is no <code nobreak="false">item-separator</code>, then a single space is inserted between adjacent atomic items;
       for example if the raw result is the sequence <code nobreak="false">1 to 5</code>, then sequence normalization produces a tree
       comprising a document node with a single child, the child being a text node with the string value 
       <code nobreak="false">1 2 3 4 5</code>.</p><p>If there is an <code nobreak="false">item-separator</code>, then it is used not only between adjacent atomic items,
       but between any pair of items in the raw result. For example if the raw result is a sequence of two
       element nodes <code nobreak="false">A</code> and <code nobreak="false">B</code>, and the <code nobreak="false">item-separator</code> is a comma,
       then the result of sequence normalization will be a document node with three children: a copy of <code nobreak="false">A</code>,
       a text node whose string value is a single comma, and a copy of <code nobreak="false">B</code>.</p></note></div4><div4 id="result-serialization"><head>Serializing the Result</head><p>See <specref ref="parsing-and-serialization"/>.</p><p>The <termref def="dt-raw-result"/>
                        may optionally be serialized as described in <specref ref="serialization"/>. The serialization is controlled by the serialization
                     parameters defined in the unnamed <termref def="dt-output-definition"/> of the
                     <termref def="dt-top-level-package"/>.</p><note><p>The first phase of serialization, called <xtermref spec="SE40" ref="sequence-normalization"/>,
                     takes place for some output methods but not others. For example, if the <code nobreak="false">json</code> output method
                        (defined in <bibref ref="xslt-xquery-serialization-40"/>) is selected, then the process of constructing
                     a tree is bypassed.</p></note><p>The effect of serialization is to generate a sequence of octets, representing the serialized result
                     in some character encoding. The processor’s API may define mechanisms enabling this sequence of octets
                  to be written to persistent storage at some location. The default location is the location identified
                  by the <termref def="dt-base-output-uri"/>.</p><p>In previous versions of this specification it was stated that
                  when the <termref def="dt-raw-result"/> of the initial template or function is the empty sequence,
                  a result tree should be produced if and only if the transformation generates no secondary results
                  (that is, if it does not invoke <elcode>xsl:result-document</elcode>). This provision is most likely
                  to have a noticeable effect if the transformation produces serialized results, and these results
                  are written to persistent storage: the effect is then that a transformation producing the empty
                  principal result will overwrite any existing content at the base output URI location if and only
                  if the transformation produces no other output. Processor APIs offering backwards compatibility
                  with earlier versions of XSLT must respect this behavior, but there is no requirement for new
                  processor APIs to do so.</p><p><termdef id="dt-base-output-uri" term="base output URI"> The <term>base output URI</term> is a URI to be used as the base URI when
                     resolving a relative URI reference allocated
                     to a <termref def="dt-final-result-tree">final result tree</termref>. If the
                     transformation generates more than one final result tree, then typically each
                     one will be allocated a URI relative to this base URI.</termdef> The way in
                  which a base output URI is established is <termref def="dt-implementation-defined">implementation-defined</termref>. Each invocation of the stylesheet may supply
                  a different base output URI. It is acceptable for the base output URI to be
                     <termref def="dt-absent"/>, provided no constructs (such as
                     <elcode>xsl:result-document</elcode>) are evaluated that depend on the value of
                  the base output URI.</p><note><p>It will often be convenient for the base output URI to be the same as the
                     location to which the principal result document is serialized, but this
                     relationship is not a necessary one.</p></note><imp-def-feature id="idf-api-baseoutputuri">The way in which a <termref def="dt-base-output-uri"/> is established is <termref def="dt-implementation-defined">implementation-defined</termref></imp-def-feature></div4></div3></div2><div2 id="executing-a-transformation"><head>Instructions</head><p>The main executable components of a stylesheet are templates and functions. The body of
            a template or function is a <termref def="dt-sequence-constructor"/>, which is a sequence of elements
            and text nodes that can be evaluated to produce a result.</p><p>A <termref def="dt-sequence-constructor"/> is a sequence of sibling nodes in the
               stylesheet, each of which is either an <termref def="dt-xslt-instruction">XSLT
                  instruction</termref>, a <termref def="dt-literal-result-element">literal result
                     element</termref>, a text node, or an <termref def="dt-extension-instruction">extension instruction</termref>.</p><p>
               <termdef id="dt-instruction" term="instruction">An <term>instruction</term> is either
                  an <termref def="dt-xslt-instruction">XSLT instruction</termref> or an <termref def="dt-extension-instruction">extension instruction</termref>.</termdef>
            </p><p>
               <termdef id="dt-xslt-instruction" term="XSLT instruction">An <term>XSLT
                  instruction</term> is an <termref def="dt-xslt-element">XSLT element</termref>
                  whose syntax summary in this specification contains the annotation <code nobreak="false">&lt;!--
                     category: instruction --&gt;</code>.</termdef>
            </p><p>
               <termref def="dt-extension-instruction">Extension instructions</termref> are
               described in <specref ref="extension-instruction"/>.</p><p>The main categories of <termref def="dt-xslt-instruction">XSLT instruction</termref>
               are as follows:</p><ulist><item><p>instructions that create new nodes: <elcode>xsl:document</elcode>,
                     <elcode>xsl:element</elcode>, <elcode>xsl:attribute</elcode>,
                     <elcode>xsl:processing-instruction</elcode>, <elcode>xsl:comment</elcode>,
                     <elcode>xsl:value-of</elcode>, <elcode>xsl:text</elcode>,
                     <elcode>xsl:namespace</elcode>;</p></item><item><p>instructions that construct maps and arrays: <elcode>xsl:array</elcode>,
                      <elcode>xsl:map</elcode>, <elcode>xsl:map-entry</elcode>, <elcode>xsl:record</elcode>;</p></item><item><p>instructions that copy nodes: <elcode>xsl:copy</elcode>,
                     <elcode>xsl:copy-of</elcode>;</p></item><item><p>instructions that returns an arbitrary sequence by evaluating an XPath
                     expression: <elcode>xsl:sequence</elcode>, <elcode>xsl:select</elcode>,
                     <elcode>xsl:evaluate</elcode>;</p></item><item><p>instructions that cause conditional or repeated evaluation of nested
                     instructions: <elcode>xsl:if</elcode>, <elcode>xsl:choose</elcode>, 
                     <elcode>xsl:switch</elcode>, <elcode>xsl:try</elcode>,
                     <elcode>xsl:for-each</elcode>, <elcode>xsl:for-each-group</elcode>, <elcode>xsl:fork</elcode>, 
                     <elcode>xsl:iterate</elcode>
                        and its subordinate instructions <elcode>xsl:next-iteration</elcode> and
                        <elcode>xsl:break</elcode>;</p></item><item><p>instructions that generate output conditionally if elements are or are not
                     empty: <elcode>xsl:on-empty</elcode>, <elcode>xsl:on-non-empty</elcode>,
                     <elcode>xsl:where-populated</elcode>;</p></item><item><p>instructions that invoke templates: <elcode>xsl:apply-templates</elcode>,
                     <elcode>xsl:apply-imports</elcode>, <elcode>xsl:call-template</elcode>,
                     <elcode>xsl:next-match</elcode>;</p></item><item><p>Instructions that declare variables: <elcode>xsl:variable</elcode>;</p></item><item><p>Instructions to assist debugging: <elcode>xsl:message</elcode>,
                     <elcode>xsl:assert</elcode>;</p></item><item><p>other specialized instructions: <elcode>xsl:number</elcode>,
                     <elcode>xsl:analyze-string</elcode>, <elcode>xsl:fork</elcode>, 
                     <elcode>xsl:result-document</elcode>, <elcode>xsl:source-document</elcode>, <elcode>xsl:perform-sort</elcode>,
                        <elcode>xsl:merge</elcode>.</p></item></ulist></div2><div2 id="rule-based-processing"><head>Rule-Based Processing</head><p>The classic method of executing an XSLT transformation is to apply
               template rules to the root node of an input document (see <specref ref="invoking-initial-mode"/>).
               The operation of applying templates to a node searches the stylesheet for the best matching template
               rule for that node. This template rule is then evaluated. A common coding pattern, especially when XSLT
               is used to convert XML documents into display formats such as HTML, is to have one template rule 
               for each kind of element in the source document, and for that template rule to generate some 
               appropriate markup elements, and to apply templates recursively to its own children. The effect is to 
               perform a recursive traversal of the source tree, in which each node is processed using the best-fit 
               template rule for that node. The final result of the transformation is then the tree produced by this 
               recursive process. This result can then be optionally serialized (see <specref ref="post-processing"/>). 
            </p><example id="rule-based-processing-example"><head>Example of Rule-Based Processing</head><p>This example uses rule-based processing to convert a simple XML input document into an HTML
               output document.</p><p>The input document takes the form:</p><eg role="xml" xml:space="preserve">

  &lt;PERSONAE PLAY="OTHELLO"&gt;
    &lt;TITLE&gt;Dramatis Personae&lt;/TITLE&gt;
    &lt;PERSONA&gt;DUKE OF VENICE&lt;/PERSONA&gt;
    &lt;PERSONA&gt;BRABANTIO, a senator.&lt;/PERSONA&gt;
    &lt;PERSONA&gt;Other Senators.&lt;/PERSONA&gt;
    &lt;PERSONA&gt;GRATIANO, brother to Brabantio.&lt;/PERSONA&gt;
    &lt;PERSONA&gt;LODOVICO, kinsman to Brabantio.&lt;/PERSONA&gt;
    &lt;PERSONA&gt;OTHELLO, a noble Moor in the service of the Venetian state.&lt;/PERSONA&gt;
    &lt;PERSONA&gt;CASSIO, his lieutenant.&lt;/PERSONA&gt;
    &lt;PERSONA&gt;IAGO, his ancient.&lt;/PERSONA&gt;
    &lt;PERSONA&gt;RODERIGO, a Venetian gentleman.&lt;/PERSONA&gt;
    &lt;PERSONA&gt;MONTANO, Othello's predecessor in the government of Cyprus.&lt;/PERSONA&gt;
    &lt;PERSONA&gt;Clown, servant to Othello. &lt;/PERSONA&gt;
    &lt;PERSONA&gt;DESDEMONA, daughter to Brabantio and wife to Othello.&lt;/PERSONA&gt;
    &lt;PERSONA&gt;EMILIA, wife to Iago.&lt;/PERSONA&gt;
    &lt;PERSONA&gt;BIANCA, mistress to Cassio.&lt;/PERSONA&gt;
    &lt;PERSONA&gt;Sailor, Messenger, Herald, Officers, 
             Gentlemen, Musicians, and Attendants.&lt;/PERSONA&gt;
  &lt;/PERSONAE&gt;</eg><p>The stylesheet to render this as HTML can be written as a set of template rules:</p><eg role="xslt" xml:space="preserve">
 &lt;xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    version="3.0"
    expand-text="yes"&gt;
    
 &lt;xsl:strip-space elements="PERSONAE"/&gt;   
    
 &lt;xsl:template match="PERSONAE"&gt;
   &lt;html&gt;
     &lt;head&gt;
       &lt;title&gt;The Cast of {@PLAY}&lt;/title&gt;
     &lt;/head&gt;
     &lt;body&gt;
       &lt;xsl:apply-templates/&gt;
     &lt;/body&gt;
   &lt;/html&gt;
 &lt;/xsl:template&gt;
 
 &lt;xsl:template match="TITLE"&gt;
   &lt;h1&gt;{.}&lt;/h1&gt;
 &lt;/xsl:template&gt;
 
 &lt;xsl:template match="PERSONA[count(tokenize(., ',')) = 2]"&gt;
   &lt;p&gt;&lt;b&gt;{substring-before(., ',')}&lt;/b&gt;: {substring-after(., ',')}&lt;/p&gt;
 &lt;/xsl:template&gt; 

 &lt;xsl:template match="PERSONA"&gt;
   &lt;p&gt;&lt;b&gt;{.}&lt;/b&gt;&lt;/p&gt;
 &lt;/xsl:template&gt;

&lt;/xsl:stylesheet&gt;</eg><p>There are four template rules here:</p><ulist><item><p>The first rule matches the outermost element, named <code nobreak="false">PERSONAE</code> (it could equally
                  have used <code nobreak="false">match="/"</code> to match the document node). The effect of this rule is to create
                  the skeleton of the output HTML page. Technically, the body of the template is a sequence constructor
                  comprising a single <termref def="dt-literal-result-element"/> (the <code nobreak="false">html</code> element); this
                  in turn contains a sequence constructor comprising two literal result elements (the <code nobreak="false">head</code>
                  and <code nobreak="false">body</code> elements). The <code nobreak="false">head</code> element is populated with a literal <code nobreak="false">title</code>
                     element whose content is computed as a mixture of fixed and variable text using a <termref def="dt-text-value-template"/>. 
                     The <code nobreak="false">body</code> element is populated by evaluating an <elcode>xsl:apply-templates</elcode>
                  instruction.</p><p>The effect of the <elcode>xsl:apply-templates</elcode> instruction is to process the children of
                     the <code nobreak="false">PERSONAE</code> element in the source tree: that is, the <code nobreak="false">TITLE</code> and
                     <code nobreak="false">PERSONA</code> elements. (It would also process any whitespace text node children, but these
                     have been stripped by virtue of the <elcode>xsl:strip-space</elcode> declaration.) Each of these
                     child elements is processed by the best matching template rule for that element, which will be one 
                     of the other three rules in the stylesheet.</p></item><item><p>The template rule for the <code nobreak="false">TITLE</code> element outputs an <code nobreak="false">h1</code> element
                  to the HTML result document, and populates this with the value of <code nobreak="false">.</code>, the context item. That is,
                  it copies the text content of the <code nobreak="false">TITLE</code> element to the output <code nobreak="false">h1</code> element.</p></item><item><p>The last two rules match <code nobreak="false">PERSONA</code> elements. The first rule matches <code nobreak="false">PERSONA</code>
                  elements whose text content contains exactly one comma; the second rule matches all <code nobreak="false">PERSONA</code> elements,
                     but it has lower priority than the first rule (see <specref ref="default-priority"/>), so in practice it 
                     applies only to <code nobreak="false">PERSONA</code>
                  elements that contain no comma or multiple commas.</p><p>For both rules the body of the rule is a sequence constructor containing a single literal result element,
                  the <code nobreak="false">p</code> element. These literal result elements contain
                  further sequence constructors comprising literal result elements and text nodes. 
                  In each of these examples the text nodes are in the form of a <termref def="dt-text-value-template"/>:
                  in general this is a combination of fixed text together with XPath expressions enclosed in curly braces, which 
                  are evaluated to form the content of the containing literal result element. </p></item></ulist></example><p>
               <termdef id="dt-template-rule" term="template rule">A stylesheet contains a set of
                  <term>template rules</term> (see <specref ref="rules"/>). A template rule has
                  three parts: a <termref def="dt-pattern">pattern</termref> that is matched against
                  selected items (often but not necessarily nodes), a (possibly empty) set of <termref def="dt-template-parameter">template
                     parameters</termref>, and a <termref def="dt-sequence-constructor">sequence
                        constructor</termref> that is evaluated to produce a sequence of
                  items.</termdef> In many cases these items are newly constructed nodes, which are
               then written to a <termref def="dt-result-tree">result tree</termref>.</p></div2><div2 id="context"><head>The Evaluation Context</head><p>The results of some expressions and instructions in a stylesheet may depend on
               information provided contextually. This context information is divided into two
               categories: the static context, which is known during static analysis of the
               stylesheet, and the dynamic context, which is not known until the stylesheet is
               evaluated. Although information in the static context is known at analysis time, it
               is sometimes used during stylesheet evaluation.</p><p>Some context information can be set by means of declarations within the stylesheet
               itself. For example, the namespace bindings used for any XPath expression are
               determined by the namespace declarations present in containing elements in the
               stylesheet. Other information may be supplied externally or implicitly: an example is
               the current date and time.</p><p>The context information used in processing an XSLT stylesheet includes as a subset
               all the context information required when evaluating XPath expressions. 
               The XPath 4.0 specification defines a static and dynamic
               context that the host language (in this case, XSLT) may initialize, which affects the
               results of XPath expressions used in that context. XSLT augments the context with
               additional information: this additional information is used firstly by XSLT
               constructs outside the scope of XPath (for example, the <elcode>xsl:sort</elcode>
               element), and secondly, by functions that are defined in the XSLT specification (such
               as <function>key</function> and <function>current-group</function>) that are
               available for use in XPath expressions appearing within a stylesheet.</p><p>The static context for an expression or other construct in a stylesheet is determined
               by the place in which it appears lexically. The details vary for different components
               of the static context, but in general, elements within a stylesheet module affect the
               static context for their descendant elements within the same stylesheet module.</p><p>The dynamic context is maintained as a stack. When an instruction or expression is
               evaluated, it may add dynamic context information to the stack; when evaluation is
               complete, the dynamic context reverts to its previous state. An expression that
               accesses information from the dynamic context always uses the value at the top of the
               stack.</p><p>The most commonly used component of the dynamic context is the <termref def="dt-context-item"/>. This is an implicit variable whose
               value is the item currently being processed (it may be a node, an atomic item,
                  or a function item). The value of the context
               item can be referenced within an XPath expression using the expression <code nobreak="false">.</code>
               (dot).</p><p diff="add" at="2023-10-30">XPath 4.0 generalizes the <termref def="dt-context-item"/> so it can be any value (not necessarily a single item),
            and it is now known as the <xtermref spec="XP40" ref="dt-context-value"/>. In certain XPath expressions, the
            value of the expression <code nobreak="false">.</code> can now be an arbitrary value, rather than a single item. However, there
            is currently no construct in XSLT 4.0 that takes advantage of this; in the context supplied by XSLT to XPath
            (except when using the <elcode>xsl:evaluate</elcode> instruction),
            the context value is always either a single item, or absent. The XSLT specification therefore continues to refer
            to the <termref def="dt-context-item"/> rather than the <xtermref spec="XP40" ref="dt-context-value"/>.</p><p>Full details of the static and dynamic context are provided in <specref ref="static-and-dynamic-context"/>.</p></div2><div2 id="parsing-and-serialization"><head>Parsing and Serialization</head><p>An XSLT <termref def="dt-stylesheet">stylesheet</termref>
               describes a process that constructs a set of results from a set of inputs. The inputs
               are the data provided at stylesheet invocation, as described in <specref ref="initiating"/>. The results include the <termref def="dt-principal-result"/>
               (an arbitrary sequence), which is the result of the initial component invocation,
               together with any <termref def="dt-secondary-result">secondary results</termref>
               produced using <elcode>xsl:result-document</elcode> instructions. </p><p>The <termref def="dt-stylesheet">stylesheet</termref> does not describe how a
                  <termref def="dt-source-tree">source tree</termref> is constructed. Some possible
               ways of constructing source trees are described in <bibref ref="xpath-datamodel-40"/>. Frequently an <termref def="dt-implementation">implementation</termref> will
               operate in conjunction with an XML parser (or more strictly, in the terminology of
                  <bibref ref="REC-xml"/>, an <emph>XML processor</emph>), to build a source tree
               from an input XML document. An implementation <rfc2119>may</rfc2119> also provide an
               application programming interface allowing the tree to be constructed directly, or
               allowing it to be supplied in the form of a DOM Document object (see <bibref ref="DOM-Level-2-Core"/>). This is outside the scope of this specification. Users
               should be aware, however, that since the input to the transformation is a tree
               conforming to the XDM data model as described in <bibref ref="xpath-datamodel-40"/>,
               constructs that might exist in the original XML document, or in the DOM, but which
               are not within the scope of the data model, cannot be processed by the <termref def="dt-stylesheet">stylesheet</termref> and cannot be guaranteed to remain
               unchanged in the transformation output. Such constructs include CDATA section
               boundaries, the use of entity references, and the DOCTYPE declaration and internal
               DTD subset.</p><p>
               <termdef id="dt-serialization" term="serialization">A frequent requirement is to
                  output a <termref def="dt-final-result-tree">final result tree</termref> as an XML
                  document (or in other formats such as HTML). This process is referred to as
                     <term>serialization</term>.</termdef>
            </p><p>Like parsing, serialization is not part of the transformation process, and it is not
                  <rfc2119>required</rfc2119> that an XSLT processor <rfc2119>must</rfc2119> be able
               to perform serialization. However, for pragmatic reasons, this specification
               describes declarations (the <elcode>xsl:output</elcode> element and the
                  <elcode>xsl:character-map</elcode> declarations, see <specref ref="serialization"/>), and attributes on the <elcode>xsl:result-document</elcode> instruction, that
               allow a <termref def="dt-stylesheet">stylesheet</termref> to specify the desired
               properties of a serialized output file. When serialization is not being performed,
               either because the implementation does not support the serialization option, or
               because the user is executing the transformation in a way that does not invoke
               serialization, then the content of the <elcode>xsl:output</elcode> and
                  <elcode>xsl:character-map</elcode> declarations has no effect. Under these
               circumstances the processor <rfc2119>may</rfc2119> raise any errors in an
                  <elcode>xsl:output</elcode> or <elcode>xsl:character-map</elcode> declaration, or
               in the serialization attributes of <elcode>xsl:result-document</elcode>, but is not
                  <rfc2119>required</rfc2119> to do so.</p></div2><div2 id="packages-and-modules"><head>Packages and Modules</head><p>In XSLT 1.0 and 2.0 it was possible to structure a
               stylesheet as a collection of modules, using the <elcode>xsl:include</elcode> and
                  <elcode>xsl:import</elcode> declarations to express the dependency of one module on
               others.</p><p>In XSLT 3.0 an additional layer of modularization of stylesheet code was enabled
               through the introduction of <termref def="dt-package">packages</termref>. A package
               is a collection of stylesheet modules with a controlled interface to the packages
               that use it: for example, it defines which functions and templates defined in the
               package are visible to callers, which are purely internal, and which are not only
               public but capable of being overridden by other functions and templates supplied by
               the using package.</p><p>Packages are introduced with several motivations, which broadly divide into two
               categories:</p><olist><item><p>Software engineering benefits: greater re-use of code, greater robustness
                     through ease of testing, controlled evolution of code in response to new
                     requirements, ability to deliver code that users cannot see or modify.</p></item><item><p>Efficiency benefits: the ability to avoid compiling libraries repeatedly when
                     they are used in multiple stylesheets, and to avoid holding multiple copies of
                     the same library in memory simultaneously.</p></item></olist><p>Packages are designed to allow separate compilation: that is, a package can be
               compiled independently of the packages that use it. This specification does not
               define a process model for compilation, or expand on what it means to compile
               different packages independently. Nor does it mandate that implementations offer any
               feature along these lines. It merely defines language features that are designed to
               make separate compilation of packages possible.</p><p>To achieve this, packages (unlike modules):</p><ulist><item><p>Must not contain unresolved references to functions, templates, or variables
                     declared in other packages;</p></item><item><p>Have strict rules governing the ability to override declarations in a <termref def="dt-library-package">library package</termref> with declarations in a
                     package that uses the library;</p></item><item><p>Constrain the visibility of component names and of context declarations such as
                     the declarations of keys and decimal formats;</p></item><item><p>Can declare a mode (a collection of template rules) as final, which disallows
                     the addition of new overriding template rules in a using package;</p></item><item><p>Require explicit disambiguation where naming conflicts arise, for example when
                     a package uses two other packages that both export like-named components;</p></item><item><p>Allow multiple specializations of library components to coexist in the same
                     application.</p></item></ulist><p>A package is defined in XSLT
               by means of an XML document whose
               outermost element is an <elcode>xsl:package</elcode> element. This is referred to as
               the <termref def="dt-package-manifest"/>. The <elcode>xsl:package</elcode> element
               has optional child elements <elcode>xsl:use-package</elcode> and
                  <elcode>xsl:expose</elcode> describing properties of the package. The package
               manifest may refer to an external top-level stylesheet module using an
                  <elcode>xsl:include</elcode> or <elcode>xsl:import</elcode> declaration, or it may
               contain the body of a stylesheet module inline (the two approaches can also be
               mixed).</p><p>Although this specification defines packages as constructs 
               written using a defined XSLT syntax, implementations <rfc2119>may</rfc2119> provide mechanisms that allow 
               packages to be written using other languages (for example, XQuery).</p><p>When no packages are explicitly defined, the entire
               stylesheet is treated as a single package; the effect is as if the
                  <elcode>xsl:stylesheet</elcode> or <elcode>xsl:transform</elcode> element of the
                  <termref def="dt-principal-stylesheet-module">principal stylesheet
                  module</termref> were replaced by an <elcode>xsl:package</elcode> element with no
               other information in the package manifest.</p></div2><div2 id="extensibility"><head>Extensibility</head><p>XSLT defines a number of features that allow the language to be extended by
               implementers, or, if implementers choose to provide the capability, by users. These
               features have been designed, so far as possible, so that they can be used without
               sacrificing interoperability. Extensions other than those explicitly defined in this
               specification are not permitted.</p><p>These features are all based on XML namespaces; namespaces are used to ensure that
               the extensions provided by one implementer do not clash with those of a different
               implementer.</p><p>The most common way of extending the language is by providing additional functions,
               which can be invoked from XPath expressions. These are known as 
               <termref def="dt-extension-function">extension functions</termref>, and are described in
                  <specref ref="extension-functions"/>.</p><p>It is also permissible to extend the language by providing new <termref def="dt-instruction">instructions</termref>. 
               These are referred to as <termref def="dt-extension-instruction">extension instructions</termref>, and are described
               in <specref ref="extension-instruction"/>. A stylesheet that uses extension
               instructions in a particular namespace must declare that it is doing so by using the
                  <code nobreak="false">[xsl:]extension-element-prefixes</code> attribute.</p><p>Extension instructions and extension functions defined according to these rules
                  <rfc2119>may</rfc2119> be provided by the implementer of the XSLT processor, and
               the implementer <rfc2119>may</rfc2119> also provide facilities to allow users to
               create further extension instructions and extension functions.</p><p>This specification defines how extension instructions and extension functions are
               invoked, but the facilities for creating new extension instructions and extension
               functions are <termref def="dt-implementation-defined">implementation-defined</termref>. 
               For further details, see <specref ref="extension"/>.</p><imp-def-feature id="idf-ext-mechanisms">The mechanisms for creating new <termref def="dt-extension-instruction">extension instructions</termref> and <termref def="dt-extension-function">extension functions</termref> are <termref def="dt-implementation-defined"/>. It is not <rfc2119>required</rfc2119> that
               implementations provide any such mechanism.</imp-def-feature><p>The XSLT language can also be extended by the use of <termref def="dt-extension-attribute">extension attributes</termref> (see <specref ref="extension-attributes"/>), and by means of <termref def="dt-data-element">user-defined data elements</termref> (see <specref ref="user-defined-top-level"/>).</p></div2><div2 id="stylesheets-and-schemas"><head>Stylesheets and XML Schemas</head><changes><change issue="451" PR="1819" date="2025-02-18">
                  Different parts of a stylesheet may now use different imported schemas.
               </change></changes><p>An XSLT <termref def="dt-stylesheet">stylesheet</termref> can make use of information
               from a schema. An XSLT transformation can take place in the absence of a schema (and,
               indeed, in the absence of a DTD), but where the source document has undergone schema
               validity assessment, the XSLT processor has access to the type information associated
               with individual nodes, not merely to the untyped text.</p><p>Information from a schema can be used both statically (when the <termref def="dt-stylesheet">stylesheet</termref> is compiled), and dynamically (during
               evaluation of the stylesheet to transform a source document).</p><p>There are places within a <termref def="dt-stylesheet">stylesheet</termref>, and
               within XPath <termref def="dt-expression">expressions</termref> and <termref def="dt-pattern">patterns</termref> in a <termref def="dt-stylesheet">stylesheet</termref>, where it is possible to refer to named type definitions in
               a schema, or to element and attribute declarations. For example, it is possible to
               declare the types expected for the parameters of a function. This is done using
               a <termref def="dt-sequence-type"/>.</p><p><termdef id="dt-sequence-type" term="SequenceType">A <term>SequenceType</term>
            constrains the type and number of items in a sequence. The term is used both to denote the
            concept, and to refer to the syntactic form in which sequence types are expressed in the
            XPath grammar: specifically <xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="XP40" ref="prod-xpath40-SequenceType" xlink:type="simple">SequenceType</xnt> in
                <bibref ref="xpath-40"/>.</termdef></p><p>
               <termdef id="dt-schema-component" term="schema component">Type definitions and
                  element and attribute declarations are referred to collectively as <term>schema
                     components</term>.</termdef>
            </p><p>
               <termdef id="dt-in-scope-schema-component" term="in-scope schema component">The
                     <termref def="dt-schema-component">schema components</termref> that may be
                  referenced by name in a <termref def="dt-package">package</termref> are referred to as the
                     <term>in-scope schema components</term>.</termdef></p><p>The set of in-scope schema components may vary between
               one package and another, and between different parts of the same package,
               but as explained in <specref ref="import-schema"/>, the
               schema components used in different parts of the stylesheet 
               must be consistent with each other.</p><p>The conformance rules for XSLT 4.0, defined in
                  <specref ref="conformance"/>, distinguish between a <termref def="dt-basic-xslt-processor">basic XSLT processor</termref> and a <termref def="dt-schema-aware-xslt-processor">schema-aware XSLT processor</termref>. As the
               names suggest, a basic XSLT processor does not support the features of XSLT that
               require access to schema information, either statically or dynamically. A <termref def="dt-stylesheet">stylesheet</termref> that works with a basic XSLT processor
               will produce the same results with a schema-aware XSLT processor provided that the
               source documents are untyped (that is, they are not validated against a schema).
               However, if source documents are validated against a schema then the results may be
               different from the case where they are not validated. Some constructs that work on
               untyped data may fail with typed data (for example, an attribute of type
                  <code nobreak="false">xs:date</code> cannot be used as an argument of the
                  <xfunction>substring</xfunction> function) and other constructs may produce
               different results depending on the datatype (for example, given the element
                  <code nobreak="false">&lt;product price="10.00" discount="2.00"/&gt;</code>, the expression
                  <code nobreak="false">@price gt @discount</code> will return <code nobreak="false">true</code> if the attributes have type
                  <code nobreak="false">xs:decimal</code>, but will return <code nobreak="false">false</code> if they are untyped).</p><p>There is a standard set of type definitions that are always available as <termref def="dt-in-scope-schema-component">in-scope schema components</termref> in every
               stylesheet. These are defined in <specref ref="built-in-types"/>. </p><p>The remainder of this section describes facilities that are available only with a
                  <termref def="dt-schema-aware-xslt-processor">schema-aware XSLT
                  processor</termref>.</p><p>Additional <termref def="dt-schema-component">schema components</termref> (type
               definitions, element declarations, and attribute declarations) may be added to the
                  <termref def="dt-in-scope-schema-component">in-scope schema components</termref>
               by means of the <elcode>xsl:import-schema</elcode> declaration in a stylesheet.</p><p>The <elcode>xsl:import-schema</elcode> declaration may reference an external schema
               document by means of a URI, or it may contain an inline <code nobreak="false">xs:schema</code>
               element.</p><p>An <elcode>xsl:import-schema</elcode> declaration may include a <code nobreak="false">role</code>
            attribute, which indicates that the schema components are only to be present in the
            static context of a region of the stylesheet where they are explicitly invoked
            by means of an <code nobreak="false">[xsl:]schema-role</code> attribute.</p><p>It is only necessary to import a schema explicitly if one or more of its <termref def="dt-schema-component">schema components</termref> are referenced explicitly by
               name in the <termref def="dt-stylesheet">stylesheet</termref>; it is not necessary to
               import a schema merely because the stylesheet is used to process a source document
               that has been assessed against that schema. It is possible to make use of the
               information resulting from schema assessment (for example, the fact that a particular
               attribute holds a date) even if no schema has been imported by the stylesheet.</p><p>Importing a schema does not of itself say anything about the type of the source
               document that the <termref def="dt-stylesheet">stylesheet</termref> is expected to
               process. The imported type definitions can be used for temporary nodes or for nodes
               on a <termref def="dt-result-tree">result tree</termref> just as much as for nodes in
               source documents. It is possible to make assertions about the type of an input
               document by means of tests within the <termref def="dt-stylesheet">stylesheet</termref>. For example:</p><example><head>Asserting the Required Type of the Source Document</head><eg role="xslt-declaration" xml:space="preserve">&lt;xsl:mode typed="lax"/&gt;
&lt;xsl:global-context-item use="required"
            as="document-node(schema-element(my:invoice))"/&gt;</eg><p>This example will cause the transformation to fail with an error message, unless
                  the <termref def="dt-global-context-item"/> is valid against the top-level element
                  declaration <code nobreak="false">my:invoice</code>, and has been annotated as such.</p><p>A <code nobreak="false">schema-role</code> attribute could be added to the declaration to indicate
                 which schema the element declaration <code nobreak="false">my:invoice</code> is to be taken from.</p><p>The setting <code nobreak="false">typed="lax"</code> further ensures that in any
                  match pattern for a template rule in this mode, an element name that corresponds
                  to the name of an element declaration in the schema is taken as referring to
                  elements validated against that declaration: for example,
                     <code nobreak="false">match="employee"</code> will only match a validated <code nobreak="false">employee</code>
                  element. Selecting this option enables the XSLT processor to do more compile-time
                  type-checking against the schema, for example it allows the processor to produce
                  warning or error messages when path expressions contain misspelt element names, or
                  confuse an element with an attribute.</p></example><p>It is also true that importing a schema does not of itself say
               anything about the structure of the result tree. It is possible to request validation
               of a result tree against the schema by using the <elcode>xsl:result-document</elcode>
               instruction, for example:</p><example><head>Requesting Validation of the Result Document</head><eg role="xslt-declaration xmlns:xhtml='xhtml'" xml:space="preserve">&lt;xsl:template match="/"&gt;
  &lt;xsl:result-document validation="strict"&gt;
    &lt;xhtml:html&gt;
      &lt;xsl:apply-templates/&gt;
    &lt;/xhtml:html&gt;
  &lt;/xsl:result-document&gt;
&lt;/xsl:template&gt;
               </eg><p>This example will cause the transformation to fail with an error message unless
                  the document element of the result document is valid against the top-level element
                  declaration <code nobreak="false">xhtml:html</code>.</p><p>A <code nobreak="false">schema-role</code> attribute could be added to the <elcode>xsl:result-document</elcode>
                  instruction to indicate
                 which schema the document is to be validated against.</p></example><p>It is possible that a source document may contain nodes whose 
               <termref def="dt-type-annotation">type annotation</termref> is not one of the types
               imported by the stylesheet. The data model (see <bibref ref="xpath-datamodel-40"/>)
               requires that the processor has sufficient information about such types to 
               correctly implement the semantics of the language, even though the schema has
               not been imported; it also requires that all schemas used by the processor in a given
               processing episode (for example, an XSLT transformation) should be consistent. For 
               example, if a type annotation of a node is the simple type <code nobreak="false">my:percentage</code>,
               and a type named <code nobreak="false">my:percentage</code> appears in an imported schema, then they
               must be the same type.</p><p>Where a stylesheet author chooses to make assertions about the types of nodes or of
                  <termref def="dt-variable">variables</termref> and <termref def="dt-parameter">parameters</termref>, it is possible for an XSLT processor to perform static
               analysis of the <termref def="dt-stylesheet">stylesheet</termref> (that is, analysis
               in the absence of any source document). Such analysis <rfc2119>may</rfc2119> reveal
               errors that would otherwise not be discovered until the transformation is actually
               executed. An XSLT processor is not <rfc2119>required</rfc2119> to perform such static
               type-checking. Under some circumstances (see <specref ref="errors"/>) type errors
               that are detected early <rfc2119>may</rfc2119> be raised as static errors. In
               addition an implementation <rfc2119>may</rfc2119> report any condition found during
               static analysis as a warning, provided that this does not prevent the stylesheet
               being evaluated as described by this specification.</p><p>A <termref def="dt-stylesheet">stylesheet</termref> can also control the <termref def="dt-type-annotation">type annotations</termref> of nodes that it constructs in
               a <termref def="dt-result-tree">result
                     tree</termref>. This can be done in a number of ways.</p><ulist><item><p>It is possible to request explicit validation of a complete document, that is,
                     a <termref def="dt-result-tree">result
                           tree</termref> rooted at a document node.  Validation
                     is either strict or lax, as described in <bibref ref="xmlschema-1"/>. If
                     validation of a <termref def="dt-result-tree">result tree</termref> fails
                     (strictly speaking, if the outcome of the validity assessment is
                        <code nobreak="false">invalid</code>), then the transformation fails, but in all other
                     cases, the element and attribute nodes of the tree will be annotated with the
                     names of the types to which these nodes conform. These <termref def="dt-type-annotation">type annotations</termref> will be discarded if the
                     result tree is serialized as an XML document, but they remain available when
                     the result tree is passed to an application (perhaps another <termref def="dt-stylesheet">stylesheet</termref>) for further processing.</p></item><item><p>It is also possible to validate individual element and attribute nodes as they
                     are constructed. This is done using the <code nobreak="false">type</code> and
                        <code nobreak="false">validation</code> attributes of the <elcode>xsl:element</elcode>,
                        <elcode>xsl:attribute</elcode>, <elcode>xsl:copy</elcode>, and
                        <elcode>xsl:copy-of</elcode> instructions, or the <code nobreak="false">xsl:type</code> and
                        <code nobreak="false">xsl:validation</code> attributes of a literal result element.</p></item><item><p>When elements, attributes, or document nodes are copied, either explicitly
                     using the <elcode>xsl:copy</elcode> or <elcode>xsl:copy-of</elcode>
                     instructions, or implicitly when nodes in a sequence are attached to a new
                     parent node, the options <code nobreak="false">validation="strip"</code> and
                        <code nobreak="false">validation="preserve"</code> are available, to control whether
                     existing <termref def="dt-type-annotation">type annotations</termref> are to be
                     retained or not.</p></item></ulist><p>When nodes in a <termref def="dt-temporary-tree">temporary tree</termref> are
               validated, type information is available for use by operations carried out on the
               temporary tree, in the same way as for a source document that has undergone schema
               assessment.</p><p>For details of how validation of element and attribute nodes works, see <specref ref="validation"/>.</p></div2><div2 id="streaming-concepts"><head>Streaming</head><p>Streaming is an optional feature of the XSLT 4.0 language.</p><p><termdef id="dt-streaming" term="streaming">The term <term>streaming</term> refers to
                  a manner of processing in which XML documents (such as source and result documents)
                  are not represented by a complete tree of nodes occupying memory proportional to
                  document size, but instead are processed “on the fly” as a sequence of events,
                  similar in concept to the stream of events notified by an XML parser to represent
                  markup in lexical XML.</termdef></p><p><termdef id="dt-streamed-document" term="streamed document">A <term>streamed
                     document</term> is a <termref def="dt-source-tree">source tree</termref> that
                  is processed using streaming, that is, without constructing a complete tree of
                  nodes in memory.</termdef></p><p><termdef id="dt-streamed-node" term="streamed node">A <term>streamed
                     node</term> is a node in a <termref def="dt-streamed-document">streamed
                     document</termref>.</termdef></p><p>For full information about streaming, see <bibref ref="xslt40streaming"/>.</p></div2><div2 id="errors"><head>Error Handling</head><p>
               <termdef id="dt-static-error" term="static error">An error that can be detected by
                  examining a <termref def="dt-stylesheet">stylesheet</termref> before execution
                  starts (that is, before the source document and values of stylesheet parameters
                  are available) is referred to as a <term>static error</term>.</termdef>
            </p><p>Generally, errors in the structure of the <termref def="dt-stylesheet">stylesheet</termref>, or in the syntax of XPath <termref def="dt-expression">expressions</termref> contained in the stylesheet, are classified as <termref def="dt-static-error">static errors</termref>. Where this specification states
               that an element in the stylesheet <rfc2119>must</rfc2119> or <rfc2119>must
                  not</rfc2119> appear in a certain position, or that it <rfc2119>must</rfc2119> or
                  <rfc2119>must not</rfc2119> have a particular attribute, or that an attribute
                  <rfc2119>must</rfc2119> or <rfc2119>must not</rfc2119> have a value satisfying
               specified conditions, then any contravention of this rule is a static error unless
               otherwise specified. </p><p>A processor <rfc2119>must</rfc2119> provide a mode of operation 
               that takes a (possibly erroneous) stylesheet <termref def="dt-package">package</termref> as 
               input and enables the user to determine whether or not that package contains any
               <termref def="dt-static-error">static errors</termref>.
            </p><note><p>The manner in which static errors are reported, and the behavior when there are multiple
               static errors, are left as design choices for the implementer. It is <rfc2119>recommended</rfc2119> 
               that the error codes defined in this specification should be made available in any diagnostics.
            </p></note><p>A processor <rfc2119>may</rfc2119> also provide a mode of operation in which 
               <termref def="dt-static-error">static errors</termref> in parts of the stylesheet that 
               are not evaluated can go unreported.
            </p><note><p>For example, when operating in this mode, a processor might report static errors 
               in a template rule only if the input document contains nodes that match that template rule. 
               Such a mode of operation can provide performance benefits when large and well-tested stylesheets 
               are used to process source documents that might only use a small part of the XML vocabulary 
               that the stylesheet is designed to handle.
            </p></note><p>
               <termdef id="dt-dynamic-error" term="dynamic error">An error that is not 
                  capable of detection
                  until a source document is being transformed is referred to as a <term>dynamic
                     error</term>.</termdef>
            </p><p>When a <termref def="dt-dynamic-error"/> occurs, and is not caught
               using <elcode>xsl:catch</elcode>, the <termref def="dt-processor">processor</termref>
               <rfc2119>must</rfc2119> raise the error, and the transformation fails.</p><p>Because different implementations may optimize execution of the <termref def="dt-stylesheet">stylesheet</termref> in different ways, the detection of
               dynamic errors is to some degree <termref def="dt-implementation-dependent">implementation-dependent</termref>. In cases where an implementation is able to
               produce a <termref def="dt-principal-result"/> or
                     <termref def="dt-secondary-result"/>
                without evaluating a particular construct, the
               implementation is never <rfc2119>required</rfc2119> to evaluate that construct solely
               in order to determine whether doing so causes a dynamic error. For example, if a
                  <termref def="dt-variable">variable</termref> is declared but never referenced, an
               implementation <rfc2119>may</rfc2119> choose whether or not to evaluate the variable
               declaration, which means that if evaluating the variable declaration causes a dynamic
               error, some implementations will raise this error and others will not.</p><p>There are some cases where this specification requires that a construct <rfc2119>must
                  not</rfc2119> be evaluated: for example, the content of an <elcode>xsl:if</elcode>
               instruction <rfc2119>must not</rfc2119> be evaluated if the test condition is false.
               This means that an implementation <rfc2119>must not</rfc2119> raise any dynamic
               errors that would arise if the construct were evaluated.</p><p>An implementation <rfc2119>may</rfc2119> raise a <termref def="dt-dynamic-error">dynamic error</termref> before any source document is available, but only if it
               can determine that the error would be raised for every possible source document and
               every possible set of parameter values. For example, some <termref def="dt-circularity">circularity</termref> errors fall into this category: see
                  <specref ref="circularity"/>.</p><p>There are also some <termref def="dt-dynamic-error">dynamic
                  errors</termref> where the specification gives a processor license to raise the
               error during the analysis phase even if the construct might never be executed; an
               example is the use of an invalid QName as a literal argument to a function such as
                  <function>key</function>, or the use of an invalid regular expression in the
                  <code nobreak="false">regex</code> attribute of the <elcode>xsl:analyze-string</elcode>
               instruction.</p><p>A <termref def="dt-dynamic-error"/>
               is also raised during the static
               analysis phase if the error occurs during evaluation of a <termref def="dt-static-expression"/>.</p><p>The XPath specification states (see <xspecref spec="XP40" ref="id-kinds-of-errors"/>)
               that if any expression (at any level) can be evaluated during the analysis phase
               (because all its explicit operands are known and it has no dependencies on the
               dynamic context), then any error in performing this evaluation <rfc2119>may</rfc2119>
               be raised as a static error. For XPath expressions used in an XSLT stylesheet,
               however, any such errors <rfc2119>must not</rfc2119> be raised as static errors in
               the stylesheet unless they would occur in every possible evaluation of that
               stylesheet; instead, they must be raised as dynamic errors, and raised only if
               the XPath expression is actually evaluated.</p><example><head>Errors in Constant Subexpressions</head><p>An XPath processor may report statically that the expression <code nobreak="false">1 div 0</code>
                  fails with a “divide by zero” error. But suppose this XPath expression occurs in
                  an XSLT construct such as:</p><eg role="xslt-instruction" xml:space="preserve">&lt;xsl:choose&gt;
  &lt;xsl:when test="system-property('xsl:version') = '1.0'"&gt;
    &lt;xsl:value-of select="1 div 0"/&gt;
  &lt;/xsl:when&gt;
  &lt;xsl:otherwise&gt;
    &lt;xsl:value-of select="xs:double('INF')"/&gt;
  &lt;/xsl:otherwise&gt;
&lt;/xsl:choose&gt;</eg><p>Then the XSLT processor must not report an error, because the relevant XPath
                  construct appears in a context where it will never be executed by an XSLT 
                  <phrase diff="chg" at="2023-02-24">4.0</phrase> processor. (An XSLT 1.0 processor
                  will execute this code successfully, returning positive infinity, because it uses
                  double arithmetic rather than decimal arithmetic.)</p></example><p>
               <termdef id="dt-type-error" term="type error">Certain errors are classified as
                     <term>type errors</term>. A type error occurs when the value supplied as input
                  to an operation is of the wrong type for that operation, for example when an
                  integer is supplied to an operation that expects a node.</termdef> If a type error
               occurs in an instruction that is actually evaluated, then it <rfc2119>must</rfc2119>
               be raised in the same way as a <termref def="dt-dynamic-error"> dynamic error</termref>. Alternatively, an
               implementation <rfc2119>may</rfc2119> raise a type error during the analysis phase
               in the same way as a <termref def="dt-static-error">static error</termref>, even if
               it occurs in part of the stylesheet that is never evaluated, provided it can
               establish that execution of a particular construct would never succeed.</p><p>It is <termref def="dt-implementation-defined"/> whether type errors are raised
               statically.</p><imp-def-feature id="idf-err-statictypechecking">It is <termref def="dt-implementation-defined"/> whether type errors are raised
               statically.</imp-def-feature><example><head>A Type Error</head><p>The following construct contains a type error, because
                     <code nobreak="false">42</code> is not allowed as the value of the <code nobreak="false">select</code>
                  expression of the <elcode>xsl:number</elcode> instruction (it must be a node). An
                  implementation <rfc2119>may</rfc2119> optionally raise this as a static error,
                  even though the offending instruction will never be evaluated, and the type error
                  would therefore never be raised as a dynamic error.</p><eg role="error" xml:space="preserve">&lt;xsl:if test="false()"&gt;
  &lt;xsl:number select="42"/&gt;
&lt;/xsl:if&gt;</eg><p>On the other hand, in the following example it is not possible to determine
                  statically whether the operand of <elcode>xsl:number</elcode> will have a suitable dynamic type. An
                  implementation <rfc2119>may</rfc2119> produce a warning in such cases, but it
                     <rfc2119>must not</rfc2119> treat it as an error.</p><eg role="xslt-declaration" xml:space="preserve">&lt;xsl:template match="para"&gt;
  &lt;xsl:param name="p" as="item()"/&gt;
  &lt;xsl:number select="$p"/&gt;
&lt;/xsl:template&gt;</eg></example><p>If more than one error arises, an implementation is not <rfc2119>required</rfc2119>
               to raise any errors other than the first one that it detects. It is <termref def="dt-implementation-dependent">implementation-dependent</termref> which of the
               several errors is raised. This applies both to static errors and to dynamic errors.
               An implementation is allowed to raise more than one error, but if any errors have
               been raised, it <rfc2119>must not</rfc2119> finish as if the transformation were
               successful.</p><p>When a transformation raises one or more dynamic errors, the final state of any
               persistent resources updated by the transformation is <termref def="dt-implementation-dependent">implementation-dependent</termref>.
               Implementations are not <rfc2119>required</rfc2119> to restore such resources to
               their initial state. In particular, where a transformation produces multiple result
               documents, it is possible that one or more serialized result documents
                  <rfc2119>may</rfc2119> be written successfully before the transformation
               terminates, but the application cannot rely on this behavior.</p><p>Everything said above about error handling applies equally to errors in evaluating
               XSLT instructions, and errors in evaluating XPath <termref def="dt-expression">expressions</termref>. Static errors and dynamic errors may occur in both
               cases.</p><p>
               <termdef id="dt-serialization-error" term="serialization error">If a transformation
                  has successfully produced a <termref def="dt-principal-result"/> or <termref def="dt-secondary-result"/>, it is
                     still possible that errors may occur in serializing that result
                  . For example, it may be impossible to
                  serialize the result  using the
                  encoding selected by the user. Such an error is referred to as a
                     <term>serialization error</term>.</termdef> If the processor performs
               serialization, then it <rfc2119>must</rfc2119> do so as specified in <specref ref="serialization"/>, and in particular it <rfc2119>must</rfc2119> raise any
               serialization errors that occur.</p><p>Errors are identified by a QName. For errors defined in this specification, the
               namespace of the QName is always <code nobreak="false">http://www.w3.org/2005/xqt-errors</code> (and
               is therefore not given explicitly), while the local part is an 8-character code in
               the form <var>PPSSNNNN</var>. Here <var>PP</var> is always <code nobreak="false">XT</code> (meaning
               XSLT), and <var>SS</var> is one of <code nobreak="false">SE</code> (static error), <code nobreak="false">DE</code>
               (dynamic error),  or <code nobreak="false">TE</code>
               (type error). Note that the allocation of an error to one of these categories is
               purely for convenience and carries no normative implications about the way the error
               is handled. Many errors, for example, can be raised either dynamically or
               statically. These error codes are used to label error conditions in this
               specification, and are summarized in <specref ref="error-summary"/>. </p><p>Errors defined in related specifications (<bibref ref="xpath-40"/>, <bibref ref="xpath-functions-40"/>
               <bibref ref="xslt-xquery-serialization-40"/>) use QNames with a similar structure, in
               the same namespace. When errors occur in processing XPath expressions, an XSLT
               processor <rfc2119>should</rfc2119> use the original error code reported by the XPath
               processor, unless a more specific XSLT error code is available.</p><p>Implementations <rfc2119>must</rfc2119> use the codes
               defined in these specifications when raising dynamic errors, to ensure that
                     <elcode>xsl:catch</elcode> behaves in an interoperable way across
                  implementations. Stylesheet authors should note, however, that there are many
                  examples of errors where more than one rule in this specification is violated, and
                  where the processor therefore has discretion in deciding which error code to
                  associate with the condition: there is therefore no guarantee that different
                  processors will always use the same error code for the same erroneous
                  input.</p><p>Additional errors defined by an implementation (or by an application)
                  <rfc2119>may</rfc2119> use QNames in an implementation-defined (or user-defined)
               namespace without risk of collision.</p></div2></div1><div1 id="stylesheet-structure"><head>Stylesheet Structure</head><p>This section describes the overall structure of a stylesheet as a collection of XML
            documents.</p><div2 id="namespaces"><head>Namespaces</head><p diff="add" at="2023-05-04">A <termref def="dt-stylesheet-module"/> is typically written
               as a namespace well-formed XML document: more formally, as described in 
               <specref ref="stylesheet-modules"/>, a stylesheet module 
               takes the form of an XDM tree rooted at an element node.</p><p diff="add" at="2023-05-04">The names of elements and attributes in source documents and
               result documents are namespace-qualified names. In addition, as described in <specref ref="qname"/>,
               XSLT uses namespace-qualified names to identify variables, functions, templates, and other components.
               These names generally use namespace prefixes that are resolved to namespace URIs using a set
               of prefix-uri namespace bindings.</p><p diff="add" at="2023-05-04">There are two ways namespace bindings can be established in a
            stylesheet module:</p><ulist diff="add" at="2023-05-04"><item><p><termdef id="dt-native-namespace-bindings" term="native namespace bindings">
                     The <term>native namespace bindings</term> for any element in an XSLT <termref def="dt-stylesheet-module"/>
                     are the prefix-uri mappings defined by the namespace nodes of that element, according to the rules in
                     <bibref ref="xpath-datamodel-40"/>.</termdef></p><p>For example, a namespace declaration of the form 
                     <code nobreak="false">xmlns:math="http://www.w3.org/2005/xpath-functions/math</code> establishes a binding 
                     of the prefix <code nobreak="false">math</code> to the namespace URI <code nobreak="false">http://www.w3.org/2005/xpath-functions/math</code>,
                     thereby enabling functions in that namespace to be invoked using an expression such as
                     <code nobreak="false">math:sin($theta)</code>
                  </p></item><item><p><termdef id="dt-fixed-namespace-bindings" term="fixed namespace bindings">
                     The <term>fixed namespace bindings</term> for a <termref def="dt-stylesheet-module"/> are
                     established using the <code nobreak="false">fixed-namespaces</code> attribute on the <elcode>xsl:stylesheet</elcode>,
                     <elcode>xsl:transform</elcode>, or <elcode>xsl:package</elcode> element enclosing the stylesheet
                     module.</termdef></p><p>For example, the attribute <code nobreak="false">fixed-namespaces="math map array"</code>
                     establishes bindings for the prefixes <code nobreak="false">math</code>, <code nobreak="false">map</code>, and <code nobreak="false">array</code>
                     to the namespace URIs conventionally associated with these prefixes as described
                     in <specref ref="reserved-namespaces"/>.</p></item></ulist><p diff="add" at="2023-05-04">Prefixes used in element and attribute names in the stylesheet, because these are interpreted
            by the XML parser and not only by the XSLT processor, <rfc2119>must</rfc2119> be bound
            using <termref def="dt-native-namespace-bindings"/>.
            In particular, the <termref def="dt-xslt-namespace"/> is used in the names of XSLT elements, so it must 
            be declared in every stylesheet module using a namespace declaration such as
            <code nobreak="false">xmlns:xsl="http://www.w3.org/1999/XSL/Transform</code>. (A different prefix can be used:
               some users prefer <code nobreak="false">xslt</code>, some favor the default namespace.) 
               But namespace prefixes that are only used within the content of
            attribute and text nodes in the stylesheet (for example, <code nobreak="false">select="math:sin($theta)"</code>)
            can be declared in <termref def="dt-fixed-namespace-bindings"/>.</p><p diff="add" at="2023-05-04"><termdef id="dt-applicable-static-namespaces" term="applicable static namespaces">
               The <term>applicable static namespaces</term> for an element in a stylesheet module are the
               <termref def="dt-fixed-namespace-bindings"/> for the module if the root element
               of the module has a <code nobreak="false">fixed-namespaces</code> attribute, or the <termref def="dt-native-namespace-bindings"/>
               of the element otherwise.
            </termdef></p><p>The effect of declaring fixed namespace bindings is described in more detail in
            <specref ref="fixed-namespaces"/>.</p><note><p>As a general rule:</p><ulist><item><p>Prefixes used in the names of elements and attributes in the stylesheet
                  must be declared using <termref def="dt-native-namespace-bindings"/>.</p></item><item><p>Prefixes used in QNames appearing in the content of attribute nodes
                     and text nodes in the stylesheet can usually be declared using
                     <termref def="dt-fixed-namespace-bindings"/>. There are a small number
                  of exceptions, notably the standard attributes <code nobreak="false">[xsl:]exclude-result-prefixes</code>
                  and <code nobreak="false">[xsl:]extension-element-prefixes</code>, and the <code nobreak="false">stylesheet-prefix</code>
                  and <code nobreak="false">result-prefix</code> attributes of <elcode>xsl:namespace-alias</elcode>.</p></item></ulist></note><div3 id="xslt-namespace"><head>XSLT Namespace</head><p>
                  <termdef id="dt-xslt-namespace" term="XSLT namespace">The <term>XSLT namespace</term>
                     has the URI <code nobreak="false">http://www.w3.org/1999/XSL/Transform</code>. It is used to
                     identify elements, attributes, and other names that have a special meaning defined
                     in this specification.</termdef>
               </p><note><p>The <code nobreak="false">1999</code> in the URI indicates the year in which the URI was allocated
                     by the W3C. It does not indicate the version of XSLT being used, which is
                     specified by attributes (see <specref ref="stylesheet-element"/> and <specref ref="simplified-stylesheet"/>).</p></note><p>XSLT <termref def="dt-processor">processors</termref>
                  <rfc2119>must</rfc2119> use the XML namespaces mechanism <bibref ref="xml-names"/> to
                  recognize elements and attributes from this namespace. Elements from the XSLT
                  namespace are recognized only in the <termref def="dt-stylesheet">stylesheet</termref> and not in the source document. The complete list of
                  XSLT-defined elements is specified in <specref ref="element-syntax-summary"/>.
                     <termref def="dt-implementation">Implementations</termref>
                  <rfc2119>must not</rfc2119> extend the XSLT namespace with additional elements or
                  attributes. Instead, any extension <rfc2119>must</rfc2119> be in a separate
                  namespace. Any namespace that is used for additional instruction elements
                     <rfc2119>must</rfc2119> be identified by means of the <termref def="dt-extension-instruction">extension instruction</termref> mechanism specified
                  in <specref ref="extension-instruction"/>.</p><p>Except where the rules for <termref def="dt-forwards-compatible-behavior"/>
                     dictate otherwise, it is a <termref def="dt-static-error">static error</termref>
                     for any element in the stylesheet to be in the XSLT namespace unless it is an element defined in this
                     specification <errorref spec="XT" class="SE" code="0010"/>.</p><p>This specification uses a prefix of <code nobreak="false">xsl:</code> for referring to elements in
                  the XSLT namespace. However, XSLT stylesheets are free to use any prefix, provided
                  that there is a namespace declaration that binds the prefix to the URI of the XSLT
                  namespace.</p><note><p>Throughout this specification, an element or attribute that is in no namespace, or
                     an <termref def="dt-expanded-qname">expanded QName</termref> whose namespace part
                     is the empty sequence, is referred to as having a <term>null namespace
                     URI</term>.</p></note><note><p>By convention, the names of <termref def="dt-xslt-element">XSLT
                        elements</termref>, attributes and functions are all lower-case;
                     they use hyphens to separate words, and they use abbreviations only if these already appear
                     in the syntax of a related language such as XML or HTML. Names of types defined in
                     XML Schema are regarded as single words and are capitalized exactly as in XML
                     Schema. This sometimes leads to composite function names such as
                        <xfunction>current-dateTime</xfunction>.</p></note></div3></div2><div2 id="xslt-media-type"><head>XSLT Media Type</head><p>The media type <code nobreak="false">application/xslt+xml</code>
               has been registered for XSLT stylesheet
               modules.</p><p>The definition of the media type is at <bibref ref="XSLT-Mime-Type"/>.</p><p>This media type <rfc2119>should</rfc2119> be used for an XML document containing a
                  <termref def="dt-standard-stylesheet-module">standard stylesheet module</termref>
               at its top level, and it <rfc2119>may</rfc2119> also be used for a <termref def="dt-simplified-stylesheet-module">simplified stylesheet module</termref>. It
                  <rfc2119>should not</rfc2119> be used for an XML document containing an 
               <termref def="dt-embedded-stylesheet-module">embedded stylesheet module</termref>.</p></div2><div2 id="standard-attributes"><head>Standard Attributes</head><changes><change issue="451" PR="1819" date="2025-02-18">
                  The standard attribute <code nobreak="false">[xsl:]schema-role</code> is introduced, to allow 
                  different parts of a stylesheet to use different schemas.
               </change></changes><p>
               <termdef id="dt-standard-attributes" term="standard attributes">There are a number of
                     <term>standard attributes</term> that may appear on any <termref def="dt-xslt-element">XSLT element</termref>: specifically
                     <code nobreak="false">default-collation</code>, 
                     <code nobreak="false">default-mode</code>,
                     <code nobreak="false">default-validation</code>,
                     <code nobreak="false">exclude-result-prefixes</code>, 
                     <code nobreak="false">expand-text</code>, 
                     <code nobreak="false">extension-element-prefixes</code>,
                     <code nobreak="false">schema-role</code>,
                     <code nobreak="false">use-when</code>, 
                     <code nobreak="false">version</code>, and
                     <code nobreak="false">xpath-default-namespace</code>.</termdef>
            </p><p>These attributes may also appear on a <termref def="dt-literal-result-element">literal result element</termref>, but in this case, to distinguish them from
               user-defined attributes, the names of the attributes are in the <termref def="dt-xslt-namespace">XSLT namespace</termref>. They are thus typically written
               as <code nobreak="false">xsl:default-collation</code>,
               <code nobreak="false">xsl:default-mode</code>, 
               <code nobreak="false">xsl:default-validation</code>,
                  <code nobreak="false">xsl:exclude-result-prefixes</code>, <code nobreak="false">xsl:expand-text</code>, 
               <code nobreak="false">xsl:extension-element-prefixes</code>, <code nobreak="false">xsl:use-when</code>,
                  <code nobreak="false">xsl:version</code>, or <code nobreak="false">xsl:xpath-default-namespace</code>.</p><p>It is <rfc2119>recommended</rfc2119> that all these attributes should also be
               permitted on <termref def="dt-extension-instruction">extension
               instructions</termref>, but this is at the discretion of the implementer of each
               extension instruction. They <rfc2119>may</rfc2119> also be permitted on <termref def="dt-data-element">user-defined data elements</termref>, though they will only
               have any useful effect in the case of data elements that are designed to behave like
               XSLT declarations or instructions.</p><p>In the following descriptions, these attributes are referred to generically as
                  <code nobreak="false">[xsl:]version</code>, and so on.</p><p>These attributes all affect the element they appear on, together with any elements
               and attributes that have that element as an ancestor. The two forms with and without
               the XSLT namespace have the same effect; the XSLT namespace is used for the attribute
               if and only if its parent element is <emph>not</emph> in the XSLT namespace.</p><p>In the case of <code nobreak="false">[xsl:]default-collation</code>, 
               <code nobreak="false">[xsl:]expand-text</code>, <code nobreak="false">[xsl:]schema-role</code>,
               <code nobreak="false">[xsl:]version</code>, and <code nobreak="false">[xsl:]xpath-default-namespace</code>, the value
               can be overridden by a different value for the same attribute appearing on a
               descendant element. The <termref def="dt-effective-value"/> of the attribute for a particular stylesheet
               element is determined by the innermost ancestor-or-self element on which the
               attribute appears.</p><p>In an <termref def="dt-embedded-stylesheet-module">embedded stylesheet
                  module</termref>, <termref def="dt-standard-attributes">standard
                  attributes</termref> appearing on ancestors of the outermost element of the
               stylesheet module have no effect.</p><p>In the case of <code nobreak="false">[xsl:]exclude-result-prefixes</code> and
                  <code nobreak="false">[xsl:]extension-element-prefixes</code> the values are cumulative. For these
               attributes, the value is given as a whitespace-separated list of namespace prefixes,
               and the <termref def="dt-effective-value"/> for an element is the combined set of namespace URIs
               designated by the prefixes that appear in this attribute for that element and any of
               its ancestor elements. Again, the two forms with and without the XSLT namespace are
               equivalent.</p><p>The effect of the <code nobreak="false">[xsl:]use-when</code> attribute is described in <specref ref="conditional-inclusion"/>.</p><p>Because these attributes may appear on any <termref def="dt-xslt-element">XSLT
                  element</termref>, they are not listed in the syntax summary of each individual
               element. Instead they are listed and described in the entry for the
                  <elcode>xsl:stylesheet</elcode>, <elcode>xsl:transform</elcode>, and <elcode>xsl:package</elcode> elements only. This
               reflects the fact that these attributes are often used on the outermost element of the stylesheet, in which case they apply to
               the entire <termref def="dt-stylesheet-module"/>
               or <termref def="dt-package-manifest"/>.</p><p>Note that the effect of these attributes does <emph>not</emph> extend to <termref def="dt-stylesheet-module">stylesheet modules</termref> referenced by
                  <elcode>xsl:include</elcode> or <elcode>xsl:import</elcode> declarations, nor to packages referenced using
                     <elcode>xsl:use-package</elcode>.</p><p>For the detailed effect of each attribute, see the following sections:</p><glist><gitem><label>
                     <code nobreak="false">[xsl:]default-collation</code>
                  </label><def><p>see <specref ref="default-collation-attribute"/>
                     </p></def></gitem><gitem><label>
                     <code nobreak="false">[xsl:]default-mode</code>
                  </label><def><p>see <specref ref="default-mode"/>
                     </p></def></gitem><gitem><label>
                     <code nobreak="false">[xsl:]default-validation</code>
                  </label><def><p>see <specref ref="validation"/>
                     </p></def></gitem><gitem><label>
                     <code nobreak="false">[xsl:]exclude-result-prefixes</code>
                  </label><def><p>see <specref ref="lre-namespaces"/>
                     </p></def></gitem><gitem><label>
                     <code nobreak="false">[xsl:]expand-text</code>
                  </label><def><p>see <specref ref="text-value-templates"/>
                     </p></def></gitem><gitem><label>
                     <code nobreak="false">[xsl:]extension-element-prefixes</code>
                  </label><def><p>see <specref ref="extension-instruction"/>
                     </p></def></gitem><gitem><label>
                     <code nobreak="false">[xsl:]schema-role</code>
                  </label><def><p>see <specref ref="multiple-schemas"/>
                     </p></def></gitem><gitem><label>
                     <code nobreak="false">[xsl:]use-when</code>
                  </label><def><p>see <specref ref="conditional-inclusion"/>
                     </p></def></gitem><gitem><label>
                     <code nobreak="false">[xsl:]version</code>
                  </label><def><p>see <specref ref="backwards"/> and <specref ref="forwards"/>
                     </p></def></gitem><gitem><label>
                     <code nobreak="false">[xsl:]xpath-default-namespace</code>
                  </label><def><p>see <specref ref="unprefixed-qnames"/>
                     </p></def></gitem></glist></div2><div2 id="packages"><head>Packages</head><p><termdef id="dt-package" term="package">An explicit <term>package</term> is
                  represented by an <elcode>xsl:package</elcode> element, which will generally be
                  the outermost element of an XML document. When the
                        <elcode>xsl:package</elcode> element is not used explicitly, the entire
                     stylesheet comprises a single implicit package.</termdef> (This
               specification does not preclude the <elcode>xsl:package</elcode> being embedded in
               another XML document, but it will never have any other XSLT element as an
               ancestor).</p><e:element-syntax xmlns:e="http://www.w3.org/1999/XSL/Spec/ElementSyntax" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" name="package">
      <e:attribute name="id" required="no">
         <e:data-type name="id"/>
      </e:attribute>
      <e:attribute name="name" required="no">
         <e:data-type name="uri"/>
      </e:attribute>
      <e:attribute name="package-version" required="no" default="'1'">
         <e:data-type name="string"/>
      </e:attribute>
      <e:attribute name="version" required="yes">
         <e:data-type name="decimal"/>
      </e:attribute>

      <e:attribute name="input-type-annotations" default="'unspecified'">
         <e:constant value="preserve"/>
         <e:constant value="strip"/>
         <e:constant value="unspecified"/>
      </e:attribute>
      <e:attribute name="declared-modes" required="no" default="'yes'">
         <e:data-type name="boolean"/>
      </e:attribute>
      <e:attribute name="default-mode" default="'#unnamed'">
         <e:data-type name="eqname"/>
         <e:constant value="#unnamed"/>
      </e:attribute>
      <e:attribute name="default-validation" default="'strip'">
         <e:constant value="preserve"/>
         <e:constant value="strip"/>
      </e:attribute>

      <e:attribute name="default-collation" required="no">
         <e:data-type name="uris"/>
      </e:attribute>
      <e:attribute name="extension-element-prefixes" required="no">
         <e:data-type name="prefixes"/>
      </e:attribute>
      <e:attribute name="exclude-result-prefixes" required="no">
         <e:data-type name="prefixes"/>
      </e:attribute>
      <e:attribute name="expand-text" required="no" default="'no'">
         <e:data-type name="boolean"/>
      </e:attribute>
      <e:attribute name="fixed-namespaces" required="no">
         <e:data-type name="string"/>
      </e:attribute>
      <e:attribute name="schema-role" required="no">
         <e:data-type name="ncname"/>
      </e:attribute>
      <e:attribute name="use-when" required="no" default="true()">
         <e:data-type name="expression"/>
      </e:attribute>
      <e:attribute name="xpath-default-namespace" required="no">
         <e:data-type name="uri"/>
      </e:attribute>

      <e:sequence>
         <e:choice repeat="zero-or-more">
            <e:element name="expose"/>
            <e:model name="declarations"/>
         </e:choice>
      </e:sequence>
      <e:allowed-parents/>
   </e:element-syntax><p><termdef id="dt-package-manifest" term="package manifest">The content of the
                     <elcode>xsl:package</elcode> element is referred to as the <term>package
                     manifest</term></termdef>.</p><p>The <code nobreak="false">version</code> attribute indicates the
               version of the XSLT language specification to which the package manifest conforms.
                  The value <rfc2119>should</rfc2119> normally be
                     <phrase diff="chg" at="2023-02-24"><code nobreak="false">4.0</code></phrase>. 
               If the value is numerically less than <phrase diff="chg" at="2023-02-24"><code nobreak="false">4.0</code></phrase>, the
                  content of the <elcode>xsl:package</elcode> element is processed using the rules
                  for <termref def="dt-backwards-compatible-behavior">backwards compatible
                     behavior</termref> (see <specref ref="backwards"/>). If the value is
               numerically greater than <phrase diff="chg" at="2023-02-24"><code nobreak="false">4.0</code></phrase>, it is processed using the rules for
                     <termref def="dt-forwards-compatible-behavior"/> (see <specref ref="forwards"/>).</p><p>A package typically has a name, given in its <code nobreak="false">name</code>
               attribute, which <rfc2119>must</rfc2119> be an absolute URI. Unnamed packages are
               allowed, but they can only be used as the “top level” of an application; they cannot
               be the target of an <elcode>xsl:use-package</elcode> declaration in another
               package.</p><p>A package may have a version identifier, given in
               its <code nobreak="false">package-version</code> attribute. This is used to distinguish different
               versions of a package. The value of the version
                  attribute, after trimming leading and trailing whitespace, <rfc2119>must</rfc2119>
                  conform to the syntax given in <specref ref="package-versions"/>. If no version
                  number is specified for a package, version <code nobreak="false">1</code> is assumed.</p><p>The attributes <code nobreak="false">default-collation</code>, <code nobreak="false">default-mode</code>, <code nobreak="false">default-validation</code>,
                  <code nobreak="false">exclude-result-prefixes</code>, <code nobreak="false">expand-text</code>,
                  <code nobreak="false">extension-element-prefixes</code>, <code nobreak="false">use-when</code>,
                  <code nobreak="false">version</code>, and <code nobreak="false">xpath-default-namespace</code> are standard
               attributes that can appear on any XSLT element, and potentially affect all descendant
               elements. Their meaning is described in <specref ref="standard-attributes"/>.</p><p>The package manifest contains the following
                  elements, arbitrarily ordered:</p><olist><item><p>Zero or more <elcode>xsl:expose</elcode> declarations that define the interface
                     offered by this package to the outside world. An <elcode>xsl:expose</elcode>
                  declaration may appear only as a child of <elcode>xsl:package</elcode>.</p></item><item><p>Zero or more additional <termref def="dt-declaration">declarations</termref>.
                     These are the same as the declarations permitted as children of <elcode>xsl:stylesheet</elcode>
                     or <elcode>xsl:transform</elcode>.</p><p>Some declarations of particular relevance to packages include:</p><olist><item><p>The <elcode>xsl:use-package</elcode> declaration, which declares the names and
                     versions of the packages on which this package depends.</p></item><item><p>The optional <elcode>xsl:global-context-item</elcode> element; if present this
                           element defines constraints on the existence and type of the <termref def="dt-global-context-item"/>.</p></item><item><p>Zero or more <elcode>xsl:include</elcode> and <elcode>xsl:import</elcode>
                     declarations, which define additional stylesheet modules to be incorporated into this package.</p></item><item><p>Zero or more ordinary <termref def="dt-declaration">declarations</termref>, that is,
                        elements that are permitted as children of <elcode>xsl:stylesheet</elcode> or
                        <elcode>xsl:transform</elcode>. One possible coding style is to include in
                        the package manifest just a single <elcode>xsl:import</elcode> or
                        <elcode>xsl:include</elcode> declaration as a reference to the effective
                        top-level stylesheet module; this approach is particularly suitable when
                        writing code that is required to run under releases of XSLT 
                        <phrase diff="add" at="2023-02-24">earlier than 3.0</phrase>. 
                        Another approach is to include the substance of the top-level
                        stylesheet module inline within the package manifest.</p></item></olist></item></olist><example><head>An example package</head><p>The following example shows a package that offers a number of functions for
                  manipulating complex numbers. A complex number is represented as a map with two
                  entries, the keys being 0 for the real part, and 1 for the imaginary part.</p><eg role="xslt-document" xml:space="preserve">
&lt;xsl:package
  name="http://example.org/complex-arithmetic.xsl"
  package-version="1.0"
  version="3.0"
  xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
  xmlns:xs="http://www.w3.org/2001/XMLSchema"
  xmlns:f="http://example.org/complex-arithmetic.xsl"&gt;
  
  &lt;xsl:function name="f:complex-number" 
                as="map(xs:integer, xs:double)" visibility="public"&gt;
    &lt;xsl:param name="real" as="xs:double"/&gt;
    &lt;xsl:param name="imaginary" as="xs:double"/&gt;
    &lt;xsl:sequence select="{ 0: $real, 1: $imaginary }"/&gt;
  &lt;/xsl:function&gt;
  
  &lt;xsl:function name="f:real" 
                as="xs:double" visibility="public"&gt;
    &lt;xsl:param name="complex" as="map(xs:integer, xs:double)"/&gt;
    &lt;xsl:sequence select="$complex(0)"/&gt;
  &lt;/xsl:function&gt;
  
  &lt;xsl:function name="f:imag" 
                as="xs:double" visibility="public"&gt;
    &lt;xsl:param name="complex" as="map(xs:integer, xs:double)"/&gt;
    &lt;xsl:sequence select="$complex(1)"/&gt;
  &lt;/xsl:function&gt;
  
  &lt;xsl:function name="f:add" 
                as="map(xs:integer, xs:double)" visibility="public"&gt;
    &lt;xsl:param name="x" as="map(xs:integer, xs:double)"/&gt;
    &lt;xsl:param name="y" as="map(xs:integer, xs:double)"/&gt;
    &lt;xsl:sequence select="
         f:complex-number(
           f:real($x) + f:real($y), 
           f:imag($x) + f:imag($y))"/&gt;
  &lt;/xsl:function&gt;
  
  &lt;xsl:function name="f:multiply" 
                as="map(xs:integer, xs:double)" visibility="public"&gt;
    &lt;xsl:param name="x" as="map(xs:integer, xs:double)"/&gt;
    &lt;xsl:param name="y" as="map(xs:integer, xs:double)"/&gt;
    &lt;xsl:sequence select="
         f:complex-number(
           f:real($x)*f:real($y) - f:imag($x)*f:imag($y),
           f:real($x)*f:imag($y) + f:imag($x)*f:real($y))"/&gt;
  &lt;/xsl:function&gt;
  
  &lt;!-- etc. --&gt;
  
&lt;/xsl:package&gt;</eg><p>A more complex package might include private or abstract functions as well as
                  public functions; it might expose components other than functions (for example,
                  templates or global variables), and it might contain
                     <elcode>xsl:use-package</elcode> elements to allow it to call on the services
                  of other packages.</p><note><p>In this example, the way in which complex numbers are represented is exposed to
                     users of the package. It would be possible to hide the representation by
                     declaring the types on public functions simply as <code nobreak="false">item()</code>; but this
                     would be at the cost of type safety.</p></note></example><p>A package that does not itself expose any components  may be written
               using a simplified syntax: the <elcode>xsl:package</elcode> element is omitted, and
               the <elcode>xsl:stylesheet</elcode> or <elcode>xsl:transform</elcode> element is now
               the outermost element of the stylesheet module. For compatibility reasons, all the
               named templates and modes declared in the package are made public. More formally, the
               principal stylesheet module of the <termref def="dt-top-level-package">top-level
                  package</termref> may be expressed as an <elcode>xsl:stylesheet</elcode> or
                  <elcode>xsl:transform</elcode> element, which is equivalent to the package represented
               by the output of the following transformation, preserving the base URI of the
               source:</p><eg role="xslt-document" xml:space="preserve">
 &lt;xsl:transform version="3.0" 
    xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    xmlns:t="http://www.w3.org/1999/XSL/TransformAlias"&gt;
 
    &lt;xsl:namespace-alias stylesheet-prefix="t" result-prefix="xsl"/&gt;
    
    &lt;xsl:template match="xsl:stylesheet|xsl:transform"&gt;
      &lt;t:package declared-modes="no"&gt;
        &lt;xsl:copy-of select="@*"/&gt;
        &lt;t:expose component="mode" names="*" visibility="public"/&gt;
        &lt;t:expose component="template" names="*" visibility="public"/&gt;
        &lt;xsl:copy-of select="node()"/&gt;
      &lt;/t:package&gt;
    &lt;/xsl:template&gt;
 &lt;/xsl:transform&gt;
       </eg><p>The effect of the <code nobreak="false">input-type-annotations</code>
               attribute is defined in <specref ref="stripping-annotations"/>.</p><p>A more extensive example of a package, illustrating how components
               in a package can be overridden in a client package, is given in <specref ref="packages-csv-library-example"/>.</p><div3 id="package-versions"><head>Versions of a Package</head><p>If a package has a version number, the version number must conform to the
                  grammar:</p><eg role="non-xml" xml:space="preserve">
        PackageVersion   ::= NumericPart ( "-" NamePart )?
        NumericPart      ::= IntegerLiteral ( "." IntegerLiteral )*
        NamePart         ::= NCName
               </eg><p>Here <xnt xmlns:xlink="http://www.w3.org/1999/xlink" ref="prod-xpath40-IntegerLiteral" spec="XP40" xlink:type="simple">IntegerLiteral</xnt> and <code nobreak="false">NCName</code> are as defined in
                  the XPath <phrase diff="chg" at="2023-02-24">4.0</phrase> grammar productions of the same name (including rules on
                     limits). Leading and trailing whitespace is ignored; no other
                  whitespace is allowed.</p><p>Examples of valid version numbers are <code nobreak="false">2.0.5</code> or
                     <code nobreak="false">3.10-alpha</code>.</p><p><termdef id="dt-portion" term="portion">The integer literals and the optional
                        <code nobreak="false">NamePart</code> within the version number are referred to as the
                        <term>portions</term> of the version number.</termdef></p><note><p>This means that <code nobreak="false">1-alpha-2</code> is a valid version number, with two
                        <termref def="dt-portion">portions</termref>: <code nobreak="false">1</code> and
                        <code nobreak="false">alpha-2</code>. The second hyphen is part of the <code nobreak="false">NCName</code>,
                     it does not act as a portion separator.</p></note><p>Versions are ordered. When comparing two versions:</p><olist><item><p>Trailing zero <termref def="dt-portion">portions</termref> (that is, any
                        zero-valued integer that is not followed by another integer) are
                        discarded.</p></item><item><p>Comparison proceeds by comparing <termref def="dt-portion">portions</termref> pairwise from the left.</p></item><item><p>If both versions have the same number of <termref def="dt-portion">portions</termref> and all <termref def="dt-portion">portions</termref>
                        compare equal (under the rules of the
                           XPath <code nobreak="false">eq</code> operator using the Unicode codepoint
                           collation), then the versions compare equal.</p></item><item><p>If the number of <termref def="dt-portion">portions</termref> in the two
                        versions <var>V1</var> and <var>V2</var> is <var>N1</var> and <var>N2</var>,
                        with <var>N1</var>&lt;<var>N2</var>, and if all <termref def="dt-portion">portions</termref> in positions 1 to <var>N</var> compare equal, then
                           <var>V1</var> is less than <var>V2</var> if the <termref def="dt-portion"/> of <var>V2</var> in position <var>N1+1</var> is an integer, and is
                        greater than <var>V2</var> if this <termref def="dt-portion"/> is an
                           <code nobreak="false">NCName</code>. For example, <code nobreak="false">1.2</code> is less than
                           <code nobreak="false">1.2.5</code>, while <code nobreak="false">2.0</code> is greater than
                           <code nobreak="false">2.0-rc1</code>.</p></item><item><p><termref def="dt-portion">Portions</termref> are compared as follows:</p><olist><item><p>If both <termref def="dt-portion">portions</termref> are integers,
                              they are compared using the rules
                                 of XPath value comparisons.</p></item><item><p>If both <termref def="dt-portion">portions</termref> are NCNames, they
                              are compared using the rules of
                                 XPath value comparisons, using the Unicode Codepoint
                              Collation.</p></item><item><p>If one <termref def="dt-portion"/> is an integer and the other is an
                                 <code nobreak="false">NCName</code>, the <code nobreak="false">NCName</code> comes first.</p></item></olist></item></olist><p>For example, the following shows a possible ordered sequence of version
                  numbers:</p><eg role="non-xml" xml:space="preserve">0-rc1 &lt; 0-rc2 &lt; 0 &lt; 1 = 1.0 &lt; 1.0.2 
   &lt; 1.0.3-rc1 &lt; 1.0.3 &lt; 1.0.3.2 &lt; 1.0.10</eg><note><p>The version number format defined here is designed to be general enough to
                     accommodate a variety of conventions in common use, and to allow useful
                     semantics for matching of versions and ranges of versions, without being
                     over-prescriptive. It is influenced by <bibref ref="SemVer"/>, but is not as
                     prescriptive, and it imposes no assumptions about backwards compatibility of
                     packages between successive versions.</p></note><p>Implementations <rfc2119>may</rfc2119> impose limits on the values
               used in a version number (or a version range: see below). Such limits are
               <termref def="dt-implementation-defined"/>. As a minimum, 
               a processor <rfc2119>must</rfc2119> accept version numbers including:</p><ulist><item><p>A numeric part containing four integers;</p></item><item><p>Each integer being in the range 0 to 999999;</p></item><item><p>An <code nobreak="false">NCName</code> of up to 100 characters</p></item></ulist><p>Dependencies between packages may specify a version range (see <specref ref="package-dependencies"/>). A version range represents a set of accepted
                  versions. The syntax of a version range is
                     shown below. Whitespace is permitted only where indicated, using the terminal
                     symbol <var>S</var>.</p><eg role="non-xml" xml:space="preserve">
        PackageVersionRange    ::=  AnyVersion | VersionRanges
        AnyVersion             ::=  "*"
        VersionRanges          ::=  VersionRange (S? "," S? VersionRange)*
        VersionRange           ::=  PackageVersion | VersionPrefix | 
                                      VersionFrom | VersionTo | VersionFromTo
        VersionPrefix          ::=  PackageVersion ".*"
        VersionFrom            ::=  PackageVersion "+"
        VersionTo              ::=  "to" S (PackageVersion | VersionPrefix)
        VersionFromTo          ::=  PackageVersion S 
                                      "to" S (PackageVersion | VersionPrefix)     
               </eg><p>The meanings of the various forms of version range are
                  defined below:</p><ulist><item><p>The range <code nobreak="false">AnyVersion</code> matches any version.</p></item><item><p>The range <code nobreak="false">VersionRanges</code> matches a version if any constituent
                           <code nobreak="false">VersionRange</code> matches that version.</p><p>For example, <code nobreak="false">9.5.0.8, 9.6.1.2</code>
                        matches those specific versions only, while <code nobreak="false">9.5.0.8, 9.6+</code>
                        matches either version 9.5.0.8 or any version from 9.6 onwards.</p></item><item><p>A range that is a <code nobreak="false">PackageVersion</code> matches that version only.</p></item><item><p>The range <code nobreak="false">VersionPrefix</code> matches any version whose leading
                           <termref def="dt-portion">portions</termref> are the same as the 
                           <termref def="dt-portion">portions</termref> in the <code nobreak="false">PackageVersion</code> part of the
                              <code nobreak="false">VersionPrefix</code>.</p><p>For example, <code nobreak="false">1.3.*</code> matches <code nobreak="false">1.3</code>, 
                           <code nobreak="false">1.3.5</code>,  <code nobreak="false">1.3.10.2</code>,  and
                           <code nobreak="false">1.3-beta</code>
                        (but not <code nobreak="false">1</code> or
                              <code nobreak="false">1.4</code>).</p><note><p>The <code nobreak="false">.*</code> indicates that additional 
                           <termref def="dt-portion">portions</termref> may follow; 
                           it does not indicate a substring match
                           on the final <termref def="dt-portion">portion</termref>. So
                              <code nobreak="false">1.3.*</code> does not match <code nobreak="false">1.35</code>, and
                              <code nobreak="false">3.3-beta.*</code> does not match <code nobreak="false">3.3-beta12</code>. Also,
                              <code nobreak="false">3.3-beta.*</code> does not match <code nobreak="false">3.3-beta.5</code>: this
                           is because the last dot is not a portion separator, but is part of the
                           final <code nobreak="false">NCName</code>. In fact, using <code nobreak="false">.*</code> after a version
                           number that includes an <code nobreak="false">NCName</code> portion is pointless, because
                           an <code nobreak="false">NCName</code> portion can never be followed by further
                           portions.</p></note></item><item><p>The range <code nobreak="false">VersionFrom</code> matches any version that is greater than
                        or equal to the version supplied.</p><p>For example <code nobreak="false">1.3+</code> matches
                           <code nobreak="false">1.3</code>,  <code nobreak="false">1.3.2</code>,  <code nobreak="false">1.4</code>, 
                        and <code nobreak="false">2.1</code> (but not <code nobreak="false">1.3-beta</code> or <code nobreak="false">1.2</code>).
                        And <code nobreak="false">1.3-beta+</code> matches <code nobreak="false">1.3-beta</code>, 
                           <code nobreak="false">1.3-gamma</code>,  <code nobreak="false">1.3.0</code>,  <code nobreak="false">1.4</code>,
                        and <code nobreak="false">8.0</code>, but not <code nobreak="false">1.3-alpha</code> or
                        <code nobreak="false">1.2</code>.</p></item><item><p>The range <code nobreak="false">VersionTo</code> matches any version that is less than or
                        equal to some version that matches the supplied 
                        <code nobreak="false">PackageVersion</code> or <code nobreak="false">VersionPrefix</code>.</p><p>For example, <code nobreak="false">to 4.0</code> matches <code nobreak="false">1.5</code>, 
                           <code nobreak="false">2.3</code>,  <code nobreak="false">3.8</code>,  <code nobreak="false">4.0</code>, 
                        and <code nobreak="false">4.0-beta</code> (but not <code nobreak="false">4.0.1</code>), while <code nobreak="false">to
                           3.3.*</code> matches <code nobreak="false">1.5</code> or <code nobreak="false">2.0.6</code> or
                           <code nobreak="false">3.3.4621</code>, but not <code nobreak="false">3.4.0</code> or
                           <code nobreak="false">3.4.0-beta</code>. </p></item><item><p>The range <code nobreak="false">VersionFromTo</code> matches any version that is greater
                        than or equal to the starting <code nobreak="false">PackageVersion</code>, and less than or
                        equal to some version that matches the ending 
                        <code nobreak="false">PackageVersion</code> or <code nobreak="false">VersionPrefix</code>.</p><p>For example, <code nobreak="false">1 to 5</code> matches <code nobreak="false">1.1</code>, 
                           <code nobreak="false">2.1</code>,  <code nobreak="false">3.1</code>,  or <code nobreak="false">5.0</code> (but
                        not <code nobreak="false">5.1</code>), while <code nobreak="false">1 to 5.*</code> matches all of these,
                        plus versions such as <code nobreak="false">5.7.2</code> (but not <code nobreak="false">6.0</code> or
                           <code nobreak="false">6.0-beta</code>). Similarly,
                              <code nobreak="false">1.0-beta to 1.0</code> matches <code nobreak="false">1.0-beta</code>,
                              <code nobreak="false">1.0-beta.2</code>, <code nobreak="false">1.0-gamma</code>, and <code nobreak="false">1.0</code>,
                           but not <code nobreak="false">1.0-alpha</code> or <code nobreak="false">1.0.1</code>.</p></item></ulist></div3><div3 id="package-dependencies"><head>Dependencies between Packages</head><p>When <termref def="dt-component">components</termref> in one <termref def="dt-package"/> reference components in another, the dependency of the first
                  package on the second must be represented by an <elcode>xsl:use-package</elcode>
                  element. This may appear in the <termref def="dt-principal-stylesheet-module"/>
               of the first package (which may be a <termref def="dt-package-manifest"/>), or
               it may appear in a <termref def="dt-stylesheet-module"/> that is referenced from
                  the <termref def="dt-principal-stylesheet-module"/> via one or more
               <elcode>xsl:include</elcode> declarations; however it must not be referenced
               via <elcode>xsl:import</elcode> declarations (this is to avoid complications
                     caused by multiple <elcode>xsl:use-package</elcode> declarations with
                     different <termref def="dt-import-precedence"/>).</p><p><termdef id="dt-use" term="use">If a package <var>Q</var> contains an
                        <elcode>xsl:use-package</elcode> element that references package
                        <var>P</var>, then package <var>Q</var> is said to <term>use</term> package
                        <var>P</var>. In this relationship package <var>Q</var> is referred to as
                     the <term>using</term> package, package <var>P</var> as the <term>used</term>
                     package.</termdef></p><p>The phrase <term>directly uses</term> is synonymous with <term>uses</term> as
                  defined above, while <term>directly or indirectly uses</term> refers to the
                  transitive closure of this relationship.</p><e:element-syntax xmlns:e="http://www.w3.org/1999/XSL/Spec/ElementSyntax" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" name="use-package">
      <e:in-category name="declaration"/>
      <e:attribute name="name" required="yes">
         <e:data-type name="uri"/>
      </e:attribute>
      <e:attribute name="package-version" required="no" default="'*'">
         <e:data-type name="string"/>
      </e:attribute>
      <e:choice repeat="zero-or-more">
         <e:element name="package-location"/>
         <e:element name="accept"/>
         <e:element name="override"/>
         <e:element name="with-param"/>
      </e:choice>
      <e:allowed-parents>
         <e:parent name="package"/>
         <e:parent name="stylesheet"/>
         <e:parent name="transform"/>
      </e:allowed-parents>
   </e:element-syntax><p>A <termref def="dt-package">package</termref> may be <termref def="dt-use">used</termref> by more than one other package, but the relationship
                     <rfc2119>must not</rfc2119> be cyclic. It is possible, but by no means
                  inevitable, that using the same package in more than one place within a stylesheet
                  will cause static errors due to the presence of conflicting components according
                  to the above rules. Where a package is successfully used by more than one other
                  package, its components may be overridden in different ways by different using
                  packages.</p><p>The <code nobreak="false">name</code> and <code nobreak="false">package-version</code> attributes together
                  identify the used package. The value of the
                        <code nobreak="false">package-version</code> attribute, if present, must conform to the
                     rules for a <code nobreak="false">PackageVersionRange</code> given in <specref ref="package-versions"/>; if omitted the value <code nobreak="false">*</code> is assumed,
                     which matches any version. The used package must have a name that is an exact
                     match for the name in the <code nobreak="false">name</code> attribute (using codepoint
                     comparison), and its explicit or implicit <code nobreak="false">package-version</code> must
                     match the version range given in the <code nobreak="false">package-version</code>
                     attribute.</p><p>Rules for determining the location of the package are described at 
                   <specref ref="package-locations"/>.</p><p>Rules for supplying parameters to the package are described at
                  <specref ref="supplying-package-parameters"/>.</p><p><error spec="XT" type="static" class="SE" code="3005"><p>It is a <termref def="dt-static-error"/> if a package is dependent on
                        itself, where package <var>A</var> is defined as being dependent on package
                           <var>B</var> if <var>A</var> contains an <elcode>xsl:use-package</elcode>
                        declaration that references <var>B</var>, or if <var>A</var> contains an
                           <elcode>xsl:use-package</elcode> declaration that references a package
                           <var>C</var> that is itself dependent on <var>B</var>.</p></error></p><p><error spec="XT" type="static" class="SE" code="3008"><p>It is a <termref def="dt-static-error"/> if an <elcode>xsl:use-package</elcode>
                  declaration appears in a <termref def="dt-stylesheet-module"/> that is not in the
                  same <termref def="dt-stylesheet-level"/> as the <termref def="dt-principal-stylesheet-module"/>
                  of the <termref def="dt-package"/>.</p></error></p><p>The <elcode>xsl:accept</elcode> and <elcode>xsl:override</elcode> elements are
                  used to modify the visibility or behavior of components acquired from the used
                  package; they are described in <specref ref="accepting-components"/> below.</p><note><p>It is not intrinsically an error to have two 
                  <elcode>xsl:use-package</elcode> declarations that identify the same package
                  (or different versions of the same package). This has the same effect as
                  having two declarations that identify packages with different names but
                  identical content. In most cases it will result in an error (<errorref spec="XT" class="SE" code="3050"/>)
                  due to the presence of multiple components with the same name; but 
                  no error would occur, for example, if the used package is empty, or if the 
                  two <elcode>xsl:use-package</elcode> declarations use <elcode>xsl:accept</elcode>
                  to accept non-overlapping subsets of the components in the used package.</p></note></div3><div3 id="package-locations"><head>Locating Packages</head><changes><change issue="366" PR="1888" date="2025-06-17">A new XSLT element, <code nobreak="false">xsl:package-location</code> is provide
                      to indicate to the processor where the required package is to be found.</change></changes><p>A package may be located either explicitly, through one or more
                            <elcode>xsl:use-package</elcode> elements, or implicitly, in an <termref def="dt-implementation-defined"/> mechanism. Providing multiple package locations 
                       allows a developer to create fallback mechanisms or perform diagnostics.</p><e:element-syntax xmlns:e="http://www.w3.org/1999/XSL/Spec/ElementSyntax" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" name="package-location">
        <e:attribute name="href" required="yes">
            <e:data-type name="uri"/>
        </e:attribute>
        <e:attribute name="path-in-archive" required="no">
            <e:data-type name="string"/>
        </e:attribute>
        <e:attribute name="archive-type" required="no">
            <e:data-type name="string"/>
        </e:attribute>
        <e:attribute name="is-priority" required="no" default="true()">
            <e:data-type name="boolean"/>
        </e:attribute>
        <e:attribute name="format" required="no">
            <e:data-type name="string"/>
        </e:attribute>
        <e:empty/>
        <e:allowed-parents>
            <e:parent name="use-package"/>
        </e:allowed-parents>
    </e:element-syntax><p>A <code nobreak="false">xsl:package-location</code> points to a resource that may or 
                    may not be an archive. If the target resource is an archive, then <code nobreak="false">xsl:package-location</code>:
                       <ulist><item><p> <rfc2119>must</rfc2119> have an attribute <code nobreak="false">path-in-archive</code>, specifying the 
                                 location of the package manifest within the archive. The value of 
                                 <code nobreak="false">path-in-archive</code> is normalized such that it always begins with the string <code nobreak="false">!/</code>
                                 (the result of <code nobreak="false">replace(., "^(!/)?(.+)", "!/$2")</code>).
                             </p></item><item><p> <rfc2119>may</rfc2119> have an attribute <code nobreak="false">archive-type</code>,
                                specifying the type of archive. Implementations <rfc2119>must</rfc2119> 
                                support the ZIP file format, as defined by <bibref ref="ISO21320"/>, the 
                                default archive format if the attribute is missing or the explicit format 
                                if the attribute has the value <code nobreak="false">zip</code>. All other values of this 
                                attribute are <termref def="dt-implementation-defined"/>.</p></item></ulist>
                    </p><p>It is a <termref def="dt-static-error"/> if the attribute <code nobreak="false">archive-type</code>
                      is present without the attribute <code nobreak="false">path-in-archive</code>, or if it does not have the
                      value <code nobreak="false">zip</code> or an <termref def="dt-implementation-defined"/> value.
                   </p><p>The attribute <code nobreak="false">href</code> takes an absolute or relative URI reference,
                        which is resolved as described in <specref ref="uri-references"/>, to 
                        locate the resource that is the <termref def="dt-package-manifest">package manifest</termref> 
                        or is the archive that contains the <termref def="dt-package-manifest"/>. </p><p>The URI scheme for archive resources is currently only provisionally defined (<bibref ref="rfc7595"/>),
                       with the syntax <code nobreak="false">jar:&lt;url&gt;!/[&lt;entry&gt;]</code>, but variations on this syntax are known (such as using
                       <code nobreak="false">zip</code> instead of <code nobreak="false">jar</code>). The entry is already accommodated by the attribute 
                       <code nobreak="false">archive-type</code>, so the following adjustments must be made to the value of <code nobreak="false">href</code>
                       that points to an archive:
                        <ulist><item><p>Remove "zip:" or "jar:" from the beginning of the value.</p></item><item><p>Remove <code nobreak="false">!/</code> and any string text that follows.</p></item></ulist>
                    </p><p>The attribute <code nobreak="false">format</code> takes a string, default value
                            <code nobreak="false">xslt</code> if the attribute is absent, specifying the format of
                        the <termref def="dt-package-manifest">package manifest</termref>. The value 
                        <code nobreak="false">xslt</code> indicates that the package manifest is a standard XML
                        resource as described in these specifications. All other values are <termref def="dt-implementation-defined"/>, allowing implementers to support optimized
                        formats for a package manifest, be it a compiled binary resource or a different XML 
                        format.</p><p><termdef id="dt-high-priority-package-location" term="high priority package location">A 
                         <code nobreak="false">xsl:package-location</code> without the attribute <code nobreak="false">is-priority</code>, 
                         or with <code nobreak="false">is-priority</code> set to <code nobreak="false">true</code> is a <term>high priority package 
                            location</term>.</termdef>
                      <termdef id="dt-low-priority-package-location" term="low priority package location">A 
                         <code nobreak="false">xsl:package-location</code> with <code nobreak="false">is-priority</code> set to <code nobreak="false">false</code> is a 
                         <term>low priority package location</term>.</termdef></p><p>Each <termref def="dt-high-priority-package-location"/> is processed in document order, followed by
                       <termref def="dt-implementation-defined"/> package locations, followed by each 
                       <termref def="dt-low-priority-package-location"/> in document order. <termdef id="dt-optimal-package-location" term="priority package location">The
                            first package location whose value of <code nobreak="false">href</code>, when resolved
                            as described in <specref ref="uri-references"/>, allows the system to
                            find the specified resource, and its entry if the resource is an archive, is
                            the <term>optimal package location</term>.</termdef> Once an optimal
                        package location is found, no other package locations are checked. </p><p>If the returned resource is an archive, the archive entry is to be treated as the
                     <termref def="dt-package-manifest"/>, otherwise the resource itself is to be
                  treated as the <termref def="dt-package-manifest"/>. The <termref def="dt-package-manifest"/> returned from the optimal package location is
                  checked against the implicit or explicit value of the attribute
                     <code nobreak="false">format</code>. If the resource does not conform to the rules for the
                  format type a <termref def="dt-static-error"/> is raised.</p><p>The <termref def="dt-package-manifest"/> is then checked against the the
                        package name and version specified in the <elcode>xsl:use-package</elcode>
                        declaration. If the resource does not conform to the rules for the name and
                        version, a <termref def="dt-static-error"/> is raised.</p><p><error spec="XT" type="static" class="SE" code="3000"><p>It is a <termref def="dt-static-error"/> if after evaluating each
                                    <elcode>xsl:package-location</elcode> declaration and <termref def="dt-implementation-defined"/> package location, no 
                               <termref def="dt-optimal-package-location"/> is found.</p></error></p><p><error spec="XT" type="static" class="SE" code="3002"><p>It is a <termref def="dt-static-error"/> if the <termref def="dt-package-manifest"/> returned by the <termref def="dt-optimal-package-location"/> does not conform to the
                                rules of the implicit or explicit value of attribute
                                    <code nobreak="false">format</code>.</p></error></p><p><error spec="XT" type="static" class="SE" code="3003"><p>It is a <termref def="dt-static-error"/> if the <termref def="dt-package-manifest"/> returned by the <termref def="dt-optimal-package-location"/> does not conform to the
                                name and version specified in an <elcode>xsl:use-package</elcode>
                                declaration.</p></error></p><p><error spec="XT" type="static" class="SE" code="3004"><p>It is a <termref def="dt-static-error"/> if the attribute <code nobreak="false">archive-type</code>
                               is present without the attribute <code nobreak="false">path-in-archive</code>, or if it does not have the
                               value <code nobreak="false">zip</code> or an <termref def="dt-implementation-defined"/> value.</p></error></p><note><p>Use of the package name as a dereferenceable URI is <rfc2119>not
                                recommended</rfc2119>, because the intent of the packaging feature
                            is to allow a package to be distributed as reusable code and therefore
                            to exist in many different locations.</p></note><note><p>Depending on the implementation architecture, there may be a need to
                            locate used packages both during static analysis (for example, to get
                            information about the names and type signatures of the components
                            exposed by the used package), and also at evaluation time (to link to
                            the implementation of these components so they can be invoked). A
                            failure to locate a package may cause an error at either stage.</p></note><example id="example-of-package-locations"><head>Example configuration of
                            <elcode>xsl:package-location</elcode>s.</head><p>Consider a using package <var>Q</var>, invoked as follows:</p><eg role="xslt-document" xml:space="preserve">&lt;xsl:use-package name="Q" version="3.0" xmlns:saxon="http://saxon.sf.net/"/&gt;
     &lt;package-location href="q-dev.xsl" use-when="$diagnostics-on"/&gt;
     &lt;package-location _href="file:/{$prod-path}/q.zip" path-in-archive="q.sef" 
           is-priority="true" format="saxon:sef"/&gt;
     &lt;package-location href="file:/D:/fallback/q.xsl" format="xslt" is-priority="false"/&gt;
&lt;/xsl:package&gt;</eg><p>The first <elcode>xsl:package-location</elcode> will be the first to be evaluated
                           only if the static parameter <code nobreak="false">$diagnostics-on</code> is <code nobreak="false">true</code>, in which case
                           the local file <code nobreak="false">q-dev.xsl</code>, if it exists, will be the <termref def="dt-optimal-package-location"/>. 
                            The next <elcode>xsl:package-location</elcode> to be checked points to the archive resource located by 
                            the path <code nobreak="false">file:/{$prod-path}/q.zip</code> (which depends upon
                            the value of static parameter <code nobreak="false">$prod-path</code>), and the entry <code nobreak="false">q.sef</code>
                            at the root of the archive (assumed to be a ZIP file for lack of a 
                            <code nobreak="false">archive-type</code>). Next will be any <termref def="dt-implementation-defined"/> package locations. Last will be
                            the last <code nobreak="false">xsl:package-location</code>, a <termref def="dt-low-priority-package-location"/>, which 
                           serves as a local fallback.</p><p>Each of these package locations will be evaluated in turn. If no 
                            <termref def="dt-optimal-package-location"/> is found, an error is raised. 
                            Only the first resource to qualify as the <termref def="dt-optimal-package-location"/> 
                            will be checked, to ensure it conforms to the file format and the package name and version.</p></example></div3><div3 id="supplying-package-parameters"><head>Supplying Package Parameters</head><changes><change issue="272" PR="2474" date="2026-02-18">The <elcode>xsl:use-package</elcode> element
                      can have <elcode>xsl:with-param</elcode> children to supply values for global
                      parameters declared in the used package.</change></changes><p>An <elcode>xsl:use-package</elcode> element may have zero or more <elcode>xsl:with-param</elcode>
               children to supply values for <termref def="dt-stylesheet-parameter">stylesheet parameters</termref>
               declared in the <termref def="dt-library-package"/> by means of <termref def="dt-top-level"/> 
                  <elcode>xsl:param</elcode> declarations. This applies both to <termref def="dt-static-parameter">static parameters</termref>,
               and to non-static parameters.</p><p>The actual value of the supplied parameter must be known statically.
                  The <elcode>xsl:with-param</elcode> element must therefore have a <code nobreak="false">select</code>
                  attribute, and the value of the <code nobreak="false">select</code> attribute must be
                  a <termref def="dt-static-expression"/>. In other respects it is evaluated in the usual way: 
                  see <specref ref="with-param"/> and <specref ref="variable-values"/>. </p><p>
                  <error spec="XT" type="static" class="SE" code="3012"><p>It is a <termref def="dt-static-error"> static error</termref> if an
                     <elcode>xsl:with-param</elcode> child of an <elcode>xsl:use-package</elcode> 
                        declaration has no <code nobreak="false">select</code>
                        attribute, or if the value of the <code nobreak="false">select</code> attribute
                        is not a <termref def="dt-static-expression"/>.
                     </p></error>
               </p><p>It is not an error to supply a value for a parameter which the library package does not declare. Such a value
               is simply ignored.</p><note><p>The reason for this rule is to make it easier to write code that works with multiple versions of 
               a library package.</p></note><p>Especially in the case of <termref def="dt-static-parameter">static parameters</termref>, 
                  but potentially also for non-static
               parameters, it is possible that the values of the parameters in the <termref def="dt-library-package"/> are 
               already fixed, having been supplied at some stage during the preparation of the <termref def="dt-library-package"/>.
               </p><p>
                  <error spec="XT" type="static" class="SE" code="3013"><p>It is a <termref def="dt-static-error"> static error</termref> if an
                     <elcode>xsl:with-param</elcode> child of an <elcode>xsl:use-package</elcode>
                     declaration attempts to supply a value for a parameter that has already
                     been bound using some external mechanism. The processor <rfc2119>may</rfc2119>
                     ignore this error if the value being supplied is identical to the value
                     to which the parameter has already been bound.
                     </p></error>
               </p><note><p>Under the rules for global <termref def="dt-stylesheet-parameter">stylesheet parameters</termref>, 
                     it is an error if a parameter is required
                  and no value is supplied: see <errorref spec="XT" class="DE" code="0050"/>. The value of a required
                  parameter may be supplied either using this mechanism, or using some external mechanism.</p></note><note><p>In the case of a non-static <termref def="dt-stylesheet-parameter"/>, it is also possible
                  (in effect) to supply a value by overriding the parameter with an <elcode>xsl:variable</elcode>
                  or <elcode>xsl:param</elcode> declaration within the <elcode>xsl:override</elcode> child of
                  the <elcode>xsl:use-package</elcode> declaration.</p></note></div3><div3 id="named-components"><head>Named Components in Packages</head><p>This section discusses the use of named components in packages.</p><p>The components which can be declared in one package and
                  referenced in another are: <termref def="dt-stylesheet-function">functions</termref>, <termref def="dt-named-template">named
                     templates</termref>, <termref def="dt-attribute-set">attribute sets</termref>,
                     <termref def="dt-mode">modes</termref>,  and <termref def="dt-global-variable">global variables</termref> and <termref def="dt-stylesheet-parameter">parameters</termref>.</p><p>In addition, <termref def="dt-key">keys</termref> and <termref def="dt-accumulator">accumulators</termref>
                  are classified as named components because they can contain references to
                  components in another package, even though they cannot themselves be referenced
                  from outside the package.</p><p>Named and unnamed <termref def="dt-mode">modes</termref> come within the scope of this section, but there are
                  differences noted in <specref ref="modes-and-packages"/>.</p><p>Not all <termref def="dt-declaration">declarations</termref> result in <termref def="dt-component">components</termref>:</p><ulist><item><p>Named <termref def="dt-declaration">declarations</termref> that can neither be referenced from outside their
                        containing package, nor can contain references to components in other
                        packages (examples are <elcode>xsl:output</elcode>,
                           <elcode>xsl:character-map</elcode>, and
                           <elcode>xsl:decimal-format</elcode>) are not considered to be components
                        and are therefore outside the scope of this section.</p></item><item><p>Some declarations, such as <elcode>xsl:decimal-format</elcode> and
                           <elcode>xsl:strip-space</elcode>, declare aspects of the processing
                        context which are not considered to be components as defined here.</p></item><item><p><termref def="dt-template-rule">Template rules</termref>
                           (<elcode>xsl:template</elcode> with a <code nobreak="false">match</code> attribute) are
                        also not considered to be components for the purposes of this section, which
                        is concerned only with components that are bound by name. However, when an
                           <elcode>xsl:template</elcode> has both a <code nobreak="false">match</code> attribute and
                        a <code nobreak="false">name</code> attribute, then it establishes both a template rule and
                        a <termref def="dt-named-template">named template</termref>, and in its role
                        as a named template it comes within the scope of this discussion.</p></item><item><p>A named declaration, for example a named template, a function, 
                         or a global
                        variable, may be overridden within the same package by another like-named
                        declaration having higher <termref def="dt-import-precedence">import
                           precedence</termref>. When a declaration is overridden in this way it cannot
                        be referenced by name either from within its containing package or
                        from outside that package. </p></item><item><p>In the case of <elcode>xsl:attribute-set</elcode>
                        and <elcode>xsl:key</elcode> declarations, several declarations combine to
                        form a single component.</p></item></ulist><p>The section is largely concerned with details of the rules that affect references
                  from one component to another by name, whether the components are in the same
                  package or in different packages. The rules are designed to meet a number of
                  requirements:</p><ulist><item><p>A component defined in one package can be overridden by a component in
                        another package, provided the signatures are type-compatible.</p></item><item><p>The author of a package can declare whether the components in the package
                        are public or private (that is, whether or not they can be used from outside
                        the package) and whether they are final, overridable, or abstract (that is
                        whether they can or must be overridden by the using package).</p></item><item><p>Within an application, two packages can make use of a common library and
                        override its components in different ways.</p></item><item><p>Visibility of components can be defined either as part of the declaration of
                        the component, or in the package manifest.</p></item><item><p>An application that wishes to make use of a <termref def="dt-library-package">library package</termref> can be selective about
                        which components from the library it acquires, perhaps to avoid name clashes
                        between components acquired from different libraries.</p></item></ulist><p><termdef id="dt-component" term="component">The term <term>component</term> is
                     used to refer to any of the following: a <termref def="dt-stylesheet-function">stylesheet function</termref>, a <termref def="dt-named-template">named
                        template</termref>, a <termref def="dt-mode">mode</termref>, an <termref def="dt-accumulator-function">accumulator</termref>, an <termref def="dt-attribute-set">attribute set</termref>, a <termref def="dt-key">key</termref>, <termref def="dt-global-variable">global variable</termref>, or a <termref def="dt-mode">mode</termref>.</termdef></p><p><termdef id="dt-symbolic-identifier" term="symbolic identifier">The <term>symbolic
                        identifier</term> of a <termref def="dt-component">component</termref> is a
                     composite name used to identify the component uniquely within a package. The
                     symbolic identifier comprises the kind of component (stylesheet function, named
                     template, accumulator, attribute set, global
                     variable, key, or mode), the <termref def="dt-expanded-qname">expanded
                        QName</termref> of the component (namespace URI plus local name), and in the
                     case of stylesheet functions, <phrase diff="chg" at="variadicity">the upper
                     bound of the <termref def="dt-arity-range"/></phrase>.</termdef></p><note><p>In the case of the <termref def="dt-unnamed-mode"/>,
                     the expanded QName of the component may be considered to be some
                     system-allocated name different from any user-defined mode name.</p></note><p><termdef id="dt-homonymous" term="homonymous">Two <termref def="dt-component">components</termref> are said to be <term>homonymous</term> if they have
                     the same <termref def="dt-symbolic-identifier">symbolic
                     identifier</termref>.</termdef></p><p>Every <termref def="dt-component">component</termref> has a <termref def="dt-declaration">declaration</termref> in some <termref def="dt-stylesheet-module"/> and therefore within some <termref def="dt-package">package</termref>. In the
                     case of <termref def="dt-attribute-set">attribute sets</termref> and <termref def="dt-key">keys</termref>, there may be several declarations. The
                  declaration is an element in an XDM tree representing the stylesheet module.
                  Declarations therefore have identity, based on XDM node identity.</p><p><termdef id="dt-declaring-package" term="declaring package">The <term>declaring
                        package</term> of a <termref def="dt-component">component</termref> is the
                     package that contains the declaration (or,
                        in the case of <elcode>xsl:attribute-set</elcode> and
                           <elcode>xsl:key</elcode>, multiple declarations) of the
                     component.</termdef></p><p>When a <termref def="dt-component">component</termref> declared in one <termref def="dt-package">package</termref> is made available in another, the using
                  package will contain a separate component that can be regarded as a modified copy
                  of the original. The new component shares the same <termref def="dt-symbolic-identifier">symbolic identifier</termref> as the original, and
                  it has the same <termref def="dt-declaration">declaration</termref>, but it has
                  other properties such as its <termref def="dt-visibility">visibility</termref>
                  that may differ from the original.</p><p><termdef id="dt-containing-package" term="containing package">A
                     component declaration results in multiple components, one in the package in
                     which the declaration appears, and potentially one in each package that uses
                     the declaring package, directly or indirectly, subject to the visibility of the
                     component. Each of these multiple components has the same <termref def="dt-declaring-package"/>, but each has a different <term>containing
                        package</term>. For the original component, the declaring package and the
                     containing package are the same; for a copy of a component made as a result of
                     an <elcode>xsl:use-package</elcode> declaration, the declaring package will be
                     the original package, and the containing package will be the package in which
                     the <elcode>xsl:use-package</elcode> declaration appears.</termdef></p><note><p>Within this specification, we generally use the
                     notation <var>C/P</var> for a component named C whose declaring package and
                     containing package are both <var>P</var>; and the notation <var>C/PQ</var> for
                     a component whose containing package is <var>P</var> and whose declaring
                     package is <var>Q</var> (that is, a component in <var>P</var> that is derived
                     from a component <var>C/Q</var> in the used package <var>Q</var>).</p></note><p>The properties of a <termref def="dt-component">component</termref> are as
                  follows:</p><ulist><item><p>The original <termref def="dt-declaration">declaration</termref> of the
                        component.</p></item><item><p>The <termref def="dt-package">package</termref> to which the component
                        belongs (called its <term>containing</term> package, not to be confused with
                        the <termref def="dt-declaring-package">declaring package</termref>).</p></item><item><p>The <termref def="dt-symbolic-identifier">symbolic identifier</termref> of
                        the component.</p></item><item><p>The <termref def="dt-visibility">visibility</termref> of the component,
                        which determines the way in which the component is seen by other components
                        within the same package and within using packages. This is one of
                           <code nobreak="false">public</code>, <code nobreak="false">private</code>, <code nobreak="false">abstract</code>,
                           <code nobreak="false">final</code>, or <code nobreak="false">hidden</code>. The visibility of components
                        is discussed further in <specref ref="visibility"/>.</p></item><item><p>A set of bindings for the <termref def="dt-symbolic-reference">symbolic
                           references</termref> in the component. The way in which these bindings
                        are established is discussed further in <specref ref="component-references"/>.</p></item></ulist><note><p>When a function <var>F</var> defined in a package <var>P</var> is acquired by
                     two using packages <var>Q</var> and <var>R</var>, we may think of <var>P</var>,
                     <var>Q</var>, and <var>R</var> as all providing access to the “same”
                     function. The detailed semantics, however, demand an understanding that there
                     is one function declaration, but three components. The three components
                     representing the function <var>F</var> within packages <var>P</var>,
                        <var>Q</var>, and <var>R</var> have some properties in common (the same
                     symbolic identifier, the same declaration), but other properties (the
                     visibility and the bindings of symbolic references) that may vary from one of
                     these components to another.</p></note><p><termdef id="dt-symbolic-reference" term="symbolic reference">The <termref def="dt-declaration">declaration</termref> of a component includes
                     constructs that can be interpreted as references to other <termref def="dt-component">components</termref> by means of their <termref def="dt-symbolic-identifier">symbolic identifiers</termref>. These
                     constructs are generically referred to as <term>symbolic references</term>.
                     Examples of constructs that give rise to symbolic references are the
                        <code nobreak="false">name</code> attribute of <elcode>xsl:call-template</elcode>; the
                        <code nobreak="false">[xsl:]use-attribute-sets</code> attribute of
                     <elcode>xsl:copy</elcode>, <elcode>xsl:element</elcode>, and <termref def="dt-literal-result-element">literal result elements</termref>; the
                        explicit or implicit
                     <code nobreak="false">mode</code> attribute of <elcode>xsl:apply-templates</elcode>; XPath
                     variable references referring to global variables; XPath static function calls (including partial function
                        applications) referring to <termref def="dt-stylesheet-function">stylesheet functions</termref>; and
                        named function references (example: <code nobreak="false">my:f#1</code>) referring to
                        stylesheet functions.
                     </termdef></p><p>Symbolic references exist as properties of the <termref def="dt-declaration">declaration</termref> of a <termref def="dt-component">component</termref>.
                  The <termref def="dt-symbolic-identifier">symbolic identifier</termref> being
                  referred to can be determined straightforwardly from the syntactic form and
                  context of the reference: for example, the instruction <code nobreak="false">&lt;xsl:value-of
                     select="f:price($o)" xmlns:f="http://f.com/"/&gt;</code> contains a symbolic
                  reference to a function with expanded name <code nobreak="false">{http://f.com/}price</code> and
                  with arity=1. However, because there may be several (homonymous) function
                  components with this symbolic identifier, translating this symbolic reference into
                  a reference to a specific component (a process called “binding”) is less
                  straightforward, and is described in the text that follows. </p><p>The process of assembling a stylesheet from its constituent packages is primarily
                  a process of binding these symbolic references to actual components. Within any
                     <termref def="dt-component">component</termref> whose <termref def="dt-declaration">declaration</termref> is <var>D</var>, there is a set of
                  bindings; each binding is an association between a <termref def="dt-symbolic-reference">symbolic reference</termref> in <var>D</var> and a
                     <termref def="dt-component">component</termref> whose <termref def="dt-symbolic-identifier">symbolic identifier</termref> matches the outward
                  reference. Outward references for which a component <var>C</var> contains a
                  binding are said to be <term>bound</term> in <var>C</var>; those for which
                     <var>C</var> contains no binding are said to be <term>unbound</term>.</p><p>For example, suppose that in some package <var>Q</var>, function <var>A</var>
                  calls <var>B</var>, which in turn calls <var>C</var>, and that <var>B</var> is
                     <code nobreak="false">private</code>. Now suppose that in some package <var>P</var> which uses
                     <var>Q</var>, <var>C</var> is overridden. The effect of the binding process is
                  that <var>P</var> will contain three components corresponding to <var>A</var>,
                     <var>B</var>, and <var>C</var>, which we might call <var>A/P</var>,
                     <var>B/P</var>, and <var>C/P</var>. The <termref def="dt-declaration">declarations</termref> of <var>A/P</var> and <var>B/P</var> are in package
                     <var>Q</var>, but the declaration of <var>C/P</var> is in <var>P</var>. The
                  internal visibility of <var>B/P</var> will be <code nobreak="false">hidden</code> (meaning that it
                  cannot be referenced from within <var>P</var>), and <var>B/P</var> will contain a
                  binding for the component <var>C/P</var> that corresponds to the outward reference
                  from <var>B</var> to <var>C</var>. The effect is that when <var>A</var> calls
                     <var>B</var> and <var>B</var> calls <var>C</var>, it is the overriding version
                  of <var>C</var> that is executed.</p><p>In another package <var>R</var> that uses <var>Q</var> without overriding
                     <var>C</var>, there will be three different components <var>A/R</var>,
                     <var>B/R</var>, and <var>C/R</var>. This time the declaration of all three
                  components is in the original package <var>Q</var>. Component <var>B/R</var> will
                  contain a binding to <var>C/R</var>, so in this package, the original version of
                     <var>C</var> is executed. The fact that one package <var>P</var> overrides
                     <var>C</var> thus has no effect on <var>R</var>, which does not override
                  it.</p><p>The binding process outlined above is described in more detail in <specref ref="component-references"/>.</p><p>Template rules are not components in their own right;
                  unlike named templates, they are never referenced by name. Component references
                  within a template rule (for example, references to functions, global variables, or
                  named templates) are treated as occurring within the component that represents the
                  containing mode. This includes component references within the match patterns of
                  template rules. If a template rule lists several modes, it is treated as if there
                  were multiple template rules one in each mode.</p><p>An <elcode>xsl:apply-templates</elcode> instruction
                  with no <code nobreak="false">mode</code> attribute is treated as a reference to the <termref def="dt-default-mode"/>
                  defined for that <termref def="dt-instruction"/> (see <specref ref="default-mode"/>), which in turn defaults to the <termref def="dt-unnamed-mode"/>. An implicit
                  reference to the unnamed made is treated in the same way as any other <termref def="dt-symbolic-reference"/>. Note that there is an unnamed mode in every
                  package, and the unnamed mode always has private visibility.</p><p>Where an <elcode>xsl:template</elcode> element has both
                  a <code nobreak="false">name</code> and a <code nobreak="false">match</code> attribute, it is treated as if there
                  were two separate <elcode>xsl:template</elcode> elements, one with a
                     <code nobreak="false">name</code> attribute and one with a <code nobreak="false">match</code> attribute. </p><p><termref def="dt-key">Keys</termref>
                  and <termref def="dt-accumulator">accumulators</termref> behave rather differently from other
                  components. Their visibility is always private, which means they can only be used
                  within their declaring package. In addition, the component binding is generally
                  made dynamically rather than statically, by
                     virtue of a string passed as an argument to the function
                        <function>key</function>, <function>accumulator-before</function>, or
                        <function>accumulator-after</function>. (In the case of accumulators, there
                     can also be static references: see the <code nobreak="false">use-accumulators</code> attribute
                     of <elcode>xsl:source-document</elcode>, 
                     <elcode>xsl:merge-source</elcode>, and <elcode>xsl:mode</elcode>.) 
                     However, outward references from key
                  definitions and <termref def="dt-accumulator">accumulators</termref> to other components (such as global
                  variables and functions) behave in the same way as component references contained
                  in any other private component, in that they may be re-bound to an overriding
                  declaration of the target component.</p><div4 id="visibility"><head>Visibility of Components</head><changes><change issue="272" PR="2474" date="2026-02-18">The rules for the visibility of
                     stylesheet parameters have changed; this may cause some incompatibility.</change></changes><p><termdef id="dt-visibility" term="visibility">The <term>visibility</term> of a
                           <termref def="dt-component">component</termref> is one of:
                           <code nobreak="false">private</code>, <code nobreak="false">public</code>, <code nobreak="false">abstract</code>,
                           <code nobreak="false">final</code>, or <code nobreak="false">hidden</code>.</termdef></p><p>The meanings of these visibility values is as follows:</p><glist><gitem><label>public</label><def><p>The component can be referenced from other components in this package
                              or in any using package; it can be overridden by a different component
                              in any using package.</p></def></gitem><gitem><label>private</label><def><p>The component can be referenced from other components in this
                              package; it cannot be referenced or overridden within a using
                              package.</p></def></gitem><gitem><label>abstract</label><def><p>The component can be referenced from other components in this package
                              or in any using package; in a using package it can either remain
                              abstract or be overridden by a different component. </p></def></gitem><gitem><label>final</label><def><p>The component can be referenced from other components in this package
                              or in any using package; it cannot be overridden by a different
                              component in any using package.</p></def></gitem><gitem><label>hidden</label><def><p>The component cannot be referenced from other components in this
                              package; it cannot be referenced or overridden within a using
                              package.</p></def></gitem></glist><note><p>The visibility of a component in a package <var>P</var> primarily affects
                        how the component can be used in other packages, specifically, packages that
                        use <var>P</var>. There is one exception: if the visibility is
                           <code nobreak="false">hidden</code>, it also affects how the component can be used within
                           <var>P</var>.</p></note><p>When a component is declared within a particular
                     package, its <termref def="dt-visibility">visibility</termref>, which affects
                     how it can be used in other (using) packages, depends on two factors: the value
                     of the <code nobreak="false">visibility</code> declaration on the declaration itself (if
                     present), and the rules given in the <elcode>xsl:expose</elcode> declarations
                     of the package manifest.</p><p>The <elcode>xsl:function</elcode>, <elcode>xsl:template</elcode>,
                        <elcode>xsl:attribute-set</elcode>, <elcode>xsl:variable</elcode>, 
                        <elcode>xsl:mode</elcode>, <elcode>xsl:item-type</elcode>, and <elcode>xsl:record-type</elcode>
                     <termref def="dt-declaration">declarations</termref> each have an optional
                        <code nobreak="false">visibility</code> attribute. The permitted value is some subset of <code nobreak="false">private</code>,
                        <code nobreak="false">public</code>, <code nobreak="false">abstract</code>, or <code nobreak="false">final</code> (never
                        <code nobreak="false">hidden</code>). In the case of
                           an <elcode>xsl:param</elcode> element there is no explicit 
                           <code nobreak="false">visibility</code> attribute; rather the declaration has the
                           implicit attribute <code nobreak="false">visibility="public"</code>.</p><p>Any <elcode>xsl:expose</elcode> declarations that
                     appear as children of <elcode>xsl:package</elcode> define the visibility of
                     components whose declaration has no explicit <code nobreak="false">visibility</code> attribute,
                     and can also be used to reduce the visibility of components where this
                     attribute is present.</p><e:element-syntax xmlns:e="http://www.w3.org/1999/XSL/Spec/ElementSyntax" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" name="expose">
      <e:attribute name="component" required="yes">
         <e:constant value="template"/>
         <e:constant value="function"/>
         <e:constant value="attribute-set"/>
         <e:constant value="variable"/>
         <e:constant value="mode"/>
         <e:constant value="item-type"/>
         <e:constant value="record-type"/>
         <e:constant value="*"/>
      </e:attribute>
      <e:attribute name="names" required="yes">
         <e:data-type name="tokens"/>
      </e:attribute>
      <e:attribute name="visibility" required="yes">
         <e:constant value="public"/>
         <e:constant value="private"/>
         <e:constant value="final"/>
         <e:constant value="abstract"/>
         <!--<e:constant value="hidden"/>-->
      </e:attribute>
      <e:empty/>
      <e:allowed-parents>
         <e:parent name="package"/>
      </e:allowed-parents>
   </e:element-syntax><p>The <elcode>xsl:expose</elcode> element allows the <termref def="dt-visibility"/> of selected components within a package to be defined.</p><p>The components in question are identified using their <termref def="dt-symbolic-identifier">symbolic identifiers</termref>. The
                        <code nobreak="false">component</code> attribute defines the kind of component that is
                        selected.
                     The value <code nobreak="false">*</code> means “all component kinds”;
                        in this case the value of the <code nobreak="false">names</code> attribute must be a <xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="XP40" ref="prod-xpath40-Wildcard" xlink:type="simple">Wildcard</xnt>.</p><p>An <elcode>xsl:expose</elcode> declaration has no effect on the 
                     <termref def="dt-unnamed-mode"/>, which is always private to a package.</p><p>The <code nobreak="false">names</code> attribute selects a subset of these components by name
                     (and in the case of functions, arity); its value is a whitespace-separated
                     sequence of tokens each of which is either a <xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="XP40" ref="prod-xpath40-NameTest" xlink:type="simple">NameTest</xnt> or a <xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="XP40" ref="prod-xpath40-NamedFunctionRef" xlink:type="simple">NamedFunctionRef</xnt>. (Examples are
                        <code nobreak="false">*</code>, <code nobreak="false">p:*</code>, <code nobreak="false">*:local</code>,
                     <code nobreak="false">p:local</code>, and <code nobreak="false">p:local#2</code>.)</p><p>The value may be a <code nobreak="false">NamedFunctionRef</code> only in the case of stylesheet
                     functions, and distinguishes functions with the same name and different
                     arity. <phrase diff="add" at="2022-01-01">A <xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="XP40" ref="prod-xpath40-NameTest" xlink:type="simple">NameTest</xnt>
                     on its own (that is, with no arity) cannot be used to identify a function.</phrase></p><p>The visibility of a 
                     named template, function, variable, attribute set, mode,
                     named item type, or named record type
                     declared within a package is the first of the following that applies, subject to consistency
                     constraints which are defined below:</p><olist><item><p>The visibility of a <termref def="dt-stylesheet-parameter"/> declared using
                           a <termref def="dt-top-level"/> <elcode>xsl:param</elcode> element is
                           always <code nobreak="false">private</code>.</p><p>No <elcode>xsl:expose</elcode> element
                        ever matches an <elcode>xsl:param</elcode> component, so the visibility
                        cannot be changed. Stylesheet parameters, of course, are visible externally
                        to the calling application (which must be able to set their values). They
                        are also visible within an <elcode>xsl:with-param</elcode> child of an
                        <elcode>xsl:use-package</elcode> declaration, allowing a using package
                        to set values for the parameters of a <termref def="dt-library-package"/>.</p><p>It is possible to expose the value of a stylesheet parameter by binding
                        a public global variable to its value:</p><eg xml:space="preserve">&lt;xsl:param name="language" as="xs:string" select="'en'"/&gt;
&lt;xsl:variable name="library-language" as="xs:string" 
              select="$language" visibility="public"/&gt;</eg><p>This works for both <termref def="dt-static-parameter">static</termref> and non-static parameters.</p><note><p>XSLT 3.0 made conflicting statements on this; there were places in the specification
                        that said all stylesheet parameters were public, others that said static parameters were private.
                        Making stylesheet parameters public, and hence overridable, causes problems with the use
                        of <code nobreak="false">xsl:original</code> in an overriding declaration. The rules have therefore been changed.</p></note></item><item><p>If the package manifest contains an <elcode>xsl:expose</elcode> element
                           that matches this component by virtue of an explicit <code nobreak="false">EQName</code>
                           or <code nobreak="false">NamedFunctionRef</code> (that is, not by virtue of a wildcard
                           match), then the value of the <code nobreak="false">visibility</code> attribute of the
                           last such <elcode>xsl:expose</elcode> element in document order (call
                           this the <term>explicit exposed visibility</term>).</p></item><item><p>If the declaration of the component has a <code nobreak="false">visibility</code>
                           attribute, then the value of this attribute (call this the <term>declared
                              visibility</term>).</p></item><item><p>If the package manifest contains an <elcode>xsl:expose</elcode> element
                           that matches this component by virtue of a wildcard match that specifies
                           either the namespace part of the component name or the local part of the
                           name (for example, <code nobreak="false">prefix:*</code> or <code nobreak="false">*:local</code> or
                              <code nobreak="false">Q{uri}*</code>), then the value of the <code nobreak="false">visibility</code>
                           attribute of the last such <elcode>xsl:expose</elcode> element in
                           document order.</p></item><item><p>If the package manifest contains an <elcode>xsl:expose</elcode> element
                           that matches this component by virtue of a wildcard match that matches
                           all names (that is, <code nobreak="false">*</code>), then the value of the
                              <code nobreak="false">visibility</code> attribute of the last such
                              <elcode>xsl:expose</elcode> element in document order.</p></item><item><p>Otherwise, <code nobreak="false">private</code>.</p></item></olist><note><p>In the above rules, no distinction is made between declarations that specify
                  a specific component kind, and those that specify <code nobreak="false">component="*"</code>. If both match,
                  the value of the <code nobreak="false">component</code> attribute plays no role in deciding which 
                  declaration wins.</p></note><p>If both a declared visibility and an explicit
                     exposed visibility exist for the same component, then as mentioned above, they
                     must be consistent. This is determined by reference to the following table,
                     where the entry N/P means “not permitted”. (In cases where the combination is
                     permitted, the actual visibility is always the same as the visibility
                     determined by <elcode>xsl:expose</elcode>.)</p><table class="data" border="1" cellpadding="5" width="100%"><caption>Relationship of Exposed Visibility to Declared Visibility</caption><thead><tr><th rowspan="2" colspan="1" align="left" valign="top">Explicit exposed visibility</th><th colspan="4" rowspan="1" align="left" valign="top">Declared visibility</th></tr><tr><th rowspan="1" colspan="1" align="left" valign="top">public</th><th rowspan="1" colspan="1" align="left" valign="top">private</th><th rowspan="1" colspan="1" align="left" valign="top">final</th><th rowspan="1" colspan="1" align="left" valign="top">abstract</th></tr></thead><tbody><tr><th rowspan="1" colspan="1" align="left" valign="top">public</th><td rowspan="1" colspan="1" align="left" valign="top">public</td><td rowspan="1" colspan="1" align="left" valign="top">N/P</td><td rowspan="1" colspan="1" align="left" valign="top">N/P</td><td rowspan="1" colspan="1" align="left" valign="top">N/P</td></tr><tr><th rowspan="1" colspan="1" align="left" valign="top">private</th><td rowspan="1" colspan="1" align="left" valign="top">private</td><td rowspan="1" colspan="1" align="left" valign="top">private</td><td rowspan="1" colspan="1" align="left" valign="top">private</td><td rowspan="1" colspan="1" align="left" valign="top">N/P</td></tr><tr><th rowspan="1" colspan="1" align="left" valign="top">final</th><td rowspan="1" colspan="1" align="left" valign="top">final</td><td rowspan="1" colspan="1" align="left" valign="top">N/P</td><td rowspan="1" colspan="1" align="left" valign="top">final</td><td rowspan="1" colspan="1" align="left" valign="top">N/P</td></tr><tr><th rowspan="1" colspan="1" align="left" valign="top">abstract</th><td rowspan="1" colspan="1" align="left" valign="top">N/P</td><td rowspan="1" colspan="1" align="left" valign="top">N/P</td><td rowspan="1" colspan="1" align="left" valign="top">N/P</td><td rowspan="1" colspan="1" align="left" valign="top">abstract</td></tr></tbody></table><p>
                     <error spec="XT" type="static" class="SE" code="3010"><p>It is a <termref def="dt-static-error">static error</termref> if the
                           explicit exposed visibility of a component is inconsistent with its
                           declared visibility, as defined in the above table. (This error occurs
                           only when the component declaration has an explicit
                              <code nobreak="false">visibility</code> attribute, and the component is also listed
                           explicitly by name in an <elcode>xsl:expose</elcode> declaration.)</p></error>
                  </p><p>
                     <error spec="XT" type="static" class="SE" code="3020"><p>It is a <termref def="dt-static-error">static error</termref> if a token
                           in the <code nobreak="false">names</code> attribute of <elcode>xsl:expose</elcode>, other
                           than a wildcard, matches no component in the containing package.</p></error>
                  </p><p>
                     <error spec="XT" type="static" class="SE" code="3022"><p>It is a <termref def="dt-static-error">static error</termref> if the 
                           <code nobreak="false">component</code> attribute of <elcode>xsl:expose</elcode> specifies <code nobreak="false">*</code>
                           (meaning all component kinds) and the <code nobreak="false">names</code> attribute is not a wildcard.</p></error>
                  </p><note><p>There is no ambiguity, and no error, if several tokens within the same
                           <elcode>xsl:expose</elcode> element match the same component.</p></note><p>If the visibility of a component as established by the above rules
                  is <code nobreak="false">abstract</code>, then the component must have a declared visibility of <code nobreak="false">abstract</code>.</p><note><p>In other words, the <elcode>xsl:expose</elcode> declaration cannot be used to make a component
                  abstract unless it was declared as abstract to start with.</p></note><p>
                     <error spec="XT" type="static" class="SE" code="3025"><p>It is a <termref def="dt-static-error">static error</termref> if the
                           effect of an <elcode>xsl:expose</elcode> declaration would be to make a component
                           <code nobreak="false">abstract</code>, unless the component is already <code nobreak="false">abstract</code>
                           in the absence of the <elcode>xsl:expose</elcode> declaration.
                        </p></error>
                  </p><p>For a component accepted into a package <var>P</var>
                     from another package <var>Q</var>, the <termref def="dt-visibility">visibility</termref> of the component in <var>P</var> (which primarily
                     affects how it can be used in a package <var>R</var> that uses <var>P</var>)
                     depends on the visibility declared in the relevant <elcode>xsl:accept</elcode>
                     or <elcode>xsl:override</elcode> element in <var>P</var> (see <specref ref="accepting-components"/>); this in turn has a default that depends on
                     the visibility of the corresponding component in <var>Q</var>. In this case the
                     visibility is unaffected by any <elcode>xsl:expose</elcode> declaration in
                        <var>P</var>.</p></div4><div4 id="accepting-components"><head>Accepting Components</head><p>When a package <var>P</var> uses a package <var>Q</var>, by virtue of an
                        <elcode>xsl:use-package</elcode> element in the <termref def="dt-package-manifest">package manifest</termref> of <var>P</var>, then
                        <var>P</var> will contain a <termref def="dt-component">component</termref>
                     corresponding to every component in <var>Q</var>. The <termref def="dt-visibility">visibility</termref> of the component within
                        <var>P</var> depends on the <termref def="dt-visibility">visibility</termref> of the component in <var>Q</var>, optionally modified
                     by two elements that may appear as children of the
                        <elcode>xsl:use-package</elcode> element, namely <elcode>xsl:accept</elcode>
                     and <elcode>xsl:override</elcode>.</p><p>For every component <var>C/Q</var> in package <var>Q</var> that is not matched
                     by any <elcode>xsl:override</elcode> or <elcode>xsl:accept</elcode> element in
                     the package manifest of <var>P</var>, there will be a corresponding component
                        <var>C/P</var> in package <var>P</var> that has the same <termref def="dt-symbolic-identifier">symbolic identifier</termref> and <termref def="dt-declaration">declaration</termref> as <var>C/Q</var>.</p><p>If <var>C/Q</var> is an <elcode>xsl:param</elcode>
                        component, then the <termref def="dt-visibility"/> of <var>C/P</var> is
                        <code nobreak="false">public</code>.</p><p>In other cases, the <termref def="dt-visibility"/> of <var>C/P</var> 
                        depends on the <termref def="dt-visibility"/> of <var>C/Q</var>, as defined by the following table:</p><table class="data" border="1" cellpadding="5" width="100%"><caption>Visibility of Components in Used and Using Packages</caption><thead><tr><th rowspan="1" colspan="1" align="left" valign="top">Visibility in used package <var>C/Q</var></th><th rowspan="1" colspan="1" align="left" valign="top">Visibility in using package <var>C/P</var></th></tr></thead><tbody><tr><td rowspan="1" colspan="1" align="left" valign="top">public</td><td rowspan="1" colspan="1" align="left" valign="top">private</td></tr><tr><td rowspan="1" colspan="1" align="left" valign="top">final</td><td rowspan="1" colspan="1" align="left" valign="top">private</td></tr><tr><td rowspan="1" colspan="1" align="left" valign="top">private</td><td rowspan="1" colspan="1" align="left" valign="top">hidden</td></tr><tr><td rowspan="1" colspan="1" align="left" valign="top">hidden</td><td rowspan="1" colspan="1" align="left" valign="top">hidden</td></tr><tr><td rowspan="1" colspan="1" align="left" valign="top">abstract</td><td rowspan="1" colspan="1" align="left" valign="top">hidden</td></tr></tbody></table><note><p>The effect of these rules is as follows:</p><ulist><item><p>Components that are public or final in the used package <var>Q</var> become
                        private in the using package <var>P</var>. This means that they can be referenced
                        within <var>P</var> but are not (by default) visible within a package <var>R</var>
                        that uses <var>P</var>.</p></item><item><p>Components that are private or hidden in the used package <var>Q</var> become
                           hidden in the using package <var>P</var>. This means that they cannot be referenced
                           within <var>P</var>; but if they contain references to components that are overridden
                           in <var>P</var>, the hidden component’s references are bound to the overriding components
                        in <var>P</var>.</p></item><item><p>Components that are abstract in the used package <var>Q</var> become
                           hidden in the using package <var>P</var>. The hidden component in this case raises a dynamic
                           error if it is invoked. Such an invocation cannot originate within <var>P</var>,
                           because the component is not visible within <var>P</var>; but it can occur
                        if a public component in <var>Q</var> is invoked, which in turn invokes the abstract
                        component.</p></item></ulist></note><e:element-syntax xmlns:e="http://www.w3.org/1999/XSL/Spec/ElementSyntax" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" name="accept">
      <e:attribute name="component" required="yes">
         <e:constant value="template"/>
         <e:constant value="function"/>
         <e:constant value="attribute-set"/>
         <e:constant value="variable"/>
         <e:constant value="mode"/>
         <e:constant value="item-type"/>
         <e:constant value="record-type"/>
         <e:constant value="*"/>
      </e:attribute>
      <e:attribute name="names" required="yes">
         <e:data-type name="tokens"/>
      </e:attribute>
      <e:attribute name="visibility" required="yes">
         <e:constant value="public"/>
         <e:constant value="private"/>
         <e:constant value="final"/>
         <e:constant value="abstract"/>
         <e:constant value="hidden"/>
      </e:attribute>
      <e:empty/>
      <e:allowed-parents>
         <e:parent name="use-package"/>
      </e:allowed-parents>
   </e:element-syntax><p>The <elcode>xsl:accept</elcode> element has very similar syntax and semantics
                     to <elcode>xsl:expose</elcode>. Whereas <elcode>xsl:expose</elcode> allows a
                     package to restrict the visibility of its own components to other (using)
                     packages, <elcode>xsl:accept</elcode> allows a package to restrict the
                     visibility of components exposed by a package that it uses. This may be
                     necessary if, for example, it uses two different packages whose component names
                     conflict. It may also simply be good practice if the package author knows that
                     only a small subset of the functionality of a used package is required.</p><p>The rules for determining whether an <elcode>xsl:accept</elcode> element
                     matches a particular component, and for which element to use if there are
                     several matches, are the same as the rules for the <elcode>xsl:expose</elcode>
                     element.</p><p>No <elcode>xsl:accept</elcode> element
                     ever matches a variable declared using <elcode>xsl:param</elcode>.</p><note><p>Attempting to match an <elcode>xsl:param</elcode> with
                     an explicit <code nobreak="false">EQName</code> will therefore always give an error, while
                     using a wildcard has no effect.</p></note><p>
                     <error spec="XT" type="static" class="SE" code="3030"><p>It is a <termref def="dt-static-error">static error</termref> if a token
                           in the <code nobreak="false">names</code> attribute of <elcode>xsl:accept</elcode>, other
                           than a wildcard, matches no component in the used package.</p></error>
                  </p><p>
                     <error spec="XT" type="static" class="SE" code="3032"><p>It is a <termref def="dt-static-error">static error</termref> if the 
                           <code nobreak="false">component</code> attribute of <elcode>xsl:accept</elcode> specifies <code nobreak="false">*</code>
                           (meaning all component kinds) and the <code nobreak="false">names</code> attribute is not a wildcard.</p></error>
                  </p><p>In the absence of a matching <elcode>xsl:override</elcode> element (see
                        <specref ref="package-overriding-components"/>), the <termref def="dt-visibility"/> of a component that matches an
                        <elcode>xsl:accept</elcode> element depends both on the
                        <code nobreak="false">visibility</code> attribute of the best-matching
                        <elcode>xsl:accept</elcode> element and on the <termref def="dt-visibility">visibility</termref> of the corresponding component in the used package,
                     according to the following table. In this table the entry “N/P” means “not
                     permitted”.</p><table class="data" border="1" cellpadding="5" width="100%"><caption>Relationship of the Visibility given in xsl:accept to Visibility in the Used Package</caption><thead><tr><th rowspan="2" colspan="1" align="left" valign="top">Visibility in <elcode>xsl:accept</elcode> element</th><th colspan="4" rowspan="1" align="left" valign="top">Visibility in used package</th></tr><tr><th rowspan="1" colspan="1" align="left" valign="top">public</th><th rowspan="1" colspan="1" align="left" valign="top">private</th><th rowspan="1" colspan="1" align="left" valign="top">final</th><th rowspan="1" colspan="1" align="left" valign="top">abstract</th></tr></thead><tbody><tr><th rowspan="1" colspan="1" align="left" valign="top">public</th><td rowspan="1" colspan="1" align="left" valign="top">public</td><td rowspan="1" colspan="1" align="left" valign="top">N/P</td><td rowspan="1" colspan="1" align="left" valign="top">N/P</td><td rowspan="1" colspan="1" align="left" valign="top">N/P</td></tr><tr><th rowspan="1" colspan="1" align="left" valign="top">private</th><td rowspan="1" colspan="1" align="left" valign="top">private</td><td rowspan="1" colspan="1" align="left" valign="top">N/P</td><td rowspan="1" colspan="1" align="left" valign="top">private</td><td rowspan="1" colspan="1" align="left" valign="top">N/P</td></tr><tr><th rowspan="1" colspan="1" align="left" valign="top">final</th><td rowspan="1" colspan="1" align="left" valign="top">final</td><td rowspan="1" colspan="1" align="left" valign="top">N/P</td><td rowspan="1" colspan="1" align="left" valign="top">final</td><td rowspan="1" colspan="1" align="left" valign="top">N/P</td></tr><tr><th rowspan="1" colspan="1" align="left" valign="top">abstract</th><td rowspan="1" colspan="1" align="left" valign="top">N/P</td><td rowspan="1" colspan="1" align="left" valign="top">N/P</td><td rowspan="1" colspan="1" align="left" valign="top">N/P</td><td rowspan="1" colspan="1" align="left" valign="top">abstract</td></tr><tr><th rowspan="1" colspan="1" align="left" valign="top">hidden</th><td rowspan="1" colspan="1" align="left" valign="top">hidden</td><td rowspan="1" colspan="1" align="left" valign="top">N/P</td><td rowspan="1" colspan="1" align="left" valign="top">hidden</td><td rowspan="1" colspan="1" align="left" valign="top">hidden</td></tr></tbody></table><p>
                     <error spec="XT" type="static" class="SE" code="3040"><p>It is a <termref def="dt-static-error">static error</termref> if the
                           visibility assigned to a component by an <elcode>xsl:accept</elcode>
                           element is incompatible with the visibility of the corresponding
                           component in the used package, as defined by the above table, unless the
                           token that matches the component name is a wildcard, in which case the
                              <elcode>xsl:accept</elcode> element is treated as not matching that
                           component.</p></error>
                  </p><p>
                     <error spec="XT" type="static" class="SE" code="3050"><p>It is a <termref def="dt-static-error">static error</termref> if the
                              <elcode>xsl:use-package</elcode> elements in a <termref def="dt-package-manifest">package manifest</termref> cause two or more
                              <termref def="dt-homonymous">homonymous</termref> components to be
                           accepted with a visibility other than <code nobreak="false">hidden</code>.</p></error>
                  </p><p>Conflicts between the components accepted from used packages and those declared
                     within the package itself are handled as follows:</p><olist><item><p>If the conflict is between two components both declared within the
                           package itself, then it is resolved by the rules relating to <termref def="dt-import-precedence">import precedence</termref> defined for
                           each kind of component.</p></item><item><p>If the conflict is between two components both accepted from used
                           packages, or between a component declared within the package and an
                           accepted component, then a static error occurs.</p></item><item><p>If a component is explicitly accepted from a used package (by name, rather
                           than by a matching wildcard), and if the same component is the subject
                           of an <elcode>xsl:override</elcode> declaration, then a static error
                        occurs (see below). There is no conflict, however, if a component declared
                        within <elcode>xsl:override</elcode> also matches a wildcard in an <elcode>xsl:accept</elcode>
                        element.</p><p>
                           <error spec="XT" type="static" class="SE" code="3051"><p>It is a <termref def="dt-static-error">static error</termref> if
                                 a token in the <code nobreak="false">names</code> attribute of <elcode>xsl:accept</elcode>,
                                 other than a wildcard, matches the symbolic name of a component declared
                                 within an <elcode>xsl:override</elcode> child of the same
                                 <elcode>xsl:use-package</elcode> element.</p></error>
                        </p></item></olist><p>Where the used package <var>Q</var> contains a component whose
                     visibility is <code nobreak="false">abstract</code>, the using package <var>P</var> has three options:</p><olist><item><p><var>P</var> can accept the component with <code nobreak="false">visibility="abstract"</code>.
                        In this case <var>P</var> can contain references to the component, but invocation via
                     these references will fail unless a non-abstract overriding component has
                     been supplied in some package <var>R</var> that (directly or indirectly) uses <var>P</var>.</p></item><item><p><var>P</var> can accept the component with <code nobreak="false">visibility="hidden"</code>.
                        In this case <var>P</var> cannot contain references to the component, and invocation via
                        references in <var>Q</var> will always fail with a dynamic error. This is the default
                     if <var>P</var> does not explicitly accept or override the component.</p></item><item><p><var>P</var> can provide a concrete implementation of the component
                     within an <elcode>xsl:override</elcode> element.</p></item></olist><p>Any invocation of the absent component (typically from within its
                           declaring package) causes a dynamic error, as if the component were
                           overridden by a component that unconditionally raises a dynamic
                           error.</p><p>
                           <error spec="XT" type="dynamic" class="DE" code="3052"><p>It is a <termref def="dt-dynamic-error">dynamic error</termref> if
                                 an invocation of an abstract component is evaluated.
                              </p></error>                          
                        </p><note><p>This can occur when a public component in the used package invokes
                           an abstract component in the used package, and the using package provides
                           no concrete implementation for the component in an <elcode>xsl:override</elcode>
                           element.</p></note><note><p>To override a component accepted from a used package, the overriding
                        declaration must appear as a child of the <elcode>xsl:override</elcode>
                        element.</p></note><note><p>There is no rule that prevents a function (say) being declared in the using
                        package with the same name as a <code nobreak="false">private</code> function in the used
                        package. This does not create a conflict, since all references in the used
                        package are bound to one function and all those in the using package are
                        bound to another.</p></note></div4><div4 id="package-overriding-components"><head>Overriding Components from a Used Package</head><changes><change issue="272" PR="2474" date="2026-02-18">It is no longer allowed for an <elcode>xsl:param</elcode>
                        or <elcode>xsl:variable</elcode> element to override an <elcode>xsl:param</elcode>
                        in the used package, because stylesheet parameters are now defined to have
                        <code nobreak="false">visibility="private"</code>.</change></changes><p><termdef id="dt-override" term="override">A component in a using package may
                           <term>override</term> a component in a used package, provided that the
                           <termref def="dt-visibility">visibility</termref> of the component in the
                        used package is either <code nobreak="false">abstract</code> or <code nobreak="false">public</code>. The
                        overriding declaration is written as a child of the
                           <elcode>xsl:override</elcode> element, which in turn appears as a child
                        of <elcode>xsl:use-package</elcode>.</termdef></p><e:element-syntax xmlns:e="http://www.w3.org/1999/XSL/Spec/ElementSyntax" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" name="override">
      <e:choice repeat="zero-or-more">
         <e:element name="template"/>
         <e:element name="function"/>
         <e:element name="variable"/>
         <e:element name="param"/>
         <e:element name="attribute-set"/>
         <!--<e:element name="mode"/>-->
      </e:choice>
      <e:allowed-parents>
         <e:parent name="use-package"/>
      </e:allowed-parents>
   </e:element-syntax><note><p>This mechanism is distinct from the mechanism for overriding declarations
                        within the same package by relying on <termref def="dt-import-precedence">import precedence</termref>. It imposes stricter rules: the overriding
                        component is required to be type-compatible with the component that it
                        overrides.</p></note><p>If the used package <var>Q</var> contains a <termref def="dt-component">component</termref>
                     <var>C/Q</var> and the <elcode>xsl:use-package</elcode> element contains an
                        <elcode>xsl:override</elcode> element which contains a declaration
                        <var>D</var> whose <termref def="dt-symbolic-identifier">symbolic
                        identifier</termref> matches the symbolic identifier of <var>C/Q</var>, then
                     the using package <var>P</var> will contain a component <var>C/P</var> whose
                     declaration is D, whose symbolic identifier is that of D, and whose <termref def="dt-visibility"/> is equal to the value of the <code nobreak="false">visibility</code>
                     attribute of <var>D</var>, or <code nobreak="false">private</code> if this is absent, 
                     except in the case
                           of <elcode>xsl:param</elcode>, which is implicitly
                           <code nobreak="false">public</code>.</p><p>The using package <var>P</var> will also contain a component <var>C/PQ</var>
                     whose body is the same as the body of <var>C/Q</var> and whose <termref def="dt-visibility">visibility</termref> is <code nobreak="false">hidden</code>. This
                     component is used as the target of a binding for the symbolic reference
                        <code nobreak="false">xsl:original</code> described below.</p><p>Other than its appearance as a child of <elcode>xsl:override</elcode>, the
                     overriding declaration is a normal <elcode>xsl:function</elcode>,
                        <elcode>xsl:template</elcode>,
                     <elcode>xsl:variable</elcode>, <elcode>xsl:param</elcode>, or
                        <elcode>xsl:attribute-set</elcode> element. In the case of
                        <elcode>xsl:variable</elcode> and <elcode>xsl:param</elcode>, the variable
                     that is declared is a <termref def="dt-global-variable">global
                        variable</termref>.</p><p>The rules in the remainder of this section apply to
                     components having a <code nobreak="false">name</code> attribute (<term>named
                     components</term>). The only element with no <code nobreak="false">name</code> attribute that
                     can appear as a child of <elcode>xsl:override</elcode> is an
                        <elcode>xsl:template</elcode> declaration having a <code nobreak="false">match</code>
                     attribute (that is, a <termref def="dt-template-rule"/>). The rules for
                     overriding of template rules appear in <specref ref="modes-and-packages"/>. If
                     an <elcode>xsl:template</elcode> element has both a <code nobreak="false">name</code> attribute
                     and a <code nobreak="false">match</code> attribute, then it defines both a named component and
                     a template rule, and both sections apply.</p><p>
                     <error spec="XT" type="static" class="SE" code="3055"><p>It is a <termref def="dt-static-error">static error</termref> if a
                           component declaration appearing as a child of
                              <elcode>xsl:override</elcode> is <termref def="dt-homonymous">homonymous</termref> with any other declaration in the using package,
                           regardless of <termref def="dt-import-precedence">import
                              precedence</termref>, including any other overriding declaration in
                           the package manifest of the using package.</p></error></p><note><p>When an attribute set is overridden, the
                        overriding attribute set must be defined using a single
                           <elcode>xsl:attribute-set</elcode> element. Attribute sets defined in
                        different packages are never merged by virtue of having the same name,
                        though they may be merged explicitly by using the
                           <code nobreak="false">use-attribute-sets</code> attribute.</p></note><p>
                     <error spec="XT" type="static" class="SE" code="3058"><p>It is a <termref def="dt-static-error">static error</termref> if a
                           component declaration appearing as a child of
                              <elcode>xsl:override</elcode> does not match (is not <termref def="dt-homonymous">homonymous</termref> with) some component in the
                           used package.</p></error></p><p>
                     <error spec="XT" type="static" class="SE" code="3060"><p>It is a <termref def="dt-static-error">static error</termref> if the
                           component referenced by an <elcode>xsl:override</elcode> declaration has
                              <termref def="dt-visibility">visibility</termref> other than
                              <code nobreak="false">public</code> or <code nobreak="false">abstract</code></p></error>
                  </p><p>A package is executable if and only if it contains no <termref def="dt-component">component</termref> whose <termref def="dt-visibility">visibility</termref> is <code nobreak="false">abstract</code>. A package that is not
                     executable is not a <termref def="dt-stylesheet">stylesheet</termref>, and
                     therefore cannot be nominated as the stylesheet to be used when initiating a
                     transformation.</p><note><p>In other words, if a component is declared as abstract, then some package
                        that uses the declaring package of that component directly or indirectly
                        must override that component with one that is not abstract. It is not
                        necessary for the override to happen in the immediately using package.</p></note><p>
                     <error spec="XT" type="static" class="SE" code="3070"><p>It is a <termref def="dt-static-error">static error</termref> if the
                           signature of an overriding component is not <termref def="dt-compatible">compatible</termref> with the signature of the component that it is
                           overriding.</p></error>
                  </p><p><termdef id="dt-compatible" term="compatible">The signatures of two <termref def="dt-component">components</termref> are <term>compatible</term> if
                        they present the same interface to the user of the component. The additional
                        rules depend on the kind of component.</termdef></p><p>Compatibility is only relevant when comparing two components that have the same
                        <termref def="dt-symbolic-identifier"/>. The compatibility rules for each
                     kind of component are as follows:</p><ulist><item><p>Two attribute sets with the same name are compatible if
                           and only if they satisfy the following rule:</p><olist><item><p>If the overridden attribute set specifies
                                    <code nobreak="false">streamable="yes"</code> then the overriding attribute set
                                 also specifies <code nobreak="false">streamable="yes"</code>.</p></item></olist></item><item diff="chg" at="variadicity"><p>Two functions with the same symbolic identifier are compatible if and only if
                           they satisfy all the following rules:</p><olist><item><p>They have the same <termref def="dt-arity-range"/>
                              (which implies they have the same number of required and optional parameters)</p></item><item><p>The declared types of the parameters 
                                 (defaulting to <code nobreak="false">item()*</code>) are pairwise <termref def="dt-identical-types">identical</termref>.</p></item><item><p>The declared return types 
                                 (defaulting to <code nobreak="false">item()*</code>) are <termref def="dt-identical-types">identical</termref>.</p></item><item><p>The <termref def="dt-effective-value"/> of the 
                                 <code nobreak="false">new-each-time</code> 
                                 attribute on the overriding function is the same as its value on the overridden function.</p></item><item><p diff="chg" at="2022-01-01">If the overridden function has a <code nobreak="false">streamability</code> attribute with a value
                              other than <code nobreak="false">unspecified</code>, then the overriding function has a
                                 <code nobreak="false">streamability</code> attribute with the same value. </p></item></olist><p>It is <rfc2119>recommended</rfc2119>
                        that the parameter names on the overriding function should be the same as on the overridden function.
                        (However, in order to maintain backwards compatibility with XSLT 3.0, 
                        this is not <rfc2119>required</rfc2119>.) If the parameter names are not the same,
                        then the parameter names on the overriding function are effectively replaced with the names declared
                        on the overridden function, so that any static function calls using keyword arguments to set the values
                        of arguments must use the names defined on the overridden function.</p></item><item><p>Two named templates with the same name are compatible if and only if they
                           satisfy all the following rules:</p><olist><item><p>Their return types are <termref def="dt-identical-types">identical</termref>.</p></item><item><p>For every non-tunnel parameter on the overridden template, there is a
                                 non-tunnel parameter on the overriding template that has the same name, an
                                    <termref def="dt-identical-types">identical</termref> required
                                 type, and the same <termref def="dt-effective-value"/> for the <code nobreak="false">required</code> attributes.</p></item><item><p>For every tunnel parameter <var>P</var> on the overridden template, if there is a
                                 parameter <var>Q</var> on the overriding template that has the same name 
                                 as <var>P</var> then <var>Q</var> is also a tunnel parameter, and <var>P</var> and <var>Q</var> have
                                 <termref def="dt-identical-types">identical</termref> required
                                 types.</p></item><item><p>Any parameter on the overriding template for which there is no
                                 corresponding parameter on the overridden template specifies
                                    <code nobreak="false">required="no"</code>.</p></item><item><p>The two templates have equivalent
                                    <elcode>xsl:context-item</elcode> children, where equivalence
                                 means that the <code nobreak="false">use</code> attributes are the same and the
                                 required types are <termref def="dt-identical-types">identical</termref>; an absent
                                    <elcode>xsl:context-item</elcode> is equivalent to one that
                                 specifies <code nobreak="false">use="optional"</code> and
                                 <code nobreak="false">as="item()"</code>.</p></item></olist></item><item><p>Two variables (including parameters) with the same name are compatible if
                           and only if they satisfy all the following rules:</p><olist><item><p>Their declared types are <termref def="dt-identical-types">identical</termref>.
                              <phrase diff="add" at="2022-01-01">For this purpose, the declared type is the first
                              of the following that applies:</phrase></p><ulist diff="add" at="2022-01-01"><item><p>If there is an <code nobreak="false">as</code> attribute, then the type defined by that attribute.</p></item><item><p>If there is a <code nobreak="false">select</code> attribute, then <code nobreak="false">item()*</code>.</p></item><item><p>If there is a non-empty sequence constructor, then <code nobreak="false">document-node()</code>.</p></item><item><p>Otherwise, <code nobreak="false">xs:string</code>. </p></item></ulist></item></olist><note><p>Stylesheet parameters are always private, and therefore cannot be overridden.
                           However, an <elcode>xsl:param</elcode> declaration within <elcode>xsl:override</elcode>
                           may override a public global variable in the <termref def="dt-library-package"/>.</p><p>When overriding a global variable, the initial
                              value may differ.</p><p>Stylesheet parameters in a <termref def="dt-library-package"/> can (under some
                           circumstances) be given a value by the using package, using an <elcode>xsl:with-param</elcode>
                           child of the <elcode>xsl:use-package</elcode> declaration. 
                              See <specref ref="supplying-package-parameters"/>.</p></note></item></ulist><p><termdef id="dt-identical-types" term="identical (types)">Types <var>S</var> 
                     and <var>T</var> are considered <term>identical</term> for the purpose of
                        these rules if and only if <code nobreak="false">subtype(S, T)</code> and <code nobreak="false">subtype(T,
                           S)</code> both hold, where the subtype relation is defined in <xspecref spec="XP40" ref="id-seqtype-subtype"/>.</termdef></p><note><olist><item><p>One consequence of this rule is that two plain union types are
                              considered identical if they have the same set of member types, even
                              if the union types have different names or the ordering of the member
                              types is different.</p><p>Consider a function that accepts an argument
                           whose declared type is a union type with member types <code nobreak="false">xs:double</code>
                           and <code nobreak="false">xs:decimal</code>, in that order (we might write this as <code nobreak="false">(xs:double | xs:decimal)</code>).
                           Using the same notation, this can be overridden by a function that declares the argument
                           type as <code nobreak="false">(xs:decimal | xs:double)</code>. This does not affect type checking:
                              a function call that passes the type checking rules with one signature will also pass the
                              type checking rules with the other. It does however affect the way that the coercion
                              rules work: a call that passes the <code nobreak="false">xs:untypedAtomic</code> item
                           <code nobreak="false">"93.7"</code> (or an untyped node with this as its string value) will be converted to 
                              an <code nobreak="false">xs:decimal</code> in one case and an <code nobreak="false">xs:double</code> in the other.</p></item><item><p>While this rule may appear formal, it is not as straightforward as
                              might be supposed, because the subtype relation in XPath has a
                              dependency on the “Type derivation OK (Simple)” relation in XML
                              Schema, which itself appeals to a judgement as to whether the two type
                              definitions being compared “are the same type definition”. Both XSD
                              1.0 and XSD 1.1 add the note “The wording of [this rule] appeals to a
                              notion of component identity which is only incompletely defined by
                              this version of this specification.” However, they go on to say that
                              component identity is well defined if the components are named simple
                              type definitions, which will always apply in this case. For named
                              atomic types, the final result of these rules is that two atomic types
                              are identical if and only if they have the same name.</p></item><item><p>A named item type
                           (declared in an <elcode>xsl:item-type</elcode> declaration) is considered
                           identical to its expansion.</p></item><item><p>Two named record types are compared by name, not by content. This is
                              because named record types may potentially be recursive, so the name
                              cannot always be expanded to an expressible record type designator.
                              By implication, the named record type must itself be declared or exposed
                              with <code nobreak="false">visibility="public"</code>.</p></item></olist></note><p>Modes, named item types, and named record type are not overridable, 
                     so <elcode>xsl:mode</elcode>, <elcode>xsl:item-type</elcode>, and
                     <elcode>xsl:record-type</elcode> declarations cannot
                     appear as children of <elcode>xsl:override</elcode>. However,
                     the constructor function implicitly created from an 
                     <elcode>xsl:record-type</elcode> declaration may be overridden
                     in an <elcode>xsl:function</elcode> declaration.</p></div4><div4 id="refer-to-overridden"><head>Referring to Overridden Components</head><p>Within the declaration of an overriding named <termref def="dt-component"/>
                     (that is, a component whose declaration is a child of
                        <elcode>xsl:override</elcode>, and has a <code nobreak="false">name</code> attribute), where
                     the overridden component has public <termref def="dt-visibility"/>, it is
                     possible to use the name <code nobreak="false">xsl:original</code> as a symbolic reference to
                     the overridden component. More specifically: </p><ulist><item><p>Within a <termref def="dt-named-template"/> appearing as a child of
                              <elcode>xsl:override</elcode>, the name <code nobreak="false">xsl:original</code>
                           may appear as the value of the <code nobreak="false">name</code> attribute of
                              <elcode>xsl:call-template</elcode>: for example,
                              <code nobreak="false">&lt;xsl:call-template name="xsl:original"/&gt;</code>. </p></item><item><p>Within a <termref def="dt-stylesheet-function"/> appearing as a child of
                              <elcode>xsl:override</elcode>, the static context for contained XPath
                           expressions (other than <termref def="dt-static-expression">static
                              expressions</termref>) is augmented as follows: the <term>statically
                              known function signatures</term> includes a mapping from the name
                              <code nobreak="false">xsl:original</code> to the signature of the overridden
                           function (which is the same as the signature of the overriding function).
                           This means that the name <code nobreak="false">xsl:original</code> can be used in static
                           function calls, including calls that use partial function application
                           (where one of the arguments is given as <code nobreak="false">"?"</code>), and also in named function
                           references. For example: <code nobreak="false">xsl:original($x)</code>,
                              <code nobreak="false">xsl:original($x, ?)</code>, <code nobreak="false">xsl:original#2</code>.</p><note><p>The result of calling <code nobreak="false">function-name(xsl:original#2)</code> is
                              the name of the overridden function, not
                              <code nobreak="false">xsl:original</code>.</p></note><p diff="add" at="issue663">If the function <code nobreak="false">xsl:original</code> is
                        called with keyword arguments, the keywords used are those of the overridden
                        function.</p><p>Neither <code nobreak="false">xsl:original</code>, nor the overridden function, is added
                           to the <xtermref diff="add" at="issue663" spec="XP40" ref="dt-dynamically-known-function-definitions">dynamically known function definitions</xtermref> component of the dynamic context for
                           XPath expressions within the overriding function. This means that any
                           attempt to bind the function name <code nobreak="false">xsl:original</code> dynamically
                           (for example using <xfunction>function-lookup</xfunction>, or
                              <function>function-available</function>, or
                              <elcode>xsl:evaluate</elcode>) will fail, and any attempt to bind
                           the name of the overriding/overridden function dynamically will return
                           the overriding function. </p></item><item><p>Within a <termref def="dt-global-variable"/> or parameter appearing as a
                           child of <elcode>xsl:override</elcode>, the static context for contained
                           XPath expressions (other than <termref def="dt-static-expression">static
                              expressions</termref>) is augmented as follows: the <term>in-scope
                              variables</term> includes a mapping from the name
                              <code nobreak="false">xsl:original</code> to the declared type of the overridden
                           variable or parameter (which is the same as the type of the overriding
                           global variable or parameter). </p></item><item><p>Within an <termref def="dt-attribute-set"/> appearing as a child of
                              <elcode>xsl:override</elcode>, any
                              <code nobreak="false">[xsl:]use-attribute-sets</code> attribute (whether on the
                              <elcode>xsl:attribute-set</elcode> element itself, or on any
                           descendant element) may include the name <code nobreak="false">xsl:original</code> as a
                           reference to the overridden attribute set. </p></item></ulist><p>Within the overriding component <var>C/P</var>, the <termref def="dt-symbolic-reference"/>
                     <code nobreak="false">xsl:original</code> is bound to the hidden component <var>C/PQ</var>
                     described earlier, whose body is that of the component <var>C/Q</var> in the
                     used package. </p><p>
                     <error spec="XT" type="static" class="SE" code="3075"><p>It is a <termref def="dt-static-error">static error</termref> to use the
                           component reference <code nobreak="false">xsl:original</code> when the overridden
                           component has <code nobreak="false">visibility="abstract"</code>.</p></error>
                  </p><p>Modes are not overridable, so the name
                        <code nobreak="false">xsl:original</code> cannot be used to refer to a <termref def="dt-mode"/> (for example in the <code nobreak="false">mode</code> attribute of
                        <elcode>xsl:apply-templates</elcode>). </p><note><p>In the case of variables, templates, and attribute sets, the invocation of
                        the overridden component can occur only within the lexical scope of the
                        overriding component. With functions, however, there is greater flexibility.
                        The overriding component can obtain a reference to the overridden component
                        in the form of a function item, and can export this value by passing it to
                        other functions or returning it in its result. A dynamic invocation of this
                        function item (and hence, of the overridden function) can thus occur
                        anywhere. </p></note></div4><div4 id="component-references"><head>Binding References to Components</head><p><termdef id="dt-reference-binding" term="reference binding">The process of
                        identifying the <termref def="dt-component">component</termref> to which a
                           <termref def="dt-symbolic-reference">symbolic reference</termref> applies
                        (possibly chosen from several <termref def="dt-homonymous">homonymous</termref> alternatives) is called <term>reference
                           binding</term>.</termdef>
                  </p><p>The process of <termref def="dt-reference-binding"/> in the presence of
                     overriding declarations is best illustrated by an example. The formal rules
                     follow later in the section.</p><example id="example-of-component-binding"><head>Binding References to Named Components</head><p>Consider a package <var>Q</var> defined as follows:</p><eg role="xslt-document" xml:space="preserve">&lt;xsl:package name="Q"
        version="3.0"                
        xmlns:xsl="http://www.w3.org/1999/XSL/Transform"&gt;
  &lt;xsl:variable name="A" visibility="final" select="$B + 1"/&gt;
  &lt;xsl:variable name="B" visibility="private" select="$C * 2"/&gt;
  &lt;xsl:variable name="C" visibility="public" select="22"/&gt;
&lt;/xsl:package&gt;</eg><p>(The process is illustrated here using variables as the components, but the
                        logic would be the same if the example used functions, named templates, or
                        attribute sets.)</p><p>There are three components in this package, and their properties are
                        illustrated in the following table. (The ID column is an arbitrary component
                        identifier used only for the purposes of this exposition.)</p><table class="data" border="1" cellpadding="5" width="100%"><caption>Components in the above Package and their Properties</caption><thead><tr><th rowspan="1" colspan="1" align="left" valign="top">ID</th><th rowspan="1" colspan="1" align="left" valign="top">Symbolic Name</th><th rowspan="1" colspan="1" align="left" valign="top">Declaring Package</th><th rowspan="1" colspan="1" align="left" valign="top">Containing Package</th><th rowspan="1" colspan="1" align="left" valign="top">Visibility</th><th rowspan="1" colspan="1" align="left" valign="top">Body</th><th rowspan="1" colspan="1" align="left" valign="top">Bindings</th></tr></thead><tbody><tr><td rowspan="1" colspan="1" align="left" valign="top"><var>A/Q</var></td><td rowspan="1" colspan="1" align="left" valign="top">variable <var>A</var></td><td rowspan="1" colspan="1" align="left" valign="top">Q</td><td rowspan="1" colspan="1" align="left" valign="top">Q</td><td rowspan="1" colspan="1" align="left" valign="top">final</td><td rowspan="1" colspan="1" align="left" valign="top"><code nobreak="false">$B + 1</code></td><td rowspan="1" colspan="1" align="left" valign="top">$B → <var>B/Q</var></td></tr><tr><td rowspan="1" colspan="1" align="left" valign="top"><var>B/Q</var></td><td rowspan="1" colspan="1" align="left" valign="top">variable <var>B</var></td><td rowspan="1" colspan="1" align="left" valign="top">Q</td><td rowspan="1" colspan="1" align="left" valign="top">Q</td><td rowspan="1" colspan="1" align="left" valign="top">private</td><td rowspan="1" colspan="1" align="left" valign="top"><code nobreak="false">$C * 2</code></td><td rowspan="1" colspan="1" align="left" valign="top">$C → <var>C/Q</var></td></tr><tr><td rowspan="1" colspan="1" align="left" valign="top"><var>C/Q</var></td><td rowspan="1" colspan="1" align="left" valign="top">variable <var>C</var></td><td rowspan="1" colspan="1" align="left" valign="top">Q</td><td rowspan="1" colspan="1" align="left" valign="top">Q</td><td rowspan="1" colspan="1" align="left" valign="top">public</td><td rowspan="1" colspan="1" align="left" valign="top"><code nobreak="false">22</code></td><td rowspan="1" colspan="1" align="left" valign="top">none</td></tr></tbody></table><p>Now consider a package <var>P</var> that uses <var>Q</var>, and that
                        overrides one of the variables declared in <var>Q</var>:</p><eg role="xslt-document" xml:space="preserve">&lt;xsl:package name="P"
        version="3.0"                
        xmlns:xsl="http://www.w3.org/1999/XSL/Transform"&gt;
  &lt;xsl:use-package name="Q"&gt;
    &lt;xsl:override&gt;
      &lt;xsl:variable name="C" visibility="private" select="$xsl:original + 3"/&gt;
    &lt;/xsl:override&gt;
  &lt;/xsl:use-package&gt;
  
  &lt;xsl:template name="T" visibility="public"&gt;
    &lt;xsl:value-of select="$A"/&gt;
  &lt;/xsl:template&gt;
&lt;/xsl:package&gt;</eg><p>Package <var>P</var> has five components, whose properties are shown in the
                        following table:</p><table class="data" border="1" cellpadding="5" width="100%"><caption>Components in the above Package and their Properties</caption><thead><tr><th rowspan="1" colspan="1" align="left" valign="top">ID</th><th rowspan="1" colspan="1" align="left" valign="top">Symbolic Name</th><th rowspan="1" colspan="1" align="left" valign="top">Declaring Package</th><th rowspan="1" colspan="1" align="left" valign="top">Containing Package</th><th rowspan="1" colspan="1" align="left" valign="top">Visibility</th><th rowspan="1" colspan="1" align="left" valign="top">Body</th><th rowspan="1" colspan="1" align="left" valign="top">Bindings</th></tr></thead><tbody><tr><td rowspan="1" colspan="1" align="left" valign="top"><var>A/PQ</var></td><td rowspan="1" colspan="1" align="left" valign="top">variable <var>A</var></td><td rowspan="1" colspan="1" align="left" valign="top">Q</td><td rowspan="1" colspan="1" align="left" valign="top">P</td><td rowspan="1" colspan="1" align="left" valign="top">final</td><td rowspan="1" colspan="1" align="left" valign="top"><code nobreak="false">$B + 1</code></td><td rowspan="1" colspan="1" align="left" valign="top">$B → <var>B/PQ</var></td></tr><tr><td rowspan="1" colspan="1" align="left" valign="top"><var>B/PQ</var></td><td rowspan="1" colspan="1" align="left" valign="top">variable <var>B</var></td><td rowspan="1" colspan="1" align="left" valign="top">Q</td><td rowspan="1" colspan="1" align="left" valign="top">P</td><td rowspan="1" colspan="1" align="left" valign="top">hidden</td><td rowspan="1" colspan="1" align="left" valign="top"><code nobreak="false">$C * 2</code></td><td rowspan="1" colspan="1" align="left" valign="top">$C → <var>C/P</var></td></tr><tr><td rowspan="1" colspan="1" align="left" valign="top"><var>C/PQ</var></td><td rowspan="1" colspan="1" align="left" valign="top">variable <var>C</var></td><td rowspan="1" colspan="1" align="left" valign="top">Q</td><td rowspan="1" colspan="1" align="left" valign="top">P</td><td rowspan="1" colspan="1" align="left" valign="top">hidden</td><td rowspan="1" colspan="1" align="left" valign="top"><code nobreak="false">22</code></td><td rowspan="1" colspan="1" align="left" valign="top">none</td></tr><tr><td rowspan="1" colspan="1" align="left" valign="top"><var>C/P</var></td><td rowspan="1" colspan="1" align="left" valign="top">variable <var>C</var></td><td rowspan="1" colspan="1" align="left" valign="top">P</td><td rowspan="1" colspan="1" align="left" valign="top">P</td><td rowspan="1" colspan="1" align="left" valign="top">private</td><td rowspan="1" colspan="1" align="left" valign="top"><code nobreak="false">$xsl:original + 3</code></td><td rowspan="1" colspan="1" align="left" valign="top">$xsl:original → <var>C/PQ</var></td></tr><tr><td rowspan="1" colspan="1" align="left" valign="top"><var>T/P</var></td><td rowspan="1" colspan="1" align="left" valign="top">template <var>T</var></td><td rowspan="1" colspan="1" align="left" valign="top">P</td><td rowspan="1" colspan="1" align="left" valign="top">P</td><td rowspan="1" colspan="1" align="left" valign="top">public</td><td rowspan="1" colspan="1" align="left" valign="top"><code nobreak="false">value-of select="$A</code></td><td rowspan="1" colspan="1" align="left" valign="top">$A → <var>A/PQ</var></td></tr></tbody></table><p>The effect of these bindings is that when template <var>T</var> is called,
                        the result is <code nobreak="false">51</code>. This is why:</p><olist><item><p>The result of <var>T</var> is the value of <var>A/PQ</var>.</p></item><item><p>The value of <var>A/PQ</var> is the value of <var>B/PQ</var> plus
                              1.</p></item><item><p>The value of <var>B/PQ</var> is the value of <var>C/P</var> times
                              2.</p></item><item><p>The value of <var>C/P</var> is the value of <var>C/PQ</var> plus
                              3.</p></item><item><p>The value of <var>C/PQ</var> is 22.</p></item><item><p>So the final result is ((22 + 3) * 2) + 1</p></item></olist><p>In this example, the components of <var>P</var> are established in three
                        different ways:</p><olist><item><p>Components <var>A/PQ</var>, <var>B/PQ</var>, and <var>C/PQ</var> are
                              modified copies of the corresponding component <var>A/Q</var>,
                                 <var>B/Q</var>, and <var>C/Q</var> in the used package
                              <var>Q</var>. The properties of these components are modified as
                              follows:</p><olist><item><p>The <termref def="dt-symbolic-identifier"/>, <termref def="dt-declaring-package"/>, and body are unchanged.</p></item><item><p>The <termref def="dt-containing-package"/> is changed to
                                       <var>P</var>.</p></item><item><p>The <termref def="dt-visibility"/> is changed according to the
                                    rules in <specref ref="accepting-components"/>: in particular,
                                       <code nobreak="false">visibility="private"</code> changes to
                                       <code nobreak="false">visibility="hidden"</code>.</p></item><item><p>The references to other components are rebound as described in
                                    this section.</p></item></olist></item><item><p>Component <var>C/P</var> is the overriding component. Its properties
                              are exactly as if it were declared as a top-level component in
                                 <var>P</var> (outside the <elcode>xsl:use-package</elcode>
                              element), except that (a) it must adhere to the constraints on
                              overriding components (see <specref ref="package-overriding-components"/>), (b) it is allowed to use
                              the variable reference <code nobreak="false">$xsl:original</code>, and (c) the fact
                              that it overrides <var>C/Q</var> affects the way that references from
                              other components are rebound.</p></item><item><p>Component <var>T/P</var> is a new component declared locally in
                                 <var>P</var>.</p></item></olist></example><p>The general rules for <termref def="dt-reference-binding"/> can now be
                     stated:</p><olist><item><p>If the <termref def="dt-containing-package"/> of a component
                              <var>C/P</var> is <var>P</var>, then all <termref def="dt-symbolic-reference">symbolic references</termref> in
                              <var>C/P</var> are bound to components whose <termref def="dt-containing-package"/> is <var>P</var>.</p></item><item><p>When a package <var>P</var> uses a package <var>Q</var>, then for every
                           component <var>C/Q</var> in <var>Q</var>, there is a <term>corresponding
                              component</term>
                           <var>C/P</var> in <var>P</var>, as described in <specref ref="accepting-components"/>.</p></item><item><p>Given a component <var>C/P</var> whose <termref def="dt-containing-package"/> and <termref def="dt-declaring-package"/> are the same package <var>P</var>, then (as a consequence of rules
                           elsewhere in this specification) for every <termref def="dt-symbolic-reference"/>
                           <var>D</var> within <var>C/P</var>, other than a reference using the name
                              <code nobreak="false">xsl:original</code>, there will always be exactly one non-hidden
                           component <var>D/P</var> whose containing package is <var>P</var> and
                           whose <termref def="dt-symbolic-identifier"/> matches <var>D</var>
                           (otherwise a static error will have been raised). The reference is then
                           bound to <var>D/P</var>.</p></item><item><p>In the case of a component reference using the name
                              <code nobreak="false">xsl:original</code>, this will in general appear within a
                           component <var>C/P</var> that overrides a component <var>C/Q</var> whose
                           corresponding component in <var>P</var> is <var>C/PQ</var>, and the
                              <code nobreak="false">xsl:original</code> reference is bound to <var>C/PQ</var>.</p></item><item><p>Given a component <var>C/P</var> whose <termref def="dt-containing-package"/>
                           <var>P</var> is a different package from its <termref def="dt-declaring-package"/>
                           <var>R</var> (that is, <var>C/P</var> is present in <var>P</var> by
                           virtue of an <elcode>xsl:use-package</elcode> declaration referencing
                           package <var>Q</var>, which may or may not be the same as <var>R</var>),
                           then the component bindings in <var>C/P</var> are derived from the
                           component bindings in the corresponding component <var>C/Q</var> as
                           follows: if the component binding within <var>C/Q</var> is to a component
                              <var>D/Q</var>, then:</p><olist><item><p>If <var>D/Q</var> is overridden within <var>P</var> by a component
                                    <var>D/P</var>, then the reference is bound to
                                 <var>D/P</var>;</p></item><item><p>Otherwise, the reference is bound to the component <var>D/PQ</var>
                                 in <var>P</var> whose corresponding component in <var>Q</var> is
                                    <var>D/Q</var>.</p></item></olist></item></olist><p>When reference resolution is performed on a package that is intended to be used
                     as a <termref def="dt-stylesheet">stylesheet</termref> (that is, for the
                        <termref def="dt-top-level-package">top-level package</termref>), there must
                     be no symbolic references referring to components whose visibility is
                        <code nobreak="false">abstract</code> (that is, an implementation must be provided for every
                     abstract component). </p><p>
                     <error spec="XT" type="static" class="SE" code="3080"><p>It is a <termref def="dt-static-error">static error</termref> if a
                              <termref def="dt-top-level-package">top-level package</termref> (as
                           distinct from a <termref def="dt-library-package">library
                              package</termref>) contains 
                           components whose visibility is <code nobreak="false">abstract</code>.</p></error>
                  </p><note diff="chg" at="2022-01-01"><p>Abstract components in a used package by default become hidden in the using package, 
                        which means that a reference to the component in the top-level package will fail 
                        to resolve (resulting in a different static error). This particular error occurs 
                        only if the abstract component is declared within the top-level package.
                     </p></note><note><p>Unresolved references are allowed at the module level but not at the package
                        level. A stylesheet module can contain references to components that are
                        satisfied only when the module is imported into another module that declares
                        the missing component.</p></note><note><p>The process of resolving references (or linking) is critical to an
                        implementation that uses separate compilation. One of the aims of these
                        rules is to ensure that when compiling a package, it is always possible to
                        determine the signature of called functions, templates, and other
                        components. A further aim is to establish unambiguously in what
                        circumstances components can be overridden, so that compilers know when it
                        is possible to perform optimizations such as inlining of function and
                        variable references.</p><p>Suppose a public template <var>T</var> calls a private function
                        <var>F</var>. When the package containing these two components is referenced
                        by a using package, the template remains public, while the function becomes
                        hidden. Because the function becomes hidden, it can no longer conflict with
                        any other function of the same name, or be overridden by any other function;
                        at this stage the compiler knows exactly which function <var>T</var> will be
                        calling, and can perform optimizations based on this knowledge.</p></note><p>The mechanism for resolving component references described in
                     this section is consistent with the mechanism used for binding function and
                     variable references described in the XPath specification. XPath requires these
                     variable and function names to be present in the static context for an XPath
                     expression. XSLT ensures that all the non-hidden functions, global variables,
                     and global parameters in a package are present in the static context for every
                     XPath expression that appears in that package, along with required information
                     such as the type of a variable and the signature of a function.</p><example><head>Named Component References in Inline Functions</head><p>Named component references within inline functions follow the standard rules, but the rules need
                        to be interpreted with care. Suppose that in package <var>P</var> we find the declarations:</p><eg role="xslt-declarations" xml:space="preserve">
&lt;xsl:variable name="v" as="xs:integer" visibility="public" select="3"/&gt;

&lt;xsl:function name="f:factory" as="fn(*)" visibility="final"&gt;
  &lt;xsl:sequence select="fn() { $v }"/&gt;
&lt;/xsl:function&gt;  
                  </eg><p>and that in a using package Q we find:</p><eg role="xslt-declarations" xml:space="preserve">
      
&lt;xsl:use-package name="P"&gt;
  &lt;xsl:override&gt;
    &lt;xsl:variable name="v" as="xs:integer" select="4"/&gt;
  &lt;/xsl:override&gt;
&lt;/xsl:use-package&gt;

&lt;xsl:template name="xsl:initial-template"&gt;
  &lt;v value="{f:factory()()}"/&gt;
&lt;/xsl:template&gt;  
      </eg><p>The correct output here is <code nobreak="false">&lt;v value="4"/&gt;</code>.</p><p>The explanation for this is as follows. Package <var>Q</var> contains a function <var>f:factory/QP</var>
                        whose declaring package is <var>P</var> and whose containing package is <var>Q</var>. The symbolic reference
                        <code nobreak="false">$v</code> within the body of this function is resolved in the normal way; since the containing package
                        is <var>Q</var>, it is resolved to the global variable <var>v/Q</var>: that is, the overriding declaration
                        of <code nobreak="false">$v</code> that appears within the <elcode>xsl:override</elcode> element within package <var>Q</var>,
                        whose value is 4.</p><p>In terms of internal implementation, one way of looking at this is that the anonymous function returned
                        by <code nobreak="false">f:factory</code> contains within its closure bindings for the global variables and functions that
                        the anonymous function references; these bindings are inherited from the component bindings of the
                        component that lexically contains these symbolic references, which in this case is <code nobreak="false">f:factory</code>,
                        and more specifically the version of the <code nobreak="false">f:factory</code> component in package <var>Q</var>.</p></example></div4><div4 id="dynamic-component-references"><head>Dynamic References to Components</head><p>There are several functions in which a dynamically evaluated QName is used to
                     identify a component: these include <function>key</function>,
                        <function>accumulator-before</function>,
                        <function>accumulator-after</function>,
                     <function>apply-templates</function>,
                     <xfunction>function-lookup</xfunction>, and
                        <function>function-available</function>. Dynamic references can also occur
                     in the XPath expression supplied to the <elcode>xsl:evaluate</elcode>
                     instruction. </p><p>In all these cases, the set of components that are available to be referenced
                     are those that are declared in the package where this function call appears,
                     including components declared within an <elcode>xsl:override</elcode>
                     declaration in that package, but excluding components declared with
                        <code nobreak="false">visibility="abstract"</code>. If the relevant component has been
                     overridden in a different package, the overriding declarations are not
                     considered. </p><p>If one of these functions (for example <function>key</function> or
                        <function>accumulator-before</function>) is invoked via a dynamic function
                     invocation, then the relevant package is the one in which the function item is
                     created (using a construct such as <code nobreak="false">key#2</code>, <code nobreak="false">key('my-key',
                        ?)</code>, or <code nobreak="false">function-lookup($KEYFN, 2)</code>). Function items
                     referring to context-dependent functions bind the context at the point where
                     the function item is created, not the context at the point where the function
                     item is invoked.</p><note><p>This means that if a package wishes to make a key available for use by a
                        calling package, it can do so by creating a public global variable whose
                        value is a partial application of the <function>key</function> function:</p><eg role="xslt-declaration" xml:space="preserve">&lt;xsl:variable name="get-order" select="key('orders-key', ?, ?)"/&gt;</eg><p>which the calling code can invoke as <code nobreak="false">$get-order('123-456', /)</code>.</p></note></div4></div3><div3 id="modes-and-packages"><head>Overriding Template Rules from a Used Package</head><p>The rules in the previous section apply to named components including functions,
                  named templates, global variables, and named attribute sets. The rules for
                     <termref def="dt-mode">modes</termref>, and the <termref def="dt-template-rule">template rules</termref> appearing within a mode, are slightly different.</p><p>The unnamed mode is local to a package: in effect, each package has its own
                  private unnamed mode, and the unnamed mode of one package does not interact with
                  the unnamed mode of any other package. An
                        <elcode>xsl:apply-templates</elcode> instruction with no <code nobreak="false">mode</code>
                     attribute is treated as a <termref def="dt-symbolic-reference"/> to the default
                     mode defined for that instruction (see <specref ref="default-mode"/>), which in
                     turn defaults to the <termref def="dt-unnamed-mode"/>. Because the unnamed mode
                     always has private visibility, it cannot be overridden in another 
                     package.</p><p>A named mode may be declared in an <elcode>xsl:mode</elcode> declaration as being
                  either <code nobreak="false">public</code>, <code nobreak="false">private</code>, or <code nobreak="false">final</code>. The
                  values of the <code nobreak="false">visibility</code> attribute are interpreted as follows:</p><table class="def" border="1" cellpadding="5" width="100%"><caption>Visibility Values for Named Modes, and their Meaning</caption><thead><tr><th rowspan="1" colspan="1" align="left" valign="top">Value</th><th rowspan="1" colspan="1" align="left" valign="top">Meaning</th></tr></thead><tbody><tr><td rowspan="1" colspan="1" align="left" valign="top">public</td><td rowspan="1" colspan="1" align="left" valign="top">A <term>using</term> package may use
                              <elcode>xsl:apply-templates</elcode> to invoke templates in this mode;
                           it may also declare additional template rules in this mode, which are
                           selected in preference to template rules in the used package. These may
                           appear only as children of the <elcode>xsl:override</elcode> element
                           within the <elcode>xsl:use-package</elcode> element.</td></tr><tr><td rowspan="1" colspan="1" align="left" valign="top">private</td><td rowspan="1" colspan="1" align="left" valign="top">A <term>using</term> package may neither reference the mode nor provide
                           additional templates in this mode; the name of the mode is not even
                           visible in the using package, so no such attempt is possible. The using
                           package can use the same name for its own modes without risk of conflict.
                        </td></tr><tr><td rowspan="1" colspan="1" align="left" valign="top">final</td><td rowspan="1" colspan="1" align="left" valign="top">A <term>using</term> package may use
                              <elcode>xsl:apply-templates</elcode> to invoke templates in this mode,
                           but it must not provide additional template rules in this mode. </td></tr></tbody></table><p>As with other named components, an <elcode>xsl:use-package</elcode> declaration
                  may contain an <elcode>xsl:accept</elcode> element to control the visibility of a
                  mode acquired from the <term>used</term> package. The allowed values of its
                     <code nobreak="false">visibility</code> attribute are <code nobreak="false">public</code>,
                  <code nobreak="false">private</code>, and <code nobreak="false">final</code>.</p><p>The <elcode>xsl:mode</elcode> declaration itself must not be overridden. A using
                  package must not contain an <elcode>xsl:mode</elcode> declaration whose name
                  matches that of a <code nobreak="false">public</code> or <code nobreak="false">final</code>
                  <elcode>xsl:mode</elcode> component accepted from a used package.</p><p>The <elcode>xsl:expose</elcode> and <elcode>xsl:accept</elcode> elements may be
                  used to reduce the visibility of a mode in a using package; the same rules apply
                  in general, though some of the rules are not applicable because, for example,
                  modes cannot be <code nobreak="false">abstract</code>.</p><p>It is not possible for a package to combine the template rules from two other
                  packages into a single mode. When <elcode>xsl:apply-templates</elcode> is used
                  without specifying a mode, the chosen template rules will always come from the
                  same package; when it is used with a named mode, then they will come from the
                  package where the mode is defined, or any package that uses that package and adds
                  template rules to the mode. If two template rules defined in different packages
                  match the same node, then the rule in the using package wins over any rule in the
                  used package; this decision is made before taking other factors such as import
                  precedence and priority into account.</p><p>A static error occurs if two modes with the same name are visible within a
                  package, either because they are both declared within the package, or because one
                  is declared within the package and the other is acquired from a used package, or
                  because both are accepted from different used packages.</p><p>The rules for matching template rules by <termref def="dt-import-precedence"/> and <termref def="dt-priority"/> operate as
                  normal, with the addition that template rules declared within an
                     <elcode>xsl:use-package</elcode> element have higher precedence than any
                  template rule declared in the used package. More specifically, given an <elcode>xsl:apply-templates</elcode> instruction
                     in package <var>P</var>, naming a mode <var>M</var> that is declared in a used
                     package <var>Q</var> and is overridden in <var>P</var>, the search order for
                     template rules is:</p><olist><item><p>Rules declared within <var>P</var> (specifically,
                           <elcode>xsl:template</elcode> rules declared as children of an
                           <elcode>xsl:override</elcode> element within the
                           <elcode>xsl:use-package</elcode> element that references package
                           <var>Q</var>). If there are multiple rules declared within <var>P</var>
                        that match a selected node, they are resolved on the basis of their explicit
                        or implicit <termref def="dt-priority"/>, and if the priorities are equal, the last one in <termref def="dt-declaration-order"/> wins.</p></item><item><p>Rules declared within <var>Q</var>, taking <termref def="dt-import-precedence"/>, <termref def="dt-priority"/>, and <termref def="dt-declaration-order"/> into account in the usual way (see <specref ref="conflict"/>).</p></item><item><p>Built-in template rules (see <specref ref="built-in-rule"/>) selected
                        according to the <code nobreak="false">on-no-match</code> attribute of the
                           <elcode>xsl:mode</elcode> declaration (in <var>Q</var>), or its
                        default.</p></item></olist><p>If the mode is overridden again in a package
                     <var>R</var> that uses <var>P</var>, then this search order is extended by
                  adding <var>R</var> at the start of the search list, and so on recursively.</p><note><p>If existing XSLT code has been written to use template rules in the unnamed
                     mode, a convenient way to incorporate this code into a <termref def="dt-library-package">library package</termref> is to add a stub module
                     that defines a new named <code nobreak="false">public</code> or <code nobreak="false">final</code> mode, in
                     which there is a single template rule whose content is the single instruction
                        <code nobreak="false">&lt;xsl:apply-templates select="."/&gt;</code>. This in effect redirects
                        <elcode>xsl:apply-templates</elcode> instructions using the named mode to
                     the rules defined in the unnamed mode.</p></note><div4 id="requiring-explicit-modes"><head>Requiring Explicit Mode Declarations</head><p>In previous versions of XSLT, modes were implicitly declared by simply using a
                     mode name in the <code nobreak="false">mode</code> attribute of <elcode>xsl:template</elcode>
                     or <elcode>xsl:apply-templates</elcode>. XSLT 3.0 introduced the ability to
                     declare a mode explicitly using an <elcode>xsl:mode</elcode> declaration (see
                        <specref ref="declaring-modes"/>).</p><p>By default, within a package that is defined using an explicit
                        <elcode>xsl:package</elcode> element, all modes must be explicitly declared.
                     In an implicit package, however (that is, one rooted at an
                        <elcode>xsl:stylesheet</elcode> or <elcode>xsl:transform</elcode> element),
                     modes can be implicitly declared as in previous XSLT versions.</p><p>The <code nobreak="false">declared-modes</code>
                     attribute of <elcode>xsl:package</elcode> determines whether or not modes that
                     are referenced within the package must be explicitly declared. 
                     
                     If the value is <code nobreak="false">yes</code> (the default),
                     then it is an error to use a mode name 
                        unless the package either contains
                     an explicit <elcode>xsl:mode</elcode> declaration for that mode, or accepts the mode
                     from a used package. If the value is <code nobreak="false">no</code>, then this is not an error.
                     
                     
                  
                  </p><p>This attribute affects all modules making up the package, it is not confined to
                     declarations appearing as children of the <elcode>xsl:package</elcode>
                     element.</p><p>
                     <error spec="XT" type="static" class="SE" code="3085"><p>It is a <termref def="dt-static-error">static error</termref>, 
                           when the <termref def="dt-effective-value"/> of the <code nobreak="false">declared-modes</code> attribute of 
                           an <elcode>xsl:package</elcode> element is <code nobreak="false">yes</code>, if the 
                           package contains an explicit reference to an undeclared mode, or if 
                           it implicitly uses the unnamed mode and the unnamed mode is undeclared.</p></error></p><p>For the purposes of the above rule:</p><olist><item><p>A mode is <term>declared</term> if either of the following conditions is true:</p><olist><item><p>The package contains an <elcode>xsl:mode</elcode> 
                                 declaration for that mode.</p></item><item><p>The mode is a public or final mode accepted 
                                 from a used package. </p></item></olist></item><item><p>The offending reference may be either an explicit mode name, or the token <code nobreak="false">#unnamed</code> 
                           treated as a reference to the unnamed mode, or a defaulted mode attribute, and it may occur in any of the following:</p><olist><item><p>The <code nobreak="false">mode</code> 
                                 attribute of an <elcode>xsl:template</elcode> declaration</p></item><item><p>The <code nobreak="false">mode</code> 
                                 attribute of an <elcode>xsl:apply-templates</elcode> instruction</p></item><item><p>An <code nobreak="false">[xsl:]default-mode</code> attribute.</p></item></olist></item><item><p>A package <term>implicitly uses the unnamed mode</term>
                           if either of the following conditions is true:</p><olist><item><p>There is an <elcode>xsl:apply-templates</elcode> 
                                 element with no <code nobreak="false">mode</code> attribute, and with no ancestor-or-self having 
                                 an <code nobreak="false">[xsl:]default-mode</code> attribute.</p></item><item><p>There is an <elcode>xsl:template</elcode> 
                                 element with a <code nobreak="false">match</code> attribute and no <code nobreak="false">mode</code> attribute, and with no ancestor-or-self having 
                                 an <code nobreak="false">[xsl:]default-mode</code> attribute.</p></item></olist></item></olist></div4></div3><div3 id="package-local-declarations"><head>Declarations Local to a Package</head><p>The <elcode>xsl:import</elcode> and
                     <elcode>xsl:include</elcode> declarations are local to a package.</p><p>Declarations of <termref def="dt-key">keys</termref>, <termref def="dt-accumulator">accumulators</termref>, 
                  <termref def="dt-decimal-format">decimal formats</termref>, namespace aliases (see
                     <specref ref="namespace-aliasing"/>), <termref def="dt-output-definition">output definitions</termref>, and <termref def="dt-character-map">character
                     maps</termref> within a package have local scope within that package —
                  they are all effectively private. The elements that declare these constructs do
                  not have a <code nobreak="false">visibility</code> attribute. The unnamed decimal format and the
                  unnamed output format are also local to a package.</p><p>If <elcode>xsl:strip-space</elcode> or <elcode>xsl:preserve-space</elcode>
                  declarations appear within a <termref def="dt-library-package">library
                     package</termref>, they only affect calls to the <xfunction>doc</xfunction> or
                     <function>document</function> functions appearing within that package. Such a declaration within the <termref def="dt-top-level-package"/> additionally affects stripping of whitespace in
                     the document that contains the <termref def="dt-global-context-item"/>.</p><p>An <elcode>xsl:decimal-format</elcode> declaration within a package applies only
                  to calls on <xfunction>format-number</xfunction> appearing within that
                  package.</p><p>An <elcode>xsl:namespace-alias</elcode> declaration within a package applies only
                  to literal result elements within the same package.</p><p>An <elcode>xsl:import-schema</elcode> declaration within a package adds the names
                  of the imported schema components to the static context for that package only;
                  these names are effectively private, in the sense that they do not become
                  available for use in any other packages. However, the names of schema components
                  must be consistent across the stylesheet as a whole: it is not possible for two
                  different packages within a stylesheet to use a type-name such as <code nobreak="false">part-number</code> to
                  refer to different schema-defined simple or complex types.</p><p>Type names used in the interface of public components in a package (for example,
                  in the arguments of a function) must be respected by callers of those components,
                  in the sense that the caller must supply values of the correct type. Often this
                  will mean that the using component, if it contains calls on such interfaces, must
                  itself import the necessary schema components. However, the requirement for an
                  explicit schema import applies only where the package contains explicit use of the
                  names of schema components required to call such interfaces.</p><note><p>For example, suppose a <termref def="dt-library-package">library
                        package</termref> contains a function which requires an argument of type
                        <code nobreak="false">mfg:part-number</code>. The caller of this function must supply an
                     argument of the correct type, but does not need to import the schema unless it
                     explicitly uses the schema type name <code nobreak="false">mfg:part-number</code>. If it
                     obtains an instance of this type from outside the package, for example as the
                     result of another function call, then it can supply this instance to the
                     acquired function even though it has not imported a schema that defines this
                     type.</p></note><p>At execution time, the schema available for validating instance documents contains
                  (at least) the union of the schema components imported into all constituent
                  packages of the stylesheet.</p></div3><div3 id="declaring-global-context-item"><head>Declaring the Global Context Item</head><p>The <elcode>xsl:global-context-item</elcode> element is used to declare whether a
                     <termref def="dt-global-context-item"/> is required, and if so, what its
                     <termref def="dt-required-type"/> is.</p><p>The element is a <termref def="dt-declaration"/> that
                  can appear at most once in any stylesheet module; and if more than one
                     <elcode>xsl:global-context-item</elcode> declaration appears within a <termref def="dt-package"/>, then the declarations must be consistent. Specifically, all
                  the attributes <rfc2119>must</rfc2119> have semantically equivalent values.</p><note><p>This means that omitting an attribute is equivalent to specifying its default
                     value explicitly; and purely lexical variations, such as the presence of whitespace
                     in an attribute value, are not considered significant.</p></note><p>
                  <error spec="XT" type="static" class="SE" code="3087"><p>It is a <termref def="dt-static-error">static error</termref> if more than
                        one <elcode>xsl:global-context-item</elcode> declaration appears within a
                           <termref def="dt-stylesheet-module"/>, or if several modules within a
                        single <termref def="dt-package"/> contain inconsistent
                           <elcode>xsl:global-context-item</elcode> declarations</p></error></p><p>If there is no <elcode>xsl:global-context-item</elcode> declaration for a package,
                  this is equivalent to specifying the empty element
                     <code nobreak="false">&lt;xsl:global-context-item/&gt;</code>, which imposes no constraints.</p><e:element-syntax xmlns:e="http://www.w3.org/1999/XSL/Spec/ElementSyntax" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" name="global-context-item">
      <e:in-category name="declaration"/>
      <e:attribute name="as">
         <e:data-type name="item-type" default="'item()'"/>
      </e:attribute>
      <e:attribute name="use" default="'optional'">
         <e:constant value="required"/>
         <e:constant value="optional"/>
         <e:constant value="absent"/>
      </e:attribute>
      <e:empty/>
      <e:allowed-parents>
         <e:parent name="package"/>
         <e:parent name="stylesheet"/>
         <e:parent name="transform"/>
      </e:allowed-parents>
   </e:element-syntax><p>The <code nobreak="false">use</code> attribute takes the value <code nobreak="false">required</code>,
                     <code nobreak="false">optional</code>, or <code nobreak="false">absent</code>. The
                  default is <code nobreak="false">optional</code>.</p><ulist><item><p>If the value <code nobreak="false">required</code> is specified, then there must be a
                           global context item. </p></item><item><p>If the value <code nobreak="false">optional</code> is specified, or if the attribute is
                           omitted, or if the <elcode>xsl:global-context-item</elcode> element is
                           omitted, then there may or may not be a global context item.</p></item><item><p>If the value <code nobreak="false">absent</code> is specified, then the global focus
                           (context item, position, and size) will be <termref def="dt-absent"/></p><note><p>This specification does not define whether supplying a global context
                              item in this situation results in an error or warning, or whether the
                              supplied context item is simply ignored.</p></note></item></ulist><p>If the <code nobreak="false">as</code> attribute is present then its value must be an <xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="XP40" ref="prod-xpath40-ItemType" xlink:type="simple">ItemType</xnt>. If the attribute is
                  omitted this is equivalent to specifying <code nobreak="false">as="item()"</code>.</p><p>The <code nobreak="false">as</code> attribute defines the required type of the global context
                  item. The default value is <code nobreak="false">as="item()"</code>. If a global context item is
                  supplied then it must conform to the required type, after conversion (if
                  necessary) using the <termref def="dt-coercion-rules"/>.</p><p><error spec="XT" type="static" class="SE" code="3089"><p>It is a <termref def="dt-static-error"/> if the <code nobreak="false">as</code> attribute is
                        present <error.extra>on the <elcode>xsl:global-context-item</elcode>
                           element</error.extra> when <code nobreak="false">use="absent"</code> is specified.</p></error></p><p>The global context item is available only within the <termref def="dt-top-level-package"/>. If a valid <elcode>xsl:global-context-item</elcode>
                  declaration appears within a <termref def="dt-library-package"/>, then it is
                  ignored, unless it specifies <code nobreak="false">use="required"</code>, in which case an error
                  is raised: <errorref spec="XT" class="TE" code="0590"/>.</p><note><p>In earlier releases of this specification, the <termref def="dt-global-context-item"/> and
                  the <termref def="dt-initial-match-selection"/> were essentially the same thing, often referred
                  to as the <emph>principal source document</emph>. In XSLT 3.0, they were separated:
                  the global context item is a single item accessible to the initializers of global variables
                  as the value of the expression <code nobreak="false">.</code> (dot), while the initial match selection
                  is a sequence of nodes or other items supplied to an initial implicit <elcode>xsl:apply-templates</elcode>
                  invocation.</p><p>APIs that were originally designed for use with earlier versions of XSLT
                  are likely to bundle the two concepts together.</p></note><p>A <termref def="dt-type-error"/> is raised if 
                  <phrase diff="chg" at="2022-01-01">the <termref def="dt-top-level-package"/> contains</phrase>
                  an <elcode>xsl:global-context-item</elcode>
                  declaration specifying a required type that does not match the supplied <termref def="dt-global-context-item"/>. The error code is the same as for
                     <elcode>xsl:param</elcode>: <errorref spec="XT" class="TE" code="0590"/>.
                  </p><note><p>If the <code nobreak="false">ItemType</code> is one that can only be satisfied by a
                     schema-validated input document, for example
                        <code nobreak="false">as="schema-element(invoice)"</code>, the <termref def="dt-processor">processor</termref> may interpret this as a request to apply schema
                     validation to the input. Similarly, if the <code nobreak="false">KindTest</code> indicates that
                     an element node is required, the processor may interpret this as a request to
                     supply the document element rather than the document node of a supplied input
                     document.</p></note><p diff="add" at="2022-01-01">
                  <error spec="XT" type="dynamic" class="DE" code="3086"><p>It is a <termref def="dt-dynamic-error">dynamic error</termref> if an
                        <elcode>xsl:global-context-item</elcode> declaration specifies
                     <code nobreak="false">use="required"</code>, and no global context item is supplied.</p></error></p></div3><div3 id="packages-csv-library-example"><head>Worked Example of a Library Package</head><p>The example in this section illustrates the use of overrides to customize or
                  extend a (fictional) library package named
                     <code nobreak="false">http://example.com/csv-parser</code>, which provides a parsing function
                  for data formatted as lines containing comma-separated values. For simplicity of
                  exposition, the example shows a simple, naive implementation; a realistic CSV
                  parser would be more complicated and make the example harder to follow.</p><note><p>This example package should not be confused with the behavior of the
               <function>parse-csv</function> function which has been added to the standard function
               library in version 4.0.</p></note><div4 id="csv-example-default-functionality"><head>Default Functionality of the CSV Package</head><p>The basic functionality of the package is provided by the function
                        <code nobreak="false">csv:parse</code>, which expects a string parameter named
                        <code nobreak="false">input</code>. By default, the function parses the input into lines,
                     and breaks lines on commas, returning as result an element named
                        <code nobreak="false">csv</code> containing one <code nobreak="false">row</code> element per line, each
                        <code nobreak="false">row</code> containing a sequence of <code nobreak="false">field</code> elements.</p><p>A simple stylesheet which uses this library and applies it to a string might
                     look like the following. The initial template applies <code nobreak="false">csv:parse</code> to
                     a suitable string and returns a copy of the result:</p><eg role="xslt-document" xml:space="preserve">&lt;?xml version="1.0" encoding="UTF-8"?&gt;
&lt;xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
   xmlns:xs="http://www.w3.org/2001/XMLSchema"
   xmlns:csv="http://example.com/csv"
   exclude-result-prefixes="xs csv"
   version="3.0"&gt;

   &lt;xsl:output indent="yes" /&gt;

   &lt;xsl:use-package name="http://example.com/csv-parser" 
                    package-version="*" /&gt;

   &lt;!-- example input "file"  --&gt;
   &lt;xsl:variable name="input" as="xs:string"&gt;
       name,id,postal code
       "Abel Braaksma",34291,1210 KA
       "Anders Berglund",473892,9843 ZD
   &lt;/xsl:variable&gt;

   &lt;!-- entry point --&gt;
   &lt;xsl:template name="xsl:initial-template"&gt;
       &lt;xsl:copy-of select="csv:parse($input)" /&gt;
   &lt;/xsl:template&gt;

&lt;/xsl:stylesheet&gt;
</eg><p>The result returned by this stylesheet would be:</p><eg role="xml" xml:space="preserve">&lt;csv&gt;
  &lt;row&gt;
    &lt;field quoted="no"&gt;name&lt;/field&gt;
    &lt;field quoted="no"&gt;id&lt;/field&gt;
    &lt;field quoted="no"&gt;postal code&lt;/field&gt;
  &lt;/row&gt;
  &lt;row&gt;
    &lt;field quoted="yes"&gt;Abel Braaksma&lt;/field&gt;
    &lt;field quoted="no"&gt;34291&lt;/field&gt;
    &lt;field quoted="no"&gt;1210 KA&lt;/field&gt;
  &lt;/row&gt;
  &lt;row&gt;
    &lt;field quoted="yes"&gt;Anders Berglund&lt;/field&gt;
    &lt;field quoted="no"&gt;473892&lt;/field&gt;
    &lt;field quoted="no"&gt;9843 ZD&lt;/field&gt;
  &lt;/row&gt;
&lt;/csv&gt;
</eg><p>Variations on this default behavior are achieved by overriding selected
                     declarations in the package, as described below.</p></div4><div4 id="csv-example-package-structure"><head>Package Structure</head><p>The package module itself is version 1.0.0 of a package called
                        <code nobreak="false">http://example.com/csv-parser</code>; it has the following
                     structure:</p><eg role="xslt-document" xml:space="preserve">&lt;?xml version="1.0" encoding="UTF-8"?&gt;
&lt;xsl:package
   name="http://example.com/csv-parser"
   package-version="1.0.0"
   xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
   xmlns:xs="http://www.w3.org/2001/XMLSchema"
   xmlns:csv="http://example.com/csv"
   exclude-result-prefixes="xs csv"
   declared-modes="yes"
   version="3.0"&gt;

   &lt;!--* Mode declarations ... *--&gt;
   &lt;!--* Variable declarations ... *--&gt;
   &lt;!--* Attribute-set declaration ... *--&gt;
   &lt;!--* Function declarations ... *--&gt;
   &lt;!--* Templates ... *--&gt;

&lt;/xsl:package&gt;</eg><p>The contents of the package (represented here by comments) are described more
                     fully below.</p></div4><div4 id="csv-example-customizing-parse"><head>The <code nobreak="false">csv:parse</code> Function and its User-customization Hooks</head><p>The <code nobreak="false">csv:parse</code> function is final and cannot be overridden. As can be
                     seen from the code below, it (1) parses its <code nobreak="false">input</code> parameter into
                     lines, (2) calls function <code nobreak="false">csv:preprocess-line</code> on each line, then
                     (3) applies the templates of mode <code nobreak="false">csv:parse-line</code> to the
                     pre-processed value. The result is then (4) processed again by mode
                        <code nobreak="false">csv:post-process</code>.</p><eg role="xslt-declaration xmlns:csv='http://example.com/csv'" xml:space="preserve">&lt;xsl:function name="csv:parse" visibility="final"&gt;
    &lt;xsl:param name="input" as="xs:string" /&gt;   
    &lt;xsl:variable name="result" as="element()"&gt;
        &lt;csv&gt;
            &lt;xsl:apply-templates 
                select="(tokenize($input, $csv:line-separator) 
                        ! csv:preprocess-line(.))" 
                mode="csv:parse-line" /&gt;
        &lt;/csv&gt;
    &lt;/xsl:variable&gt;
    &lt;xsl:apply-templates select="$result" 
                         mode="csv:post-process" /&gt;
&lt;/xsl:function&gt;
</eg><p>The default code for this processing is given below. Each part of the
                     processing except the first (the tokenization into lines) can be overridden by
                     the user of the package.</p></div4><div4 id="csv-example-line-breaking"><head>Breaking the Input into Lines</head><p>The first user-customization hook is given by the global variable
                        <code nobreak="false">csv:line-separator</code>, which specifies the line separator used to
                     break the input string into lines. It can be overridden by the user if need be.
                     The default declaration attempts to handle the line-separator sequences used by
                     most common operating systems in text files:</p><eg role="xslt-declaration xmlns:csv='http://example.com/csv'" xml:space="preserve">&lt;xsl:variable name="csv:line-separator" 
              as="xs:string" 
              select="'\r\n?|\n\r?'" 
              visibility="public"/&gt;
</eg></div4><div4 id="csv-example-preprocessing-lines"><head>Pre-processing the Lines</head><p>The function <code nobreak="false">csv:preprocess-line</code> calls
                        <code nobreak="false">normalize-space()</code> on its argument:</p><eg role="xslt-declaration xmlns:csv='http://example.com/csv'" xml:space="preserve">&lt;xsl:function name="csv:preprocess-line" 
                 as="xs:string?" 
                 visibility="public"&gt;
    &lt;xsl:param name="line" as="xs:string" /&gt;
    &lt;xsl:sequence select="normalize-space($line)" /&gt;
&lt;/xsl:function&gt;
</eg><p>Because the function is declared <code nobreak="false">public</code>, it can be overridden by a
                     user. (This might be necessary, for example, if whitespace within quoted
                     strings needs to be preserved.)</p></div4><div4 id="example-csv-mode-parse-line"><head>The Mode <code nobreak="false">csv:parse-line</code></head><p>By default, the mode <code nobreak="false">csv:parse-line</code> parses the current item (this
                     will be one line of the input data) into fields, using mode
                        <code nobreak="false">csv:parse-field</code> on the individual fields and (by default)
                     wrapping the result in a <code nobreak="false">row</code> element.</p><p>The mode is declared with <code nobreak="false">visibility="public"</code> to allow it to be
                     called from elsewhere and overridden:</p><eg role="xslt-declaration xmlns:csv='http://example.com/csv'" xml:space="preserve">&lt;xsl:mode name="csv:parse-line" visibility="public"/&gt;</eg><eg role="xslt-declaration xmlns:csv='http://example.com/csv'" xml:space="preserve">&lt;xsl:template match="." mode="csv:parse-line"&gt;
    &lt;row&gt;
        &lt;xsl:apply-templates 
            select="tokenize(., $csv:field-separator)" 
            mode="csv:parse-field" /&gt;
    &lt;/row&gt;
&lt;/xsl:template&gt;
</eg><p>This relies on the variable <code nobreak="false">csv:field-separator</code>, which is a comma
                     by default but which can be overridden by the user to parse tab-separated data
                     or data with other delimiters.</p><eg role="xslt-declaration xmlns:csv='http://example.com/csv'" xml:space="preserve">&lt;xsl:variable name="csv:field-separator" 
              as="xs:string" 
              select="','" 
              visibility="public"/&gt;
</eg><p>The default implementation of <code nobreak="false">csv:parse-line</code> does not handle
                     occurrences of the field separator occurring within quoted strings. The user
                     can add templates to the mode to provide that functionality. </p></div4><div4 id="csv-example-mode"><head>Mode <code nobreak="false">csv:parse-field</code></head><p>Mode <code nobreak="false">csv:parse-field</code> processes the current item as a field; by
                     default it strips quotation marks from the value, calls the function
                        <code nobreak="false">csv:preprocess-field()</code> on it, and wraps the result in a
                        <code nobreak="false">field</code> element, which carries the attributes declared in the
                     attribute set <code nobreak="false">csv:field-attributes</code>.</p><eg role="xslt-declaration xmlns:csv='http://example.com/csv'" xml:space="preserve">
&lt;xsl:template match="." 
              mode="csv:parse-field" 
              expand-text="yes"&gt;
    &lt;xsl:variable name="string-body-pattern"
                  as="xs:string"
                  select="'([^' || $csv:validated-quote || ']*)'"/&gt;
    &lt;xsl:variable name="quoted-value"
                  as="xs:string"
                  select="$csv:validated-quote 
                          || $string-body-pattern 
                          || $csv:validated-quote"/&gt;
    &lt;xsl:variable name="unquoted-value"
                  as="xs:string"
                  select="'(.+)'"/&gt;

    &lt;field xsl:use-attribute-sets="csv:field-attributes"&gt;{
        csv:preprocess-field(
          replace(., 
                  $quoted-value || '|' || $unquoted-value, 
                  '$1$2'))
    }&lt;/field&gt;
&lt;/xsl:template&gt;
</eg><p>The attribute set <code nobreak="false">csv:field-attributes</code> includes, by default, a
                        <code nobreak="false">quoted</code> attribute which has the values <code nobreak="false">yes</code> or
                        <code nobreak="false">no</code> to show whether the input value was quoted or not.</p><eg role="xslt-declaration xmlns:csv='http://example.com/csv'" xml:space="preserve">&lt;xsl:attribute-set name="csv:field-attributes" 
                   visibility="public"&gt;
    &lt;xsl:attribute name="quoted" 
                   select="if (starts-with(., $csv:validated-quote)) 
                           then 'yes' 
                           else 'no'" /&gt;
&lt;/xsl:attribute-set&gt;
</eg><p>The mode <code nobreak="false">csv:parse-field</code> is declared with
                        <code nobreak="false">visibility="public"</code> to allow it to be called from elsewhere and
                     overridden; it specifies <code nobreak="false">on-no-match="shallow-copy"</code> so that any
                     string not matching a template will simply be copied:</p><eg role="xslt-declaration xmlns:csv='http://example.com/csv'" xml:space="preserve">&lt;xsl:mode name="csv:parse-field"
          on-no-match="shallow-copy" 
          visibility="public"/&gt;
</eg></div4><div4 id="csv-example-variable"><head>The <code nobreak="false">csv:quote</code> Variable</head><p>The variable <code nobreak="false">csv:quote</code> can be used to specify the character used
                     in a particular input stream to quote values.</p><eg role="xslt-declaration xmlns:csv='http://example.com/csv'" xml:space="preserve">&lt;xsl:variable name="csv:quote" 
              as="xs:string" 
              select="'&amp;quot;'" 
              visibility="public"/&gt;
</eg><p>The template given above assumes that the variable is one character long. To
                     ensure that any overriding value of the variable is properly checked, references to the value use a
                     second variable <code nobreak="false">csv:validated-quote</code>, which
                     is declared <code nobreak="false">private</code> to ensure that the checking cannot be
                     disabled.</p><eg role="xslt-declaration xmlns:csv='http://example.com/csv'" xml:space="preserve">&lt;xsl:variable name="csv:validated-quote" visibility="private"
   as="xs:string" select="
       if (string-length($csv:quote) ne 1) 
       then error( #csv:ERR001, 
                  'Incorrect length for $csv:quote, should be 1') 
       else $csv:quote" /&gt;
</eg><p>When the value of <code nobreak="false">csv:quote</code> is not
                     exactly one character long, the reference to
                        <code nobreak="false">csv:validated-quote</code> will cause an error (csv:ERR001)
                     to be raised.</p></div4><div4 id="csv-example-preprocess-field"><head>The <code nobreak="false">csv:preprocess-field</code> Function</head><p>The function <code nobreak="false">csv:preprocess-field</code> is called on each field after
                     any quotation marks are stripped and before it is written out as the value of a
                        <code nobreak="false">field</code> element:</p><eg role="xslt-declaration xmlns:csv='http://example.com/csv'" xml:space="preserve">&lt;xsl:function name="csv:preprocess-field" 
              as="xs:string"&gt;
    &lt;xsl:param name="field" 
               as="xs:string" /&gt;
    &lt;xsl:sequence select="$field" /&gt;
&lt;/xsl:function&gt;
</eg><p>As can be seen, the function does nothing but return its input; its only
                     purpose is to provide the opportunity for the user to supply a suitable
                     function to be invoked at this point in the processing of each field.</p></div4><div4 id="csv-example-postprocess"><head>The Mode <code nobreak="false">csv:post-process</code></head><p>The mode <code nobreak="false">csv:post-process</code> is intended solely as a hook for user
                     code. By default, it does nothing.</p><p>The package defines no templates for this mode; the mode definition makes it
                     return a copy of its input:</p><eg role="xslt-declaration xmlns:csv='http://example.com/csv'" xml:space="preserve">&lt;xsl:mode name="csv:post-process" 
          on-no-match="shallow-copy" 
          visibility="public"/&gt;
</eg></div4><div4 id="csv-example-overriding"><head>Overriding the Default Behavior</head><p>As can be seen from the code shown above, the package provides several
                     opportunities for users to override the default behavior:</p><ulist><item><p>The global variables <code nobreak="false">csv:line-separator</code>,
                              <code nobreak="false">csv:field-separator</code>, and <code nobreak="false">csv:quote</code> can be
                           overridden to specify the character strings used to separate lines and
                           fields and to quote individual field values.</p></item><item><p>The function <code nobreak="false">csv:preprocess-line</code> can be overridden to do
                           more (or less) than stripping white space; the function
                              <code nobreak="false">csv:preprocess-field</code> can be overridden to process
                           individual field values.</p></item><item><p>Templates can be added to the modes <code nobreak="false">csv:parse-line</code>,
                              <code nobreak="false">csv:parse-field</code>, and <code nobreak="false">csv:post-process</code> to
                           change their behavior.</p></item><item><p>The attribute set <code nobreak="false">csv:field-attributes</code> can be overridden to
                           specify a different set of attributes (or none) for <code nobreak="false">field</code>
                           elements.</p></item></ulist><p>The following using stylesheet illustrates the use of the
                        <elcode>xsl:override</elcode> element to take advantage of several of these
                     opportunities:</p><eg role="xslt-document" xml:space="preserve">
&lt;xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
   xmlns:xs="http://www.w3.org/2001/XMLSchema"
   xmlns:csv="http://example.com/csv"
   exclude-result-prefixes="xs csv"
   version="3.0"&gt;

   &lt;xsl:output indent="yes" /&gt;

   &lt;xsl:use-package name="http://example.com/csv-parser" 
                    package-version="*"&gt;
       &lt;xsl:override&gt;
           &lt;!-- Change the root element from 'csv' to 'root' --&gt;
           &lt;xsl:template match="csv" mode="csv:post-process"&gt;
               &lt;root&gt;
                   &lt;xsl:apply-templates mode="csv:post-process" /&gt;
               &lt;/root&gt;
           &lt;/xsl:template&gt;

           &lt;!-- add an extra attribute that uses the context item --&gt;
           &lt;xsl:attribute-set name="csv:field-attributes" 
                              use-attribute-sets="xsl:original"&gt;
               &lt;xsl:attribute name="type" 
                              select="if (. castable as xs:decimal) 
                                      then 'numeric' 
                                      else 'string'" /&gt;
           &lt;/xsl:attribute-set&gt;          

           &lt;!-- use semicolon not comma between fields --&gt;
           &lt;xsl:variable name="csv:field-separator" 
                         as="xs:string" select="';'" 
                         visibility="public"/&gt;

           &lt;!-- prevent empty rows from appearing with empty lines --&gt;
           &lt;xsl:function name="csv:preprocess-line" 
                         as="xs:string?" 
                         visibility="public"&gt;
               &lt;xsl:param name="line" as="xs:string" /&gt;
               &lt;xsl:variable name="norm-line" 
                             select="normalize-space(xsl:original($line))" /&gt;
               &lt;xsl:sequence select="if (string-length($norm-line) &gt; 0) 
                                     then $norm-line 
                                     else ()" /&gt;
           &lt;/xsl:function&gt;
       &lt;/xsl:override&gt;
   &lt;/xsl:use-package&gt;

   &lt;!-- example input "file"  --&gt;
   &lt;xsl:variable name="input" as="xs:string"&gt;
       name;id;postal code
       "Braaksma Abel";34291;1210 KA
       "Berglund Anders";473892;9843 ZD
   &lt;/xsl:variable&gt;

   &lt;!-- entry point --&gt;
   &lt;xsl:template name="xsl:initial-template"&gt;
       &lt;xsl:copy-of select="csv:parse($input)" /&gt;
   &lt;/xsl:template&gt;

&lt;/xsl:stylesheet&gt;</eg><note><ulist><item><p>As it does elsewhere, the visibility of components declared within
                                 <elcode>xsl:override</elcode> defaults to <code nobreak="false">private</code>; to keep
                              the component public, it is necessary to specify visibility
                              explicitly.</p></item><item><p>The types and optionality of all function parameters must match those
                              of the function being overridden; for function overriding to be
                              feasible, packages must document the function signature
                              thoroughly.</p></item><item><p>The names, types, and optionality of all named-template parameters
                              must match those of the template being overridden; for overriding to
                              be feasible, packages must document the template signature
                              thoroughly.</p></item><item><p>The values for the attributes in the attribute set
                                 <code nobreak="false">csv:field-attributes</code> are calculated once for each
                              element for which the attribute set is supplied; the
                                 <code nobreak="false">select</code> attributes which determine the values can thus
                              refer to the context item. Here, the value specification for the
                                 <code nobreak="false">type</code> attribute checks to see whether the string value
                              of the context item is numeric by inquiring whether it can be cast to
                              decimal, and sets the value for the <code nobreak="false">type</code> attribute
                              accordingly.</p></item></ulist></note><p>The result returned by this stylesheet would be:</p><eg role="xml" xml:space="preserve">&lt;root&gt;
  &lt;row&gt;
    &lt;field quoted="no" type="string"&gt;name&lt;/field&gt;
    &lt;field quoted="no" type="string"&gt;id&lt;/field&gt;
    &lt;field quoted="no" type="string"&gt;postal code&lt;/field&gt;
  &lt;/row&gt;
  &lt;row&gt;
    &lt;field quoted="yes" type="string"&gt;Braaksma Abel&lt;/field&gt;
    &lt;field quoted="no" type="numeric"&gt;34291&lt;/field&gt;
    &lt;field quoted="no" type="string"&gt;1210 KA&lt;/field&gt;
  &lt;/row&gt;
  &lt;row&gt;
    &lt;field quoted="yes" type="string"&gt;Berglund Anders&lt;/field&gt;
    &lt;field quoted="no" type="numeric"&gt;473892&lt;/field&gt;
    &lt;field quoted="no" type="string"&gt;9843 ZD&lt;/field&gt;
  &lt;/row&gt;
&lt;/root&gt;
</eg></div4></div3></div2><div2 id="stylesheet-modules"><head>Stylesheet Modules</head><p>
               <termdef id="dt-stylesheet-module" term="stylesheet module">A <termref def="dt-package">package</termref> consists of one or
                  more <term>stylesheet modules</term>, each one forming all or part of an XML
                  document.</termdef>
            </p><note><p>A stylesheet module is represented by an XDM element node (see <bibref ref="xpath-datamodel-40"/>). In the case of a standard stylesheet module, this
                  will be an <elcode>xsl:stylesheet</elcode> or <elcode>xsl:transform</elcode>
                  element. In the case of a simplified stylesheet module, it can be any element (not
                  in the <termref def="dt-xslt-namespace">XSLT namespace</termref>) that has an
                     <code nobreak="false">xsl:version</code> attribute.</p><p>Although stylesheet modules will commonly be maintained in the form of documents
                  conforming to XML 1.0 or XML 1.1, this specification does not mandate such a
                  representation. As with <termref def="dt-source-tree">source trees</termref>, the
                  way in which stylesheet modules are constructed, from textual XML or otherwise, is
                  outside the scope of this specification.</p></note><p>The principal stylesheet module of a package may take one
               of three forms:</p><ulist><item><p>A package manifest, as described in <specref ref="packages"/>, which is a
                     subtree rooted at an <elcode>xsl:package</elcode> element</p></item><item><p>An implicit package, which is a subtree rooted at an
                        <elcode>xsl:stylesheet</elcode> or <elcode>xsl:transform</elcode> element.
                     This is transformed automatically to a package as described in <specref ref="packages"/>. </p></item><item><p>A simplified stylesheet, which is a subtree rooted at a literal result element,
                     as described in <specref ref="simplified-stylesheet"/>. This is first converted
                     to an implicit package by wrapping it in an <elcode>xsl:stylesheet</elcode>
                     element using the transformation described in <specref ref="simplified-stylesheet"/>, and then to an explicit package (rooted at an
                        <elcode>xsl:package</elcode> element) using the transformation described in
                        <specref ref="packages"/>. </p></item></ulist><p>A stylesheet module other than the principal stylesheet
               module of a package may take either of two forms:</p><ulist><item><p><termdef id="dt-standard-stylesheet-module" term="standard stylesheet module">A
                           <term>standard stylesheet module</term>, which is a subtree rooted at an
                           <elcode>xsl:stylesheet</elcode> or <elcode>xsl:transform</elcode>
                        element.</termdef></p></item><item><p><termdef id="dt-simplified-stylesheet-module" term="simplified stylesheet">A
                           <term>simplified stylesheet</term>, which is a subtree rooted at a
                           <termref def="dt-literal-result-element">literal result
                        element</termref>, as described in <specref ref="simplified-stylesheet"/>.
                        This is first converted to a <termref def="dt-standard-stylesheet-module">standard stylesheet module</termref> by wrapping it in an xsl:stylesheet
                        element using the transformation described in <specref ref="simplified-stylesheet"/>.</termdef>
                  </p></item></ulist><p>Whichever of the above forms a module takes, the outermost
               element (<elcode>xsl:package</elcode>, <elcode>xsl:stylesheet</elcode>, or a <termref def="dt-literal-result-element"/>) <rfc2119>may</rfc2119> either be the outermost
               element of an XML document, or it <rfc2119>may</rfc2119> be a child of some
               (non-XSLT) element in a host document. </p><p><termdef id="dt-embedded-stylesheet-module" term="embedded stylesheet module">A stylesheet module whose outermost element is
                  the child of a non-XSLT element in a host document is referred to as an
                     <term>embedded stylesheet module</term>.</termdef>
            </p></div2><div2 id="stylesheet-element"><head>Stylesheet Element</head><changes><change issue="87" PR="353" date="2023-04-19">
                  A new attribute, <code nobreak="false">main-module</code>, is added to the <elcode>xsl:stylesheet</elcode>
                  element. The attribute is provided for the benefit of development tools such as syntax-directed
                  editors to provide information about all the components (variables, functions, etc) visible
                  within a stylesheet module.
               </change></changes><e:element-syntax xmlns:e="http://www.w3.org/1999/XSL/Spec/ElementSyntax" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" name="stylesheet">
      <e:attribute name="id">
         <e:data-type name="id"/>
      </e:attribute>
      <e:attribute name="version" required="yes">
         <e:data-type name="decimal"/>
      </e:attribute>
      <e:attribute name="default-mode" default="'#unnamed'">
         <e:data-type name="eqname"/>
         <e:constant value="#unnamed"/>
      </e:attribute>
      <e:attribute name="default-validation" default="'strip'">
         <e:constant value="preserve"/>
         <e:constant value="strip"/>
      </e:attribute>
      <e:attribute name="input-type-annotations" default="'unspecified'">
         <e:constant value="preserve"/>
         <e:constant value="strip"/>
         <e:constant value="unspecified"/>
      </e:attribute>
      <e:attribute name="default-collation">
         <e:data-type name="uris"/>
      </e:attribute>
      <e:attribute name="extension-element-prefixes">
         <e:data-type name="prefixes"/>
      </e:attribute>
      <e:attribute name="exclude-result-prefixes">
         <e:data-type name="prefixes"/>
      </e:attribute>
      <e:attribute name="expand-text">
         <e:data-type name="boolean"/>
      </e:attribute>
      <e:attribute name="fixed-namespaces" required="no">
         <e:data-type name="string"/>
      </e:attribute>
      <e:attribute name="main-module" required="no">
         <e:data-type name="uri"/>
      </e:attribute>
      <e:attribute name="schema-role" required="no">
         <e:data-type name="ncname"/>
      </e:attribute>
      <e:attribute name="use-when" default="true()">
         <e:data-type name="expression"/>
      </e:attribute>
      <e:attribute name="xpath-default-namespace">
         <e:data-type name="uri"/>
      </e:attribute>
      <e:sequence>
         <e:model name="declarations"/>
      </e:sequence>
   </e:element-syntax><e:element-syntax xmlns:e="http://www.w3.org/1999/XSL/Spec/ElementSyntax" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" name="transform">
      <e:attribute name="id">
         <e:data-type name="id"/>
      </e:attribute>
      <e:attribute name="version" required="yes">
         <e:data-type name="decimal"/>
      </e:attribute>
      <e:attribute name="default-mode" default="'#unnamed'">
         <e:data-type name="eqname"/>
         <e:constant value="#unnamed"/>
      </e:attribute>
      <e:attribute name="default-validation" default="'strip'">
         <e:constant value="preserve"/>
         <e:constant value="strip"/>
      </e:attribute>
      <e:attribute name="input-type-annotations" default="'unspecified'">
         <e:constant value="preserve"/>
         <e:constant value="strip"/>
         <e:constant value="unspecified"/>
      </e:attribute>
      <e:attribute name="default-collation">
         <e:data-type name="uris"/>
      </e:attribute>
      <e:attribute name="extension-element-prefixes">
         <e:data-type name="prefixes"/>
      </e:attribute>
      <e:attribute name="exclude-result-prefixes">
         <e:data-type name="prefixes"/>
      </e:attribute>
      <e:attribute name="expand-text" default="'no'">
         <e:data-type name="boolean"/>
      </e:attribute>
      <e:attribute name="fixed-namespaces">
         <e:data-type name="string"/>
      </e:attribute>
      <e:attribute name="main-module">
         <e:data-type name="uri"/>
      </e:attribute>
      <e:attribute name="schema-role" required="no">
         <e:data-type name="ncname"/>
      </e:attribute>
      <e:attribute name="use-when" default="true()">
         <e:data-type name="expression"/>
      </e:attribute>
      <e:attribute name="xpath-default-namespace">
         <e:data-type name="uri"/>
      </e:attribute>
      <e:sequence>
         <e:model name="declarations"/>
      </e:sequence>
   </e:element-syntax><p>A stylesheet module is represented by an <elcode>xsl:stylesheet</elcode> element in
               an XML document. <elcode>xsl:transform</elcode> is allowed as a synonym for
                  <elcode>xsl:stylesheet</elcode>; everything this specification says about the
                  <elcode>xsl:stylesheet</elcode> element applies equally to
                  <elcode>xsl:transform</elcode>.</p><p>The <code nobreak="false">version</code> attribute indicates the version
               of XSLT that the stylesheet module requires. The attribute is
                  <rfc2119>required</rfc2119>.</p><p>
               <error spec="XT" type="static" class="SE" code="0110"><p>The value of the <code nobreak="false">version</code> attribute <rfc2119>must</rfc2119> be a number:
                     specifically, it <rfc2119>must</rfc2119> be a valid instance of the type
                        <code nobreak="false">xs:decimal</code> as defined in <bibref ref="xmlschema-2"/>.</p></error>
            </p><p>The <code nobreak="false">version</code> attribute is intended to indicate the
               version of the XSLT specification against which the stylesheet is written. In a
               stylesheet written to use XSLT 4.0, the value <rfc2119>should</rfc2119> normally be
               set to <code nobreak="false">4.0</code>. If the value is numerically less than 4.0, the
               stylesheet is processed using the rules for <termref def="dt-backwards-compatible-behavior">backwards compatible behavior</termref>
               (see <specref ref="backwards"/>). If the value is numerically greater than
               <phrase diff="chg" at="2023-02-24">4.0</phrase>, the stylesheet is processed using the rules for 
               <termref def="dt-forwards-compatible-behavior"/> (see <specref ref="forwards"/>).</p><p>The effect of the <code nobreak="false">input-type-annotations</code> attribute is described in
                  <specref ref="stripping-annotations"/>.</p><p>The <code nobreak="false">[xsl:]default-validation</code> attribute defines the default value of the
                  <code nobreak="false">validation</code> attribute of all relevant instructions appearing within
               its scope. For details of the effect of this attribute, see <specref ref="validation"/>.</p><p diff="add" at="2023-02-16">The optional <code nobreak="false">main-module</code> attribute is purely documentary.
            By including this attribute in every <termref def="dt-stylesheet-module"/> of a <termref def="dt-package"/>,
            an XSLT editing tool may be enabled to locate the <termref def="dt-principal-stylesheet-module"/> of the relevant package,
            and thus to gather information about all the global variables, templates, and functions available
            within the module being edited.
            This information can be used (for example) to enable auto-completion and error highlighting of the code as it is
            entered. Note that it may be inconvenient or misleading to use this attribute when the <termref def="dt-stylesheet-module"/>
            module is used as a shared component within multiple <termref def="dt-package">packages</termref>.
          </p><p>
               <error spec="XT" type="static" class="SE" code="0120"><p>An <elcode>xsl:stylesheet</elcode>, <elcode>xsl:transform</elcode>,
                  or <elcode>xsl:package</elcode> element <rfc2119>must not</rfc2119> have any
                     text node children.</p></error> (This rule applies after stripping of <termref def="dt-whitespace-text-node">whitespace text nodes</termref> as described in <specref ref="stylesheet-stripping"/>.)</p><p>
               <termdef id="dt-top-level" term="top-level">An element occurring as a child of an
                     <elcode>xsl:package</elcode>,
                     <elcode>xsl:stylesheet</elcode>,
                        <elcode>xsl:transform</elcode>, or <elcode>xsl:override</elcode>
                  element is called a <term>top-level</term> element.</termdef>
            </p><p>
               <termdef id="dt-declaration" term="declaration">Top-level elements fall into two
                  categories: declarations, and user-defined data elements. Top-level elements whose
                  names are in the <termref def="dt-xslt-namespace">XSLT namespace</termref> are
                     <term>declarations</term>. Top-level elements in any other namespace are
                     <termref def="dt-data-element">user-defined data elements</termref> (see
                     <specref ref="user-defined-top-level"/>)</termdef>.</p><p>The <termref def="dt-declaration">declaration</termref> elements permitted in the
                  <elcode>xsl:stylesheet</elcode> element are:</p><slist><sitem>
                  <elcode>xsl:accumulator</elcode>
               </sitem><sitem>
                  <elcode>xsl:attribute-set</elcode>
               </sitem><sitem>
                  <elcode>xsl:character-map</elcode>
               </sitem><sitem>
                  <elcode>xsl:decimal-format</elcode>
               </sitem><sitem>
                  <elcode>xsl:function</elcode>
               </sitem><sitem>
                  <elcode>xsl:global-context-item</elcode>
               </sitem><sitem>
                  <elcode>xsl:import</elcode>
               </sitem><sitem>
                  <elcode>xsl:import-schema</elcode>
               </sitem><sitem>
                  <elcode>xsl:include</elcode>
               </sitem><sitem>
                  <elcode>xsl:item-type</elcode>
               </sitem><sitem>
                  <elcode>xsl:key</elcode>
               </sitem><sitem>                 
                  <elcode>xsl:mode</elcode>                 
               </sitem><sitem>
                  <elcode>xsl:namespace-alias</elcode>
               </sitem><sitem>
                  <elcode>xsl:output</elcode>
               </sitem><sitem>
                  <elcode>xsl:param</elcode>
               </sitem><sitem>
                  <elcode>xsl:preserve-space</elcode>
               </sitem><sitem>
                  <elcode>xsl:record-type</elcode>
               </sitem><sitem>
                  <elcode>xsl:strip-space</elcode>
               </sitem><sitem>
                  <elcode>xsl:template</elcode>
               </sitem><sitem>
                  <elcode>xsl:use-package</elcode>
               </sitem><sitem>
                  <elcode>xsl:variable</elcode>
               </sitem></slist><p>Note that the <elcode>xsl:variable</elcode> and <elcode>xsl:param</elcode> elements
               can act either as <termref def="dt-declaration">declarations</termref> or as <termref def="dt-instruction">instructions</termref>. A global variable or parameter is
               defined using a declaration; a local variable or parameter using an instruction.</p><p>The child elements of the <elcode>xsl:stylesheet</elcode>
               element may appear in any order. In most cases, the ordering of these elements does
               not affect the results of the transformation; however:</p><ulist><item><p>As described in <specref ref="conflict"/>, when two template rules with the
                     same <termref def="dt-priority">priority</termref> match the same nodes, there
                     are situations where the order of the template rules will affect which is
                     chosen.</p></item><item><p>Forwards references to <termref def="dt-static-variable">static variables</termref> are not allowed in <termref def="dt-static-expression">static expressions</termref>.</p></item></ulist><div3 id="fixed-namespaces" diff="add" at="2023-05-04"><head>The <code nobreak="false">fixed-namespaces</code> Attribute</head><changes><change issue="369" PR="470" date="2023-11-29">
                     The <elcode>xsl:stylesheet</elcode>, <elcode>xsl:transform</elcode>, or <elcode>xsl:package</elcode>
                     element may have a <code nobreak="false">fixed-namespaces</code> attribute making it easier to have the same
                     namespace declarations in force throughout a stylesheet.
                  </change></changes><p>The <code nobreak="false">fixed-namespaces</code> attribute, if present, defines the 
                  <termref def="dt-fixed-namespace-bindings"/>
               for a <termref def="dt-stylesheet-module"/>. The attribute may appear only on the
               outermost element of a stylesheet module (<elcode>xsl:stylesheet</elcode>,
               <elcode>xsl:transform</elcode>, or <elcode>xsl:package</elcode>). It is
               not available with <termref def="dt-simplified-stylesheet-module">simplified stylesheet modules</termref>.</p><p>If the <code nobreak="false">fixed-namespaces</code> attribute is present, then it defines the entire
               set of namespace bindings present in the static context of XPath expressions and 
               <termref def="dt-pattern">patterns</termref> within the stylesheet,
               as well as other constructs where namespace prefixes are used in attribute and text nodes,
               such as the <code nobreak="false">name</code> attribute of declarations like <elcode>xsl:function</elcode>
               and <elcode>xsl:variable</elcode>, and <code nobreak="false">as</code> and <code nobreak="false">type</code> attributes
               referring to item types and schema types.</p><p>The value of the attribute is a whitespace-separated list of tokens, where each token
                  contributes one or more namespace bindings to the <termref def="dt-fixed-namespace-bindings"/>
                  of the <termref def="dt-stylesheet-module"/>. Each token must be one of the following. If
                  a token falls into more than one of these categories, then the first one that applies
                  takes precedence.</p><ulist><item><p>The string <code nobreak="false">#standard</code>, which is equivalent to specifying
                  <code nobreak="false">xsl xml xs xsi fn math map array err</code>. This has the effect of binding
                     each of these namespace prefixes to the <termref def="dt-reserved-namespace"/> with which 
                     it is conventionally associated.</p></item><item><p>An <code nobreak="false">NCName</code> corresponding to one of the namespace prefixes present
                    in the in-scope namespaces of the containing element node. This has the effect of adding
                    the corresponding namespace binding to the <termref def="dt-fixed-namespace-bindings"/>.</p></item><item><p>Any one of the strings <code nobreak="false">xsl</code>, <code nobreak="false">xml</code>,
                     <code nobreak="false">xs</code>, <code nobreak="false">xsi</code>, <code nobreak="false">fn</code>, <code nobreak="false">math</code>,
                     <code nobreak="false">map</code>, <code nobreak="false">array</code>, <code nobreak="false">err</code>. This has the effect of binding
                     that particular namespace prefix to the <termref def="dt-reserved-namespace"/> with which 
                     it is conventionally associated, whether or not the <termref def="dt-native-namespace-bindings"/>
                     contain a binding for this prefix.</p><note><p>Including <code nobreak="false">xml</code> in the list has no effect, since the XML namespace
                     will always be in scope anyway.</p></note><p>If the namespace prefix is explicitly bound to a different namespace, for example
                     <code nobreak="false">xmlns:math="java:java.util.Math"</code>, then that binding takes precedence.</p></item><item><p>A string in the form <code nobreak="false">prefix=uri</code>, where <code nobreak="false">prefix</code> is an <code nobreak="false">NCName</code>
                     and <code nobreak="false">uri</code> is a (non-empty) namespace URI: for example,
                     <code nobreak="false">xalan=http://xml.apache.org/xalan</code>. This has the effect of binding the specified
                     prefix to the specified URI.</p></item><item><p>A <termref def="dt-uri-reference"/> identifying the location of an
                     XML document whose namespace bindings are to be used. For example, <code nobreak="false">./package.xsl</code>.
                     A token is interpreted as a URI if it does not match any of the other possibilities listed above
                     (which will be the case if it contains a <code nobreak="false">"/"</code> as in this example).</p><p>The <termref def="dt-uri-reference"/> is used to locate an XML document, in the same way
                     as described for <elcode>xsl:include</elcode> and <elcode>xsl:import</elcode> in
                     <specref ref="locating-modules"/>. The resource that is retrieved may be any namespace well-formed 
                     XML document. The in-scope namespace bindings of the outermost element of this document are
                     added to the <termref def="dt-fixed-namespace-bindings"/> of the stylesheet module.</p><note><p>Such URIs cannot contain whitespace.</p></note></item></ulist><p>If different tokens in the <code nobreak="false">fixed-namespaces</code> attribute result in multiple bindings
               for the same namespace prefix, the last one wins.</p><p>
                  <error spec="XT" type="static" class="SE" code="0122"><p>It is a <termref def="dt-static-error">static error</termref> if a token
                        appearing in the <code nobreak="false">fixed-namespaces</code> attribute takes a form
                        that is not one of the permitted forms, or if it is interpreted as a URI
                     but cannot be dereferenced to locate a namespace well-formed XML document.
                     It is not permitted to bind the prefix <code nobreak="false">xmlns</code>. It is not permitted to bind the
                        prefix <code nobreak="false">xml</code> or the XML namespace URI <code nobreak="false">http://www.w3.org/XML/1998/namespace</code>, other than
                     to each other.</p></error>
               </p><p>The following observations apply when a <code nobreak="false">fixed-namespaces</code> attribute is present:</p><ulist><item><p>All expressions in the stylesheet module will have the same 
                     <xtermref spec="XP40" ref="dt-static-namespaces">statically known
                        namespaces</xtermref> in their static context. This means that all 
                     prefixes used in XPath expressions, patterns,
                  and similar constructs must be declared at the top level.</p></item><item><p>Namespace prefixes used in element and attribute names in the stylesheet
                  cannot be declared using this mechanism. Such prefixes must be bound using
                  <termref def="dt-native-namespace-bindings"/>. This also applies to namespace
                  prefixes used in the <code nobreak="false">[xsl:]exclude-result-prefixes</code> 
                     and <code nobreak="false">[xsl:]extension-element-prefixes</code> attributes, and the
                  <code nobreak="false">stylesheet-prefix</code> and <code nobreak="false">result-prefix</code> attributes
                  of <elcode>xsl:namespace-alias</elcode>.</p></item><item><p>It is not an error for an element within a stylesheet module
                     to rebind a prefix listed in the <code nobreak="false">fixed-namespaces</code> attribute 
                     to a different URI; however this rebinding has no effect on the static
                  context of XPath expressions and other similar constructs within its scope.</p></item><item><p>The <code nobreak="false">fixed-namespaces</code> attribute has no effect on the interpretation
                  of unprefixed names.</p></item></ulist><note><p>It is possible to use
                     the <termref def="dt-fixed-namespace-bindings"/> in other attributes of the <elcode>xsl:stylesheet</elcode>
                  element, such as <code nobreak="false">default-mode</code>. It is also possible to use them in
                  shadow attributes (see <specref ref="shadow-attributes"/>).</p><p>It is possible for the <code nobreak="false">fixed-namespaces</code> attribute itself to be supplied as
                  a shadow attribute (written with an underscore, <code nobreak="false">_fixed-namespaces</code>). 
                  It can then refer to <termref def="dt-static-variable">static variables</termref>
                  declared in an importing or including <termref def="dt-stylesheet-module"/>. This provides an
                  alternative way of sharing common namespace bindings throughout a <termref def="dt-package"/>.</p></note><note><p>The ability to fetch namespace bindings using a URI can be exploited in various ways:</p><ulist><item><p>Generally, the benefit is that it avoids repeating the same information
                     in every stylesheet module, thereby reducing the amount of boilerplate code and keeping
                     common information in a common place. This satisfies the <term>DRY</term> principle in software
                     engineering: <emph>Don't Repeat Yourself</emph>.</p></item><item><p>The document identified by the URI may be a stylesheet module.
                     One way to use the feature is to use the <termref def="dt-package-manifest"/>
                     as the primary source for namespace bindings.</p></item><item><p>It is also possible to adopt the namespace bindings from a sample source
                     document. For example, if it is known that the stylesheet is designed primarily to process
                     documents whose first start tag takes the form:</p><eg xml:space="preserve">&lt;w:document
  xmlns:wps="http://schemas.microsoft.com/office/word/2010/wordprocessingShape"
  xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
  xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main"&gt;</eg><p>then these three namespace bindings may conveniently be copied to the stylesheet
                     by referencing a sample document of this form.</p><p>Note however, that only the namespace bindings from the outermost element of
                     the document will be copied.</p></item><item><p>It is possible to supply multiple URIs to assemble namespace bindings
                     from more than one source.</p></item><item><p>Namespace bindings taken from an external document may be overridden
                        using a local declaration for the prefix. This must appear after the URI
                     in the content of the <code nobreak="false">fixed-namespaces</code> attribute.</p></item></ulist></note><note><p>Using the <code nobreak="false">fixed-namespaces</code> attribute rather 
                     than <termref def="dt-native-namespace-bindings"/>
                  to bind namespaces has a number of potential benefits:</p><ulist><item><p>It reduces repetitive coding across stylesheet module boundaries,
                     and thus eliminates a source of potential errors.</p></item><item><p>It ensures that all expressions in a stylesheet module have the same
                     namespace bindings in their static context. This can reduce implementation overheads
                     because it reduces the need to maintain the namespace context at the level of individual
                     expressions through rewrites such as function inlining. With processors that compile
                     stylesheets to a persistent executable form, it can contribute to a reduction in 
                     the size of compiled code.</p></item><item><p>Namespaces bound in this way will never accidentally leak into a result tree;
                     there is no need to exclude them using <code nobreak="false">[xsl:]exclude-result-prefixes</code>.</p></item><item><p>Namespaces declared on literal result elements are used purely to define the
                     namespace of elements and attributes within the result tree; they no longer leak into
                     the static context used when evaluating XPath expressions.</p></item></ulist></note></div3><div3 id="default-collation-attribute"><head>The <code nobreak="false">default-collation</code> Attribute</head><p>The <code nobreak="false">default-collation</code> attribute is a <termref def="dt-standard-attributes">standard attribute</termref> that may appear on
                  any element in the XSLT namespace, or (as <code nobreak="false">xsl:default-collation</code>) on a
                     <termref def="dt-literal-result-element">literal result element</termref>.</p><p>The attribute, when it appears on an element
                        <var>E</var>, is used to specify the default collation used by all XPath
                     expressions appearing in attributes or <termref def="dt-text-value-template">text value templates</termref> that have <var>E</var> as an
                     ancestor, unless overridden by another <code nobreak="false">default-collation</code>
                  attribute on an inner element. It also determines the collation used by certain
                  XSLT constructs (such as <elcode>xsl:key</elcode> and
                     <elcode>xsl:for-each-group</elcode>) within its scope.</p><p>The value of the attribute is a whitespace-separated list of collation URIs. If
                  any of these URIs is a relative URI reference,
                  then it is resolved <phrase diff="chg" at="2023-05-19">as described in 
                     <xspecref spec="FO40" ref="collations"/>.</phrase>. If the implementation recognizes one or more of the resulting absolute
                  collation URIs, then it uses the first one that it recognizes as the default
                  collation.</p><p>
                  <error spec="XT" type="static" class="SE" code="0125"><p>It is a <termref def="dt-static-error">static error</termref> if the value
                        of an <code nobreak="false">[xsl:]default-collation</code> attribute, after resolving
                        against the base URI, contains no URI that the implementation recognizes as
                        a collation URI.</p></error>
               </p><note><p>The reason the attribute allows a list of collation URIs is that collation URIs
                     will often be meaningful only to one particular XSLT implementation.
                     Stylesheets designed to run with several different implementations can
                     therefore specify several different collation URIs, one for use with each. To
                     avoid the above error condition, it is possible to include as the last
                     collation URI in the list either the Unicode Codepoint Collation or a collation in the UCA family (see <xspecref spec="FO40" ref="uca-collations"/>) with the parameter
                        <code nobreak="false">fallback=yes</code>.</p></note><p>The <code nobreak="false">[xsl:]default-collation</code> attribute does not affect the collation
                  used by <elcode>xsl:sort</elcode> or by <elcode>xsl:merge</elcode>.</p><p>In the absence of an
                     <code nobreak="false">[xsl:]default-collation</code> attribute, the default collation
                     <rfc2119>may</rfc2119> be set by the calling application in an <termref def="dt-implementation-defined"/> way. The recommended default, unless the user
                  chooses otherwise, is to use the Unicode codepoint collation.</p><imp-def-feature id="idf-api-defaultcollation">In the absence of an
                     <code nobreak="false">[xsl:]default-collation</code> attribute, the default collation
                     <rfc2119>may</rfc2119> be set by the calling application in an <termref def="dt-implementation-defined"/> way.</imp-def-feature></div3><div3 id="default-mode"><head>The <code nobreak="false">default-mode</code> Attribute</head><p><termdef id="dt-default-mode" term="default mode">The 
                  <code nobreak="false">[xsl:]default-mode</code> attribute defines the <term>default mode</term>,
                  which is used as the default value for the
                     <termref def="dt-mode">mode</termref> attribute of all
                     <elcode>xsl:template</elcode> and <elcode>xsl:apply-templates</elcode> elements
                     within its scope.</termdef></p><p>More specifically, when an element <var>E</var> matches
                  the pattern <code nobreak="false">(xsl:template[@match] | xsl:apply-templates)[not(@mode) or
                     normalize-space(@mode) eq "#default"]</code> (using the Unicode codepoint
                  collation), then the <termref def="dt-effective-value"/> of the <code nobreak="false">mode</code> attribute is taken
                  from the value of the <code nobreak="false">[xsl:]default-mode</code> attribute of the innermost
                  ancestor-or-self element of <var>E</var> that has such an attribute. If there is
                  no such element, then the default is the <termref def="dt-unnamed-mode">unnamed
                     mode</termref>. This is equivalent to specifying <code nobreak="false">#unnamed</code>.</p><p>In addition, when the attribute appears on the <elcode>xsl:package</elcode>,
                  <elcode>xsl:stylesheet</elcode>, or <elcode>xsl:transform</elcode> element of the 
                  <termref def="dt-principal-stylesheet-module"/> of the <termref def="dt-top-level-package"/>,
                     it provides a default value for the <termref def="dt-initial-mode"/> used on stylesheet
                     invocation.</p><p>The value of the <code nobreak="false">[xsl:]default-mode</code> attribute <rfc2119>must</rfc2119>
                  either be an <termref def="dt-eqname">EQName</termref>, or the token <code nobreak="false">#unnamed</code> which refers to
                  the <termref def="dt-unnamed-mode">unnamed mode</termref>.</p><note><p>This attribute is provided to support an approach to stylesheet modularity in
                     which all the template rules for one <termref def="dt-mode">mode</termref> are
                     collected together into a single <termref def="dt-stylesheet-module">stylesheet
                        module</termref>. Using this attribute reduces the risk of forgetting to
                     specify the mode in one or more places where it is needed, and it also makes it
                     easier to reuse an existing stylesheet module that does not use modes in an
                     application where modes are needed to avoid conflicts with existing template
                     rules.</p><p>It is not necessary for the referenced mode to be
                     explicitly declared in an <elcode>xsl:mode</elcode> declaration, unless this is
                     mandated by the <code nobreak="false">declared-modes</code> attribute (which defaults to
                        <code nobreak="false">yes</code> on an <elcode>xsl:package</elcode> element).</p></note></div3><div3 id="user-defined-top-level"><head>User-defined Data Elements</head><p>
                  <termdef id="dt-data-element" term="user-defined data element">In addition to
                        <termref def="dt-declaration">declarations</termref>, the
                        <elcode>xsl:stylesheet</elcode> element may contain among its children any
                     element not from the <termref def="dt-xslt-namespace">XSLT namespace</termref>,
                     provided that the <termref def="dt-expanded-qname">expanded QName</termref> of
                     the element has a non-null namespace URI. Such elements are referred to as
                        <term>user-defined data elements</term>.</termdef>
               </p><p>
                  <error spec="XT" type="static" class="SE" code="0130"><p>It is a <termref def="dt-static-error">static error</termref> if an
                        <elcode>xsl:stylesheet</elcode>, <elcode>xsl:transform</elcode>,
                           or <elcode>xsl:package</elcode> element has a child element whose name
                        has a null namespace URI.</p></error>
               </p><p>An implementation <rfc2119>may</rfc2119> attach an <termref def="dt-implementation-defined"/> meaning to user-defined data elements that
                  appear in particular namespaces. The set of namespaces that are recognized for
                  such data elements is <termref def="dt-implementation-defined">implementation-defined</termref>. The presence of a user-defined data element
                     <rfc2119>must not</rfc2119> change the behavior of <termref def="dt-xslt-element">XSLT elements</termref> and functions defined in this
                  document; for example, it is not permitted for a user-defined data element to
                  specify that <elcode>xsl:apply-templates</elcode> should use different rules to
                  resolve conflicts. The constraints on what user-defined data elements can and
                  cannot do are exactly the same as the constraints on <termref def="dt-extension-attribute">extension attributes</termref>, described in
                     <specref ref="extension-attributes"/>. Thus, an implementation is always free
                  to ignore user-defined data elements, and <rfc2119>must</rfc2119> ignore such data
                  elements without giving an error if it does not recognize the namespace URI. </p><imp-def-feature id="idf-ext-namespaces">The set of namespaces that are specially
                  recognized by the implementation (for example, for user-defined data elements, and
                     <termref def="dt-extension-attribute">extension attributes</termref>) is
                     <termref def="dt-implementation-defined"/>.</imp-def-feature><imp-def-feature id="idf-ext-dataelements">The effect of user-defined data elements
                  whose name is in a namespace recognized by the implementation is <termref def="dt-implementation-defined"/>.</imp-def-feature><p>User-defined data elements can provide, for example,</p><ulist><item><p>information used by <termref def="dt-extension-instruction">extension
                           instructions</termref> or <termref def="dt-extension-function">extension
                           functions</termref> (see <specref ref="extension"/>),</p></item><item><p>information about what to do with any <termref def="dt-final-result-tree">final result tree</termref>,</p></item><item><p>information about how to construct <termref def="dt-source-tree">source
                           trees</termref>,</p></item><item><p>optimization hints for the <termref def="dt-processor">processor</termref>,</p></item><item><p>metadata about the stylesheet,</p></item><item><p>structured documentation for the stylesheet.</p></item></ulist></div3></div2><div2 id="simplified-stylesheet"><head>Simplified Stylesheet Modules</head><changes><change issue="90" PR="599" date="2023-09-12">
                  Simplified stylesheets no longer require an <code nobreak="false">xsl:version</code> attribute
                  (which means they might not need a declaration of the XSLT namespace). Unless otherwise
                  specified, a 4.0 simplified stylesheet defaults <code nobreak="false">expand-text</code> to <code nobreak="false">true</code>.
               </change><change issue="2322" PR="2323" date="2025-11-30">
                  The outermost element of a simplified stylesheet need no longer be a literal result element,
                  it can now be any instruction (including <elcode>xsl:result-document</elcode>). This allows a
                  simplified stylesheet to produce JSON output as well as XML or HTML.
               </change></changes><p>A simplified syntax is allowed for a <termref def="dt-stylesheet-module">stylesheet
               module</termref> that defines only a single template rule.
               A simplified stylesheet module consist of a single <termref def="dt-instruction"/> or
               <termref def="dt-literal-result-element"/>
               together with its contents. Such a stylesheet module is equivalent to a standard stylesheet module
               whose <elcode>xsl:stylesheet</elcode> element contains a 
               <termref def="dt-template-rule">template rule</termref> containing the instruction or literal result
               element; the template rule has a match <termref def="dt-pattern"/> of <code nobreak="false">match="."</code>,
               which matches any item.</p><example diff="add" at="2023-07-08"><head>A Simplified Stylesheet</head><p>The following example shows a stylesheet that simply evaluates one XPath expression:</p><eg xml:space="preserve">&lt;out&gt;{count(//*)}&lt;/out&gt;</eg><p>The output of the stylesheet will be an XML document such as <code nobreak="false">&lt;out&gt;17&lt;/out&gt;</code>
                  showing the number of elements found in the supplied source document.</p><p>This simplified stylesheet is defined to be equivalent to the following expanded stylesheet:</p><eg xml:space="preserve">&lt;xsl:stylesheet xmlns="http://www.w3.org/1999/XSL/Transform"
                  version="4.0" expand-text="yes"&gt;
    &lt;xsl:template match="."&gt;
        &lt;out&gt;{count(//*)}&lt;/out&gt;
    &lt;/xsl:template&gt;
&lt;/xsl:stylesheet&gt;</eg><p>Because the stylesheet contains no elements or attributes in the XSLT namespace, it does
               not need to contain any namespace declarations.</p></example><p>A simplified stylesheet can contain XSLT instructions, in which case the XSLT namespace needs
               to be declared. This is illustrated in the next example.</p><example><head>A Simplified Stylesheet Containing XSLT Instructions</head><p>This stylesheet outputs an HTML document containing a table that summarizes the value
                  of transactions according to their rate of tax:</p><eg xml:space="preserve" role="xml">&lt;html xmlns="http://www.w3.org/1999/xhtml"
      xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
      xsl:version="4.0"&gt;
  &lt;head&gt;
    &lt;title&gt;Expenditure by Tax Rate&lt;/title&gt;
  &lt;/head&gt;
  &lt;body&gt;
    &lt;table&gt;
      &lt;thead&gt;
        &lt;tr&gt;
           &lt;th&gt;Gross Amount&lt;/th&gt;
           &lt;th&gt;Tax Rate&lt;/th&gt;
        &lt;/tr&gt;
      &lt;/thead&gt;
      &lt;tbody&gt;
        &lt;xsl:for-each-group select="//transaction" group-by="vat-rate"&gt;
          &lt;tr&gt;
            &lt;td&gt;{sum(current-group()/value)}&lt;/td&gt;
            &lt;td&gt;{current-grouping-key()}&lt;/td&gt;
          &lt;/tr&gt;
        &lt;/xsl:for-each-group&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/body&gt;
&lt;/html&gt;</eg></example><example><head>A Simplified Stylesheet to Transform JSON</head><p>This example expects as input a parsed JSON document containing an array of records. It outputs a serialized
               JSON document containing a selection of fields from these records.</p><eg xml:space="preserve">
&lt;xsl:result-document method="json" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"&gt;
  &lt;xsl:array&gt;
    &lt;xsl:for-each select="?*"&gt;
      &lt;xsl:record first="?firstName" 
                  last="?surname"
                  phone="?mobile"/&gt;
    &lt;/xsl:for-each&gt;
  &lt;/xsl:array&gt;
&lt;/xsl:result-document&gt;</eg></example><p>More formally, a simplified stylesheet module is equivalent to the standard
               stylesheet module that would be generated by applying the following transformation to
               the simplified stylesheet module, invoking the transformation by calling the <termref def="dt-named-template">named template</termref>
               <code nobreak="false">expand</code>, with the outermost element as the <termref def="dt-context-node">context node</termref>: </p><eg xml:space="preserve" role="xslt-document">&lt;xsl:stylesheet version="4.0"
                xmlns:xsl="http://www.w3.org/1999/XSL/Transform"&amp;gt;

&lt;xsl:template name="expand"&gt;
  &lt;xsl:element name="xsl:stylesheet"&gt;
    &lt;xsl:variable name="version"
        select="(if (self::xsl:*) then @version else @xsl:version)
                   otherwise '4.0'"/&gt;
    &lt;xsl:attribute name="version" select="$version"/&gt;
    &lt;xsl:attribute name="expand-text" 
                   select="not(number($version) le 3.0)"/&gt;
    &lt;xsl:element name="xsl:template"&gt;
      &lt;xsl:attribute name="match" select="'.'"/&gt;
      &lt;xsl:copy-of select="."/&gt;
    &lt;/xsl:element&gt;
  &lt;/xsl:element&gt;
&lt;/xsl:template&gt;

&lt;/xsl:stylesheet&gt;</eg><p>The allowed content of an instruction or literal result element when used as a simplified stylesheet
               is the same as when it occurs within a <termref def="dt-sequence-constructor">sequence constructor</termref>. Thus, 
               a simplified stylesheet cannot contain <termref def="dt-declaration">declarations</termref>. In particular, simplified stylesheets therefore
               cannot use <termref def="dt-template-rule">template rules</termref>, <termref def="dt-global-variable">global variables</termref>, 
               <termref def="dt-stylesheet-parameter">stylesheet parameters</termref>, 
               <termref def="dt-stylesheet-function">stylesheet functions</termref>, 
               <termref def="dt-key">keys</termref>, <termref def="dt-attribute-set">attribute-sets</termref>, or
               <termref def="dt-output-definition">output definitions</termref>. Furthermore, they
               cannot contain <elcode>xsl:include</elcode>, <elcode>xsl:import</elcode>, or <elcode>xsl:use-package</elcode>
               declarations.</p><p>The only useful way to initiate the transformation is to supply an item
               as the <termref def="dt-initial-match-selection"/>, to be matched by the implicit
               <code nobreak="false">match="."</code> template rule using the <termref def="dt-unnamed-mode">unnamed mode</termref>. </p><note diff="chg" at="2023-07-08"><p>There are several significant changes to simplified stylesheets in XSLT 4.0.</p><olist><item><p>It is no longer required to include an <code nobreak="false">xsl:version</code> attribute; this
                     in turn means it is often no longer necessary to declare the <code nobreak="false">xsl</code> namespace.
                     The <code nobreak="false">xsl:version</code> attribute defaults to the version of the XSLT processor,
                     that is, "4.0" for an XSLT 4.0 processor.</p></item><item><p>If the <code nobreak="false">xsl:version</code> attribute is omitted, or is set to "4.0" or a larger
                     value, then the <code nobreak="false">expand-text</code> attribute defaults to <code nobreak="false">true</code>, meaning that 
                     <termref def="dt-text-value-template">text value templates</termref> are recognized.</p></item><item><p>The outermost element of a simplified stylesheet can be any instruction (for example,
                  <code nobreak="false">xsl:array</code>, <code nobreak="false">xsl:map</code>, or <code nobreak="false">xsl:result-document</code>), allowing the
                  stylesheet to deliver arrays, maps, or serialized JSON.</p></item><item><p>The match pattern of the implicit template rule uses <code nobreak="false">match="."</code> rather
                  than <code nobreak="false">match="/"</code>, allowing the <termref def="dt-initial-match-selection"/> to be
                  any item, not only a document node.</p><p>There may be edge cases where this causes a backwards incompatibility. For example,
                     if a transformation using a simplified stylesheet is invoked supplying an element node
                     (rather than a document node) as the <termref def="dt-initial-match-selection"/>,
                     then under 4.0 this will match the implicitly-defined template rule (<code nobreak="false">match="."</code>
                     matches an element node), whereas in 3.0 it would have been processed using the built-in
                     template rules for the unnamed mode. A similar situation arises if a simplified stylesheet
                     module is imported into a larger stylesheet package, and the implicitly-defined template
                     rule is invoked using <elcode>xsl:next-match</elcode> or <elcode>xsl:apply-imports</elcode>.</p></item></olist></note><note><p>It is technically valid for the outermost element to be <elcode>xsl:variable</elcode> or
               <elcode>xsl:param</elcode>, because these are defined as <termref def="dt-instruction">instructions</termref>;
               however, this achieves no useful purpose because the result of these instructions is the empty sequence.</p></note></div2><div2 id="backwards"><head>Backwards Compatible Processing</head><p><termdef id="dt-effective-version" term="effective version">The <term>effective
                     version</term> of an element in a <termref def="dt-stylesheet-module"/> or <termref def="dt-package-manifest"/> is the decimal value of the <code nobreak="false">[xsl:]version</code> attribute
                  (see <specref ref="standard-attributes"/>) on that element or on the innermost
                  ancestor element that has such an attribute, <phrase diff="chg" at="issue649">subject
                  to special rules for the <elcode>xsl:output</elcode> and <elcode>xsl:fallback</elcode>
                     elements.</phrase></termdef></p><p>These rules do not apply to the <elcode>xsl:output</elcode> element, whose
               <code nobreak="false">version</code> attribute has an entirely different purpose: it is used to
               define the version of the output method to be used for serialization.
               The <termref def="dt-effective-version"/> of an <elcode>xsl:output</elcode> element
            is the effective version of its parent element.</p><p>There are additional rules for an <elcode>xsl:fallback</elcode> element: see
            <specref ref="forwards"/>.</p><p>
               <termdef id="dt-backwards-compatible-behavior" term="backwards compatible behavior">An element is 
                  processed with <term>backwards compatible behavior</term> if its
                     <termref def="dt-effective-version">effective version</termref> is less than
                  <phrase diff="chg" at="2023-02-24">4.0</phrase>.</termdef>
            </p><p>Specifically:</p><ulist><item><p>If the <termref def="dt-effective-version">effective version</termref> is equal
                     to 1.0, then the element is processed with XSLT 1.0 behavior as described in
                        <specref ref="backwards-1.0"/>.</p></item><item><p>If the <termref def="dt-effective-version">effective version</termref> is equal
                     to 2.0, then the element is processed with XSLT 2.0 behavior as described in
                        <specref ref="backwards-2.0"/>.</p></item><item diff="add" at="2023-02-28"><p>If the <termref def="dt-effective-version">effective version</termref> is equal
                     to 3.0, then the element is processed with XSLT 3.0 behavior as described in
                     <specref ref="backwards-3.0"/>.</p></item><item><p>If the <termref def="dt-effective-version">effective version</termref> is any
                     other value less than <phrase diff="chg" at="2023-02-24">4.0</phrase>, 
                     the <rfc2119>recommended</rfc2119> action is to
                     raise a static error; however, processors <rfc2119>may</rfc2119> recognize
                     such values and process the element in an <termref def="dt-implementation-defined"/> way.</p><imp-def-feature id="idf-err-unknownversion">If the 
                     <termref def="dt-effective-version">effective version</termref> of any element in the
                     stylesheet is not 1.0 or 2.0 but is less than <phrase diff="chg" at="2023-02-24">4.0</phrase>, the
                        <rfc2119>recommended</rfc2119> action is to raise a static error; however,
                     processors <rfc2119>may</rfc2119> recognize such values and process the element
                     in an <termref def="dt-implementation-defined"/> way.</imp-def-feature><note><p>XSLT 1.0 allowed the <code nobreak="false">version</code> attribute to take any decimal
                        value, and invoked forwards compatible processing for any value other than
                        1.0. XSLT 2.0 allowed the attribute to take any decimal value, and invoked
                        backwards compatible (i.e. 1.0-compatible) processing for any value less
                        than 2.0. Some stylesheets may therefore be encountered that use values
                        other than 1.0 or 2.0. In particular, the value 1.1 is sometimes
                        encountered, as it was used at one stage in a draft language proposal.</p></note></item></ulist><p>It is <termref def="dt-implementation-defined"/> whether a particular XSLT 4.0
               implementation supports backwards compatible behavior for any XSLT version earlier
               than XSLT 4.0.</p><p>
               <error spec="XT" type="dynamic" class="DE" code="0160"><p>It is a <termref def="dt-dynamic-error"> dynamic error</termref> if an element has
                     an <termref def="dt-effective-version">effective version</termref> of
                     <var>V</var> (with <var>V</var> &lt; <phrase diff="chg" at="2023-02-24">4.0</phrase>) when the implementation does not
                     support backwards compatible behavior for XSLT version <var>V</var>.</p></error>
            </p><imp-def-feature id="idf-feature-backwardscompatibility">It is implementation-defined
               whether an XSLT 4.0 processor supports backwards
               compatible behavior for any XSLT version earlier than XSLT 4.0.</imp-def-feature><note><p>By making use of backwards compatible behavior, it is possible to write the
                  stylesheet in a way that ensures that its results when processed with an XSLT 4.0
                  processor are identical to the effects of processing the same stylesheet using
                     a processor for an earlier version of XSLT.
                  To assist with transition, some parts of a stylesheet may be processed with
                  backwards compatible behavior enabled, and other parts with this behavior
                  disabled.</p><p>All data values manipulated by an XSLT 4.0
                  processor are defined by the XDM data model, whether or not the relevant
                  expressions use backwards compatible behavior. Because the same data model is used
                  in both cases, expressions are fully composable. The result of evaluating
                  instructions or expressions with backwards compatible behavior is fully defined in
                  the XSLT 4.0 and XPath 4.0 specifications, it is not defined by reference to earlier versions of the XSLT and XPath
                     specifications. </p><p>To write a stylesheet that makes use of features that
                     are new in version <var>N</var>, while also working with a processor that only
                     supports XSLT version <var>M</var> (<var>M</var> &lt; <var>N</var>),
                  it is necessary to understand both the rules for backwards compatible behavior in
                     XSLT version <var>N</var>, and the rules for
                  forwards compatible behavior in XSLT version
                        <var>M</var>. If the <elcode>xsl:stylesheet</elcode> element
                  specifies <phrase>a <code nobreak="false">version</code> attribute with a value greater than 1.0</phrase>, then an XSLT 1.0
                  processor will ignore <phrase diff="del" at="2023-02-24">XSLT 2.0 and XSLT 3.0</phrase>
                  <termref def="dt-declaration">declarations</termref> that were not defined in XSLT
                  1.0, for example <elcode>xsl:function</elcode>,
                     <elcode>xsl:import-schema</elcode><phrase diff="add" at="2023-02-24">, 
                        and <elcode>xsl:mode</elcode></phrase>. If any new XSLT
                  <phrase diff="chg" at="2023-02-24">4.0 instructions are used (for example <elcode>xsl:switch</elcode>
                     or <elcode>xsl:array</elcode>)</phrase>, or if new XPath
                  <phrase diff="chg" at="2023-02-24">4.0 features are used (for example, keyword arguments in function calls)</phrase>, 
                     then the stylesheet must provide
                  fallback behavior that relies only on facilities available in the earliest XSLT version supported. The fallback
                  behavior can be invoked by using the <elcode>xsl:fallback</elcode> instruction, or
                  by testing the results of the <function>function-available</function> or
                     <function>element-available</function> functions, or by testing the value of
                  the <code nobreak="false">xsl:version</code> property returned by the
                     <function>system-property</function> function.</p></note><div3 id="backwards-1.0"><head>XSLT 1.0 Compatibility Mode</head><p><termdef id="dt-xslt-10-behavior" term="XSLT 1.0 behavior">An element in the
                     stylesheet is processed with <term>XSLT 1.0 behavior</term> if its <termref def="dt-effective-version">effective version</termref> is equal to
                     1.0.</termdef></p><p>In this mode, if any attribute contains an XPath <termref def="dt-expression">expression</termref>, then the expression is evaluated with <termref def="dt-xpath-compat-mode">XPath 1.0 compatibility mode</termref> set to
                     <code nobreak="false">true</code>. For details of this mode, see <xspecref spec="XP40" ref="static_context"/>. Expressions contained in
                        <termref def="dt-text-value-template">text value templates</termref> are
                     always evaluated with <termref def="dt-xpath-compat-mode">XPath 1.0
                        compatibility mode</termref> set to <code nobreak="false">false</code>, since this construct
                     was not available in XSLT 1.0.</p><p>Furthermore, in such an expression any function call for which no implementation
                  is available (unless it uses the <termref def="dt-standard-function-namespace">standard function namespace</termref>) is bound to a fallback error function
                  whose effect when evaluated is to raise a dynamic error <errorref spec="XT" class="DE" code="1425"/> . The effect is that with backwards compatible
                  behavior enabled, calls on <termref def="dt-extension-function">extension
                     functions</termref> that are not available in a particular implementation do
                  not cause an error unless the function call is actually evaluated. For further
                  details, see <specref ref="extension-functions"/>.</p><note><p>This might appear to contradict the specification of XPath 3.0, which states that a static error [XPST0017] is raised
                     when an expression contains a call to a function that is not present (with
                     matching name and arity) in the static context. This apparent contradiction is
                     resolved by specifying that the XSLT processor constructs a static context for
                     the expression in which every possible function name and arity (other than
                     names in the <termref def="dt-standard-function-namespace">standard function
                        namespace</termref>) is present; when no other implementation of the
                     function is available, the function call is bound to a fallback error function
                     whose run-time effect is to raise a dynamic error.</p></note><p>Certain XSLT constructs also produce different results when XSLT 1.0 compatibility
                  mode is enabled. This is described separately for each such construct.</p></div3><div3 id="backwards-2.0"><head>XSLT 2.0 Compatibility Mode</head><p><termdef id="dt-xslt-20-behavior" term="XSLT 2.0 behavior">An element is processed
                     with <term>XSLT 2.0 behavior</term> if its <termref def="dt-effective-version">effective version</termref> is equal to 2.0.</termdef></p><p>In this specification, no differences are defined for XSLT 2.0 behavior. An XSLT
                  <phrase diff="chg" at="2023-02-24">4.0</phrase> processor will therefore 
                  produce the same results whether the <termref def="dt-effective-version">effective version</termref> of an element is set to
                  2.0 or <phrase diff="chg" at="2023-02-24">4.0</phrase>.</p><note><p>An XSLT 2.0 processor, by contrast, will in some cases produce different
                     results in the two cases. For example, if the stylesheet contains an
                        <elcode>xsl:switch</elcode> instruction with an
                     <elcode>xsl:fallback</elcode> child, an XSLT <phrase diff="chg" at="2023-02-24">4.0</phrase> processor will process the
                        <elcode>xsl:switch</elcode> instruction regardless whether the effective
                     version is 2.0, 3.0, <phrase diff="chg" at="2023-02-24">or 4.0</phrase>, while an 
                     XSLT 2.0 processor will raise a static error
                     if the effective version is 2.0, and will take the fallback action if the
                     effective version is 3.0 or 4.0.</p></note></div3><div3 id="backwards-3.0" diff="add" at="2023-02-24"><head>XSLT 3.0 Compatibility Mode</head><p><termdef id="dt-xslt-30-behavior" term="XSLT 3.0 behavior">An element is processed
                  with <term>XSLT 3.0 behavior</term> if its <termref def="dt-effective-version">effective version</termref> 
                  is equal to 3.0.</termdef></p><p>In this specification, no differences are defined for XSLT 3.0 behavior. An XSLT
                  <phrase diff="chg" at="2023-02-24">4.0</phrase> processor will therefore 
                  produce the same results whether the <termref def="dt-effective-version">effective version</termref> of an element is set to
                  3.0 or <phrase diff="chg" at="2023-02-24">4.0</phrase>.</p><note><p>An XSLT 3.0 processor, by contrast, will in some cases produce different
                     results in the two cases. For example, if the stylesheet contains an
                     <elcode>xsl:switch</elcode> instruction with an
                     <elcode>xsl:fallback</elcode> child, an XSLT <phrase diff="chg" at="2023-02-24">4.0</phrase> processor will process the
                     <elcode>xsl:switch</elcode> instruction regardless whether the effective
                     version is 2.0, 3.0, <phrase diff="chg" at="2023-02-24">or 4.0</phrase>, while an 
                     XSLT 3.0 processor will raise a static error
                     if the effective version is 2.0 or 3.0, and will take the fallback action if the
                     effective version is 4.0.</p></note></div3></div2><div2 id="forwards"><head>Forwards Compatible Processing</head><p>The intent of forwards compatible behavior is to make it possible to write a
               stylesheet that takes advantage of features introduced in some version of XSLT
               subsequent to XSLT 4.0, while retaining the
               ability to execute the stylesheet with an XSLT 4.0
               processor using appropriate fallback behavior.</p><p>It is always possible to write conditional code to run under different XSLT versions
               by using the <code nobreak="false">use-when</code> feature described in <specref ref="conditional-inclusion"/>. 
               The rules for forwards compatible behavior
               supplement this mechanism in two ways:</p><ulist><item><p>Certain constructs in the stylesheet that mean nothing to an XSLT 4.0 processor are ignored, 
                     rather than being treated as errors.</p></item><item><p>Explicit fallback behavior can be defined for instructions defined in a future
                     XSLT release, using the <elcode>xsl:fallback</elcode> instruction.</p></item></ulist><p>The detailed rules follow.</p><p>
               <termdef id="dt-forwards-compatible-behavior" term="forwards compatible behavior">An
                  element is processed with <term>forwards compatible behavior</term> if its
                     <termref def="dt-effective-version">effective version</termref> is greater than
                     <phrase diff="chg" at="2023-02-24">4.0</phrase>.</termdef>
            </p><p>These rules do not apply to the <code nobreak="false">version</code> attribute of the
                  <elcode>xsl:output</elcode> element, which has an entirely different purpose: it
               is used to define the version of the output method to be used for serialization.</p><p>When an element is processed with forwards compatible behavior:</p><ulist><item><p>If the element is in the XSLT namespace and appears as a child of the
                        <elcode>xsl:stylesheet</elcode> element, and XSLT 4.0 does not allow the element 
                        to appear as a child of the
                        <elcode>xsl:stylesheet</elcode> element, then the element and its content
                        <rfc2119>must</rfc2119> be ignored.</p></item><item><p>If the element has an attribute that XSLT 4.0 does not allow the element to have, then the attribute
                        <rfc2119>must</rfc2119> be ignored.</p></item><item><p>If the element is in the XSLT namespace and appears as a child of an element 
                     whose content model requires a
                     <termref def="dt-sequence-constructor">sequence constructor</termref>, and XSLT
                     <phrase diff="chg" at="2023-02-24">4.0</phrase> does not allow such elements to
                     appear as part of a sequence constructor, then:</p><olist><item><p>If the element has one or more <elcode>xsl:fallback</elcode> children,
                           then no error is raised either statically or dynamically, and the
                           result of evaluating the instruction is the concatenation of the
                           sequences formed by evaluating the sequence constructors within its
                              <elcode>xsl:fallback</elcode> children, in document order. Siblings of
                           the <elcode>xsl:fallback</elcode> elements are ignored, even if they are
                           valid XSLT 4.0 instructions.</p></item><item><p>If the element has no <elcode>xsl:fallback</elcode> children, then a
                           static error is raised in the same way as if forwards compatible
                           behavior were not enabled.</p></item></olist></item></ulist><example><head>Forwards Compatible Behavior</head><p>For example, an XSLT 4.0
                  <termref def="dt-processor">processor</termref> will process the following
                  stylesheet without error, although the stylesheet includes elements from the
                     <termref def="dt-xslt-namespace">XSLT namespace</termref> that are not defined
                  in this specification:</p><eg xml:space="preserve" role="xml">&lt;xsl:stylesheet version="17.0"
                xmlns:xsl="http://www.w3.org/1999/XSL/Transform"&gt;
  &lt;xsl:template match="/"&gt;
    &lt;xsl:exciting-new-17.0-feature&gt;
      &lt;xsl:fly-to-the-moon/&gt;
      &lt;xsl:fallback&gt;
        &lt;html&gt;
          &lt;head&gt;
            &lt;title&gt;XSLT 17.0 required&lt;/title&gt;
          &lt;/head&gt;
          &lt;body&gt;
            &lt;p&gt;Sorry, this stylesheet requires XSLT 17.0.&lt;/p&gt;
          &lt;/body&gt;
        &lt;/html&gt;
      &lt;/xsl:fallback&gt;
    &lt;/xsl:exciting-new-17.0-feature&gt;
  &lt;/xsl:template&gt;
&lt;/xsl:stylesheet&gt;</eg></example><note><p>If a stylesheet depends crucially on a <termref def="dt-declaration">declaration</termref> 
                  introduced by a version of XSLT after <phrase diff="chg" at="2023-02-24">4.0</phrase>, then the stylesheet can use an
                     <elcode>xsl:message</elcode> element with <code nobreak="false">terminate="yes"</code> (see
                     <specref ref="message"/>) to ensure that implementations that conform to an
                  earlier version of XSLT will not silently ignore the <termref def="dt-declaration">declaration</termref>.</p></note><example><head>Testing the XSLT Version</head><p>For example,</p><eg xml:space="preserve" role="xml">&lt;xsl:stylesheet version="18.0"
                xmlns:xsl="http://www.w3.org/1999/XSL/Transform"&gt;

  &lt;xsl:important-new-17.0-declaration/&gt;

  &lt;xsl:template match="/"&gt;
    &lt;xsl:choose&gt;
      &lt;xsl:when test="number(system-property('xsl:version')) lt 17.0"&gt;
        &lt;xsl:message terminate="yes"&gt;
          &lt;xsl:text&gt;Sorry, this stylesheet requires XSLT 17.0.&lt;/xsl:text&gt;
        &lt;/xsl:message&gt;
      &lt;/xsl:when&gt;
      &lt;xsl:otherwise&gt;
        ...
      &lt;/xsl:otherwise&gt;
    &lt;/xsl:choose&gt;
  &lt;/xsl:template&gt;
  ...
&lt;/xsl:stylesheet&gt;</eg></example><note><p>The XSLT 1.0 and XSLT 2.0 specifications did not anticipate the
                  introduction of the <elcode>xsl:package</elcode> element. An XSLT 1.0 or 2.0
                  processor encountering this element will raise a static error, regardless of the
                     <code nobreak="false">version</code> setting.</p><p>This problem can be circumvented by using the simplified package
                  syntax (whereby an
                        <elcode>xsl:stylesheet</elcode> element is implicitly treated as
                        <elcode>xsl:package</elcode>), or by writing the stylesheet code in
                  a separate module from the package manifest, and using the separate module as the
                  version of the stylesheet that is presented to a 2.0 processor.</p></note><p diff="add" at="issue649">For an XSLT 4.0 processor, the <termref def="dt-effective-version"/> of an 
               <elcode>xsl:fallback</elcode> element that has no explicit <code nobreak="false">version</code> attribute 
               is 4.0: more generally, it is the version of XSLT supported by the processor.
               This rule is designed to ensure that the <elcode>xsl:fallback</elcode> element
               itself is not processed with <termref def="dt-forwards-compatible-behavior"/>,
            which would be pointless since the whole purpose of the instruction is to provide
            code that can be evaluated with an earlier version of XSLT.</p><note diff="add" at="issue649"><p>This rule was not present in earlier versions of this specification.
               On a strict reading of the XSLT 3.0 specification, for example, an <elcode>xsl:fallback</elcode>
               instruction with no <code nobreak="false">version</code> attribute is evaluated with forwards compatible
               behavior. This means, for example, that if the stylesheet author writes
               <code nobreak="false">&lt;xsl:fallback select="42"/&gt;</code> (which is incorrect, because
               the instruction does not define a <code nobreak="false">select</code> attribute) then the <code nobreak="false">select</code>
               attribute will simply be ignored.</p><p>Stylesheet authors can prevent this problem by adding an explicit
               <code nobreak="false">version</code> attribute to <code nobreak="false">xsl:fallback</code> indicating the version
               of XSLT that is needed to evaluate the fallback code.</p><p>This specification cannot retrospectively dictate what XSLT 3.0 (or earlier)
               processors should do; however, developers of such processors are encouraged to adopt
               this rule, so that in an XSLT 4.0 stylesheet, an <elcode>xsl:fallback</elcode> instruction 
               that cannot be properly evaluated by an XSLT 3.0 processor is rejected rather than 
               being silently ignored.</p></note></div2><div2 id="combining-modules"><head>Combining Stylesheet Modules</head><p>XSLT provides two mechanisms to construct a <termref def="dt-package">package</termref> from multiple <termref def="dt-stylesheet-module">stylesheet modules</termref>:</p><ulist><item><p>an inclusion mechanism that allows stylesheet modules to be combined without
                     changing the semantics of the modules being combined, and</p></item><item><p>an import mechanism that allows stylesheet modules to override each other.</p></item></ulist><div3 id="locating-modules"><head>Locating Stylesheet Modules</head><p>The include and import mechanisms use two declarations,
                     <elcode>xsl:include</elcode> and <elcode>xsl:import</elcode>, which are defined
                  in the sections that follow.</p><p>These declarations use an <code nobreak="false">href</code> attribute, whose value is a <termref def="dt-uri-reference">URI reference</termref>, to identify the <termref def="dt-stylesheet-module">stylesheet module</termref> to be included or
                  imported. If the value of this attribute is a relative URI reference, it is resolved as described in <specref ref="uri-references"/>.</p><p>After resolving against the base URI, the way in which the URI reference is used
                  to locate a representation of a <termref def="dt-stylesheet-module">stylesheet
                     module</termref>, and the way in which the stylesheet module is constructed
                  from that representation, are <termref def="dt-implementation-defined">implementation-defined</termref>. In particular, it is implementation-defined
                  which URI schemes are supported, whether fragment identifiers are supported, and
                  what media types are supported. Conventionally, the URI is a reference to a
                  resource containing the stylesheet module as a source XML document, or it may
                  include a fragment identifier that selects an embedded stylesheet module within a
                  source XML document; but the implementation is free to use other mechanisms to
                  locate the stylesheet module identified by the URI reference.</p><imp-def-feature id="idf-api-moduleuri"> It is implementation-defined what forms of
                  URI reference are acceptable in the <code nobreak="false">href</code> attribute of the
                     <elcode>xsl:include</elcode> and <elcode>xsl:import</elcode> elements, for
                  example, the URI schemes that may be used, the forms of fragment identifier that
                  may be used, and the media types that are supported. The way in which the URI
                  reference is used to locate a representation of a <termref def="dt-stylesheet-module">stylesheet module</termref>, and the way in which
                  the stylesheet module is constructed from that representation, are also
                  implementation-defined.</imp-def-feature><p>The referenced <termref def="dt-stylesheet-module">stylesheet module</termref>
                  <rfc2119>must</rfc2119> be either a <termref def="dt-standard-stylesheet-module"/>
                  or a <termref def="dt-simplified-stylesheet-module"/>. It <rfc2119>must
                     not</rfc2119> be a <termref def="dt-package-manifest"/>. If it is a simplified
                  stylesheet module then it is transformed into the equivalent standard stylesheet
                  module by applying the transformation described in <specref ref="simplified-stylesheet"/>. </p><p>Implementations <rfc2119>may</rfc2119> choose to accept URI references containing
                  a fragment identifier defined by reference to the XPointer specification (see
                     <bibref ref="xptr-framework"/>). Note that if the implementation does not
                  support the use of fragment identifiers in the URI reference, then it will not be
                  possible to include an <termref def="dt-embedded-stylesheet-module">embedded
                     stylesheet module</termref>.</p><p>
                  <error spec="XT" type="static" class="SE" code="0165"><p>It is a <termref def="dt-static-error">static error</termref> if the
                        processor is not able to retrieve the resource identified by the URI
                           reference<error.extra> in the <code nobreak="false">href</code> attribute of
                              <elcode>xsl:include</elcode> or <elcode>xsl:import</elcode>
                        </error.extra>, or if the resource that is retrieved does not contain a
                        stylesheet module.</p></error>
               </p><note><p> It is appropriate to use this error code when
                     the resource cannot be retrieved, or when the retrieved resource is not well
                     formed XML. If the resource contains XML that can be parsed but that violates
                     the rules for stylesheet modules, then a more specific error code may be more
                     appropriate.</p></note></div3><div3 id="include"><head>Stylesheet Inclusion</head><changes><change issue="1449" PR="1454" date="2024-09-17">
                     Duplicate <elcode>xsl:include</elcode> declarations within a stylesheet level are
                     now ignored, preventing spurious errors caused by the presence of duplicate named components.
                  </change></changes><e:element-syntax xmlns:e="http://www.w3.org/1999/XSL/Spec/ElementSyntax" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" name="include">
      <e:in-category name="declaration"/>
      <e:attribute name="href" required="yes">
         <e:data-type name="uri"/>
      </e:attribute>
      <e:empty/>
      <e:allowed-parents>
         <e:parent name="package"/>
         <e:parent name="stylesheet"/>
         <e:parent name="transform"/>
      </e:allowed-parents>
   </e:element-syntax><p>A stylesheet module may include another stylesheet module using an
                     <elcode>xsl:include</elcode> declaration.</p><p>The <elcode>xsl:include</elcode> declaration has a <rfc2119>required</rfc2119>
                  <code nobreak="false">href</code> attribute whose value is a URI reference identifying the
                  stylesheet module to be included. This attribute is used as described in <specref ref="locating-modules"/>.</p><p>
                  <error spec="XT" type="static" class="SE" code="0170"><p>An <elcode>xsl:include</elcode> element <rfc2119>must</rfc2119> be a
                           <termref def="dt-top-level">top-level</termref> element.</p></error>
               </p><p>
                  <termdef id="dt-stylesheet-level" term="stylesheet level">A <term>stylesheet
                        level</term> is a collection of <termref def="dt-stylesheet-module">stylesheet modules</termref> connected using <elcode>xsl:include</elcode>
                     declarations: specifically, two stylesheet modules <var>A</var> and
                        <var>B</var> are part of the same stylesheet level if one of them includes
                     the other by means of an <elcode>xsl:include</elcode> declaration, or if there
                     is a third stylesheet module <var>C</var> that is in the same stylesheet level
                     as both <var>A</var> and <var>B</var>.</termdef>
               </p><note><p>A stylesheet level thus groups the <termref def="dt-declaration">declarations</termref> 
                     in a <termref def="dt-package"/> by <termref def="dt-import-precedence"/>:
                  two declarations within a package are in the same stylesheet level if and only if they
                  have the same import precedence.</p></note><p>
                  <termdef id="dt-declaration-order" term="declaration order">The <termref def="dt-declaration">declarations</termref> within a <termref def="dt-stylesheet-level">stylesheet level</termref> have a total ordering
                     known as <term>declaration order</term>. The order of declarations within a
                     stylesheet level is the same as the document order that would result if each
                     stylesheet module were inserted textually in place of the
                        <elcode>xsl:include</elcode> element that references it.</termdef> In other
                  respects, however, the effect of <elcode>xsl:include</elcode> is not equivalent to
                  the effect that would be obtained by textual inclusion.</p><p>If two or more <elcode>xsl:include</elcode> declarations within the same <termref def="dt-stylesheet-level"/>
               reference the same absolute URI, or reference different absolute URIs that are known to refer
               to the same resource, then the duplicate <elcode>xsl:include</elcode> declarations, other than the
               first in <termref def="dt-declaration-order"/>, are ignored. Similarly, an <elcode>xsl:include</elcode>
               declaration that references the top-level stylesheet module within its stylesheet level is ignored.</p><note><p>The above rule is new in XSLT 4.0. It can prevent the unwanted errors that can
                  occur when assembling a stylesheet from multiple modules, where each module declares its
                  dependencies using potentially redundant, and potentially circular <elcode>xsl:include</elcode> 
                  declarations.</p><p>In XSLT 3.0 and earlier versions, including the same module more than once would usually
                  lead to errors caused by duplicate definitions of components such as global variables, named
                  templates, or functions. In the rare case where the included module only contains template rules, the
                  new rule could potentially cause a backwards incompatibility. However, it is very unlikely
                  that a stylesheet author would do this intentionally.</p><p>The new rule does not apply when multiple <elcode>xsl:include</elcode> declarations for the
                  same module appear in different <termref def="dt-stylesheet-level">stylesheet levels</termref>,
                  that is, at different <termref def="dt-import-precedence">import precedences</termref>.</p></note></div3><div3 id="import"><head>Stylesheet Import</head><e:element-syntax xmlns:e="http://www.w3.org/1999/XSL/Spec/ElementSyntax" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" name="import">
      <e:in-category name="declaration"/>
      <e:attribute name="href" required="yes">
         <e:data-type name="uri"/>
      </e:attribute>
      <e:empty/>
      <e:allowed-parents>
         <e:parent name="package"/>
         <e:parent name="stylesheet"/>
         <e:parent name="transform"/>
      </e:allowed-parents>
   </e:element-syntax><p>A stylesheet module may import another <termref def="dt-stylesheet-module">stylesheet module</termref> using an <elcode>xsl:import</elcode>
                  <termref def="dt-declaration">declaration</termref>. Importing a stylesheet module
                  is the same as including it (see <specref ref="include"/>) except that <termref def="dt-template-rule">template rules</termref> and other <termref def="dt-declaration">declarations</termref> in the importing module take
                  precedence over template rules and declarations in the imported module; this is
                  described in more detail below.</p><p>The <elcode>xsl:import</elcode> declaration has a <rfc2119>required</rfc2119>
                  <code nobreak="false">href</code> attribute whose value is a URI reference identifying the
                  stylesheet module to be included. This attribute is used as described in <specref ref="locating-modules"/>.</p><p>
                  <error spec="XT" type="static" class="SE" code="0190"><p>An <elcode>xsl:import</elcode> element <rfc2119>must</rfc2119> be a <termref def="dt-top-level">top-level</termref> element.</p></error>
               </p><example><head>Using <elcode>xsl:import</elcode>
                  </head><p>For example,</p><eg xml:space="preserve" role="xslt-document">&lt;xsl:stylesheet version="3.0"
                xmlns:xsl="http://www.w3.org/1999/XSL/Transform"&gt;
  &lt;xsl:import href="article.xsl"/&gt;
  &lt;xsl:import href="bigfont.xsl"/&gt;
  &lt;xsl:attribute-set name="note-style"&gt;
    &lt;xsl:attribute name="font-style"&gt;italic&lt;/xsl:attribute&gt;
  &lt;/xsl:attribute-set&gt;
&lt;/xsl:stylesheet&gt;</eg></example><p>
                  <termdef id="dt-import-tree" term="import tree">The <termref def="dt-stylesheet-level">stylesheet levels</termref> making up a <termref def="dt-stylesheet">stylesheet</termref> are treated as forming an
                        <term>import tree</term>. In the import tree, each stylesheet level has one
                     child for each <elcode>xsl:import</elcode> declaration that it
                     contains.</termdef> The ordering of the children is the <termref def="dt-declaration-order">declaration order</termref> of the
                     <elcode>xsl:import</elcode> declarations within their stylesheet level.</p><p>
                  <termdef id="dt-import-precedence" term="import precedence">A <termref def="dt-declaration">declaration</termref>
                     <var>D</var> in the stylesheet is defined to have lower <term>import
                        precedence</term> than another declaration <var>E</var> if the stylesheet
                     level containing <var>D</var> would be visited before the stylesheet level
                     containing <var>E</var> in a post-order traversal of the import tree (that is,
                     a traversal of the import tree in which a stylesheet level is visited after its
                     children). Two declarations within the same stylesheet level have the same
                     import precedence.</termdef>
               </p><p>For example, suppose</p><ulist><item><p>stylesheet module <var>A</var> imports stylesheet modules <var>B</var> and
                           <var>C</var> in that order;</p></item><item><p>stylesheet module <var>B</var> imports stylesheet module <var>D</var>;</p></item><item><p>stylesheet module <var>C</var> imports stylesheet module <var>E</var>.</p></item></ulist><p>Then the import tree has the following structure:</p><ulist role="type-hierarchy type-colors"><item role="primitive special root"><p role="root" id="th_anyAtomicType">
                        <phrase>A</phrase>
                     </p><ulist><item role="primitive"><p role="first">
                              <phrase>B</phrase>
                           </p><ulist><item role="atomic"><p role="first">
                                    <phrase>D</phrase>
                                 </p></item></ulist></item><item role="primitive"><p role="item">
                              <phrase>C</phrase>
                           </p><ulist><item role="atomic"><p role="first">
                                    <phrase>E</phrase>
                                 </p></item></ulist></item></ulist></item></ulist><p>The order of import precedence (lowest first) is <var>D</var>, <var>B</var>,
                     <var>E</var>, <var>C</var>, <var>A</var>.</p><p>In general, a <termref def="dt-declaration">declaration</termref> with higher
                  import precedence takes precedence over a declaration with lower import
                  precedence. This is defined in detail for each kind of declaration.</p><p>
                  <error spec="XT" type="static" class="SE" code="0210"><p>It is a <termref def="dt-static-error">static error</termref> if a
                        stylesheet module directly or indirectly references itself via a chain
                        of <elcode>xsl:include</elcode> and <elcode>xsl:import</elcode>
                        declarations that contains at least one <elcode>xsl:import</elcode>.</p></error>                 
               </p><note><p>Under the new XSLT 4.0 rules, a cyclic reference that involves
                     <elcode>xsl:include</elcode> only is ignored. A cycle involving
                     <elcode>xsl:import</elcode> cannot be ignored, because it makes it
                     impossible to determine which declarations have the highest
                     <termref def="dt-import-precedence"/>.</p></note><note><p>The case where a stylesheet module with a particular URI is imported several
                     times is not treated specially. The effect is exactly the same as if several
                     stylesheet modules with different URIs but identical content were imported.
                     This might or might not cause an error, depending on the content of the
                     stylesheet module.</p></note></div3></div2><div2 id="preprocessing"><head>Stylesheet Preprocessing</head><p>This specification provides several features that cause the
               raw stylesheet to be preprocessed as the first stage of static processing:
               <ulist><item diff="add" at="2023-02-16"><p>Whitespace and commentary are stripped (see <specref ref="stylesheet-stripping"/>).</p></item><item><p>Any <elcode>xsl:note</elcode> elements are removed: see <specref ref="xsl-note-elements"/>.</p></item><item><p>Elements
                     may be conditionally included or excluded by means of an <code nobreak="false">[xsl:]use-when</code>
                     attribute as described in <specref ref="conditional-inclusion"/>.</p></item><item><p>Attributes may
                     be conditionally computed as described in <specref ref="shadow-attributes"/>.</p></item></ulist>
            </p><p>Note that many of the rules affecting the validity of
               stylesheet documents apply to a stylesheet after this preprocessing phase has been
               carried out.</p><div3 id="stylesheet-stripping"><head>Stripping Whitespace and Commentary from the Stylesheet</head><p>The tree representing the stylesheet is preprocessed as follows:</p><olist><item><p>All comments and processing instructions are removed.</p></item><item diff="add" at="2023-02-16"><p>All <elcode>xsl:note</elcode> elements are removed, together with their content
                     (see <specref ref="xsl-note-elements"/>).</p></item><item><p>Any text nodes that are now adjacent to each other are merged.</p></item><item><p>Any <termref def="dt-whitespace-text-node">whitespace text node</termref> that
                        satisfies both the following conditions is removed from the tree:</p><ulist><item><p>The parent of the text node is not an <elcode>xsl:text</elcode>
                              element</p></item><item><p>The text node does not have an ancestor element that has an
                              <code nobreak="false">xml:space</code> attribute with a value of
                              <code nobreak="false">preserve</code>, unless there is a closer ancestor element having
                              an <code nobreak="false">xml:space</code> attribute with a value of
                              <code nobreak="false">default</code>.</p></item></ulist></item><item><p>Any <termref def="dt-whitespace-text-node">whitespace text node</termref> whose
                        parent is one of the following elements is removed from the tree, regardless of
                        any <code nobreak="false">xml:space</code> attributes:</p><slist><sitem>
                           
                           <elcode>xsl:accumulator</elcode>
                           
                        </sitem><sitem>
                           <elcode>xsl:analyze-string</elcode>
                        </sitem><sitem>
                           <elcode>xsl:apply-imports</elcode>
                        </sitem><sitem>
                           <elcode>xsl:apply-templates</elcode>
                        </sitem><sitem>
                           <elcode>xsl:attribute-set</elcode>
                        </sitem><sitem>
                           <elcode>xsl:call-template</elcode>
                        </sitem><sitem>
                           <elcode>xsl:character-map</elcode>
                        </sitem><sitem>
                           <elcode>xsl:choose</elcode>
                        </sitem><sitem>
                           
                           <elcode>xsl:evaluate</elcode>
                           
                        </sitem><sitem>
                           
                           <elcode>xsl:fork</elcode>
                           
                        </sitem><sitem>
                           
                           <elcode>xsl:merge</elcode>
                           
                        </sitem><sitem>
                           
                           <elcode>xsl:merge-source</elcode>
                           
                        </sitem><sitem>
                           
                           <elcode>xsl:mode</elcode>
                           
                        </sitem><sitem>
                           
                           <elcode>xsl:next-iteration</elcode>
                           
                        </sitem><sitem>
                           <elcode>xsl:next-match</elcode>
                        </sitem><sitem>
                           
                           <elcode>xsl:override</elcode>
                           
                        </sitem><sitem>
                           
                           <elcode>xsl:package</elcode>
                           
                        </sitem><sitem>
                           <elcode>xsl:stylesheet</elcode>
                        </sitem><sitem>
                           <elcode>xsl:switch</elcode>
                        </sitem><sitem>
                           <elcode>xsl:transform</elcode>
                        </sitem><sitem>
                           
                           <elcode>xsl:use-package</elcode>
                           
                        </sitem></slist></item><item><p>Any <termref def="dt-whitespace-text-node">whitespace text node</termref> whose
                        immediate following-sibling node is an <elcode>xsl:param</elcode> or
                        <elcode>xsl:sort</elcode>
                        or <elcode>xsl:context-item</elcode> or
                        <elcode>xsl:on-completion</elcode> element is removed from the
                        tree, regardless of any <code nobreak="false">xml:space</code> attributes.</p></item><item><p>Any <termref def="dt-whitespace-text-node">whitespace text
                        node</termref> whose immediate preceding-sibling node is an
                        <elcode>xsl:catch</elcode>
                        element is removed from the
                        tree, regardless of any <code nobreak="false">xml:space</code> attributes.</p></item></olist><p>
                  <error spec="XT" type="static" class="SE" code="0260"><p>Within an <termref def="dt-xslt-element">XSLT element</termref> that is
                        <rfc2119>required</rfc2119> to be empty, any content other than comments or
                        processing instructions, including any <termref def="dt-whitespace-text-node">whitespace text node</termref> preserved using the
                        <code nobreak="false">xml:space="preserve"</code> attribute, is a <termref def="dt-static-error">static error</termref>.</p></error>
               </p><note><p>Using <code nobreak="false">xml:space="preserve"</code> in parts of the stylesheet that contain
                     <termref def="dt-sequence-constructor">sequence constructors</termref> will
                     cause whitespace text nodes in that part of the
                     stylesheet to be copied to the result of the sequence constructor.
                     When the result of the sequence constructor is used to form the content of an
                     element, this can cause errors if such text nodes are followed by attribute nodes
                     generated using <elcode>xsl:attribute</elcode>.</p></note><note><p>If an <code nobreak="false">xml:space</code> attribute is specified on a <termref def="dt-literal-result-element">literal result element</termref>, it will be
                     copied to the result tree in the same way as any other attribute.</p></note></div3><div3 id="xsl-note-elements" diff="add" at="2023-02-16"><head>The <code nobreak="false">xsl:note</code> element</head><changes><change issue="109" PR="353" date="2023-04-19">
                     A new element <elcode>xsl:note</elcode> is available for documentation and similar purposes:
                     it can appear anywhere in the stylesheet and is ignored by the XSLT processor.
                  </change></changes><p>An <elcode>xsl:note</elcode> element may appear anywhere in the stylesheet, except as the outermost element.</p><e:element-syntax xmlns:e="http://www.w3.org/1999/XSL/Spec/ElementSyntax" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" name="note">
      <e:attribute name="#any#" required="no">
         <e:data-type name="string"/>
      </e:attribute>
      <e:model name="any"/>
   </e:element-syntax><p>The element may have any attributes and any children, subject only to rules imposed by
                  other specifications such as the XML specification. The XSLT processor discards <elcode>xsl:note</elcode>
                  elements at an early stage of processing, without performing any validation, as described
               in <specref ref="stylesheet-stripping"/>.</p><p>An <elcode>xsl:note</elcode> element is typically used for documentation. The format of this documentation
               is not prescribed here: it might be free text, or XHTML, or some custom vocabulary understood by a free-standing
               documentation generator.</p><p>An <elcode>xsl:note</elcode> element might also be used for “commenting out” XSLT declarations or instructions.</p><note><p>A number of documentation processors have been produced for use with XSLT, and the general convention has
                     been to use <termref def="dt-data-element">user-defined data elements</termref> for this purpose. This
                     approach has its drawbacks:</p><ulist><item><p>Annotations can only appear at the top level of the stylesheet (between declarations, but not
                     within declarations). <termref def="dt-extension-instruction">Extension instructions</termref>
                     can also potentially be used as annotations, but this abuses their intended purpose and may create an unwanted 
                     dependency on a specific processor.</p></item><item><p>Annotations require a custom namespace to be declared, typically on the <elcode>xsl:stylesheet</elcode>
                     element, and this namespace becomes part of the static context for all expressions within the stylesheet,
                     thus changing (if only very slightly) the semantics of the stylesheet code. This is true even
                     if the namespace is excluded from the result tree by means of an <code nobreak="false">[xsl:]exclude-result-prefixes</code>
                        attribute.</p></item></ulist></note><p>Implementations <rfc2119>must not</rfc2119> interpret the contents of an <elcode>xsl:note</elcode> element
               to modify the behavior of the stylesheet in any way, whether or not the resulting behavior remains conformant
               with this specification.</p><note><p>For example, <elcode>xsl:note</elcode> elements must not be used to provide processor-specific performance
                     hints. There are better mechanisms for this, such as <termref def="dt-data-element">user-defined data elements</termref>
                  and <termref def="dt-extension-attribute">extension attributes</termref>.</p></note></div3><div3 id="conditional-inclusion"><head>Conditional Element Inclusion</head><p>Any element in the XSLT namespace may have a <code nobreak="false">use-when</code> attribute whose
                  value is an XPath expression that can be evaluated statically. 
                  A <termref def="dt-literal-result-element">literal result element</termref>, or
                  any other element within a <termref def="dt-stylesheet-module">stylesheet
                     module</termref> that is not in the XSLT namespace, may similarly carry an
                  <code nobreak="false">xsl:use-when</code> attribute.      
                  If the attribute is
                  present and the <xtermref spec="XP40" ref="dt-ebv">effective boolean
                     value</xtermref> of the expression is <code nobreak="false">false</code>, then the element, together with
                  all the nodes having that element as an ancestor, is effectively excluded from the
                     <termref def="dt-stylesheet-module">stylesheet module</termref>. When a node is
                  effectively excluded from a stylesheet module the stylesheet module has the same
                  effect as if the node were not there. Among other things this means that no static
                  or dynamic errors will be raised in respect of the element and its contents,
                  other than errors in the <code nobreak="false">use-when</code> attribute itself.</p><note><p>This does not apply to XML parsing or validation errors, which will be raised
                     in the usual way. It also does not apply to attributes that are necessarily
                     processed before <code nobreak="false">[xsl:]use-when</code>, examples being
                        <code nobreak="false">xml:space</code> and <code nobreak="false">[xsl:]xpath-default-namespace</code>.</p></note><p>If the <elcode>xsl:package</elcode>, 
               <elcode>xsl:stylesheet</elcode> or <elcode>xsl:transform</elcode> element
                  itself is effectively excluded, the effect is to exclude all the children of the
                     <elcode>xsl:stylesheet</elcode> or <elcode>xsl:transform</elcode> element, but
                  not the <elcode>xsl:stylesheet</elcode> or <elcode>xsl:transform</elcode> element
                  or its attributes.</p><note><p>This allows all the declarations that depend on the same condition to be
                     included in one stylesheet module, and for their inclusion or exclusion to be
                     controlled by a single <code nobreak="false">use-when</code> attribute at the level of the
                     module.</p></note><p>Conditional element exclusion happens after stripping of whitespace text nodes
                  from the stylesheet, as described in <specref ref="stylesheet-stripping"/>.</p><p>The XPath expression used as the value of the
                     <code nobreak="false">xsl:use-when</code> attribute follows the rules for <termref def="dt-static-expression">static expressions</termref>, including the rules for handling errors.</p><p>The use of <code nobreak="false">[xsl:]use-when</code> is illustrated in the following
                  examples.</p><example><head>Using Conditional Exclusion to Achieve Portability</head><p>This example demonstrates the use of the <code nobreak="false">use-when</code> attribute to
                     achieve portability of a stylesheet across schema-aware and non-schema-aware
                     processors.</p><eg xml:space="preserve" role="xslt-declarations">&lt;xsl:import-schema schema-location="http://example.com/schema"
              use-when="system-property('xsl:is-schema-aware')='yes'"/&gt;

&lt;xsl:template match="/" 
              use-when="system-property('xsl:is-schema-aware')='yes'" 
              priority="2"&gt;
  &lt;xsl:result-document validation="strict"&gt;
    &lt;xsl:apply-templates/&gt;
  &lt;/xsl:result-document&gt;
&lt;/xsl:template&gt;

&lt;xsl:template match="/"&gt;
  &lt;xsl:apply-templates/&gt;
&lt;/xsl:template&gt;</eg><p>The effect of these declarations is that a non-schema-aware processor ignores
                     the <elcode>xsl:import-schema</elcode> declaration and the first template rule,
                     and therefore raises no errors in respect of the schema-related constructs
                     in these declarations.</p></example><example><head>Including Variant Stylesheet Modules</head><p>This example includes different stylesheet modules depending on which XSLT
                     processor is in use.</p><eg xml:space="preserve" role="xslt-declarations">&lt;xsl:include href="module-A.xsl" 
     use-when="system-property('xsl:vendor')='vendor-A'"/&gt;
&lt;xsl:include href="module-B.xsl" 
     use-when="system-property('xsl:vendor')='vendor-B'"/&gt;</eg></example></div3><div3 id="shadow-attributes"><head>Shadow Attributes</head><p>When a no-namespace attribute name <var>N</var> is permitted to appear on an element
                  in the <termref def="dt-xslt-namespace"/> (provided that <var>N</var> does not start with an underscore), 
                  then a value <var>V</var> can be supplied for <var>N</var> in one of two ways:
               </p><ulist><item><p>The conventional way is for an attribute node with name <var>N</var> and value <var>V</var> to appear 
                     in the XDM representation of the element node in the stylesheet tree.
                  </p></item><item><p>As an alternative, a shadow attribute may be supplied allowing the value <var>V</var> 
                     to be statically computed during the preprocessing phase. The shadow attribute has a name 
                     that is the same as the name <var>N</var> prefixed with an underscore, and the value of 
                     the shadow attribute is a <termref def="dt-value-template"/> in which all expressions enclosed between 
                     curly braces must be <termref def="dt-static-expression">static
                        expressions</termref>. The value <var>V</var> is the result of 
                     evaluating the value template. If a shadow attribute is present, then any attribute node with name
                     <var>N</var> (sharing the same parent element) is ignored.
                  </p></item></ulist><p>For example, an <elcode>xsl:include</elcode> element might be written:</p><eg role="xslt-declaration" xml:space="preserve">&lt;xsl:include _href="common{ $VERSION }.xsl"/&gt;</eg><p>allowing the stylesheet to include a specific version of a library module based on
                  the value of a <termref def="dt-static-parameter"/>.</p><p>Similarly, a <termref def="dt-mode"/> might be declared like this:</p><eg role="xslt-declaration" xml:space="preserve">&lt;xsl:param name="streamable" as="xs:boolean" 
                  required="yes" static="yes"/&gt;
&lt;xsl:mode _streamable="{ $streamable }" on-no-match="shallow-skip"/&gt;</eg><p>this allowing the streamability of the mode to be controlled using a <termref def="dt-static-parameter"/>
                  (Note: this example relies on the fact that the
                        <code nobreak="false">streamable</code> attribute accepts a boolean value, which means that
                     the values <code nobreak="false">true</code> and <code nobreak="false">false</code> are accepted as synonyms of
                        <code nobreak="false">yes</code> and <code nobreak="false">no</code>).</p><p>This mechanism applies to all attributes in the stylesheet where the attribute
                  name is in no namespace and the name of the parent element is in the <termref def="dt-xslt-namespace"/>. This includes attributes that have static
                  significance such as the <code nobreak="false">use-when</code> attribute, the <code nobreak="false">version</code>
                  attribute, and the <code nobreak="false">static</code> attribute on <elcode>xsl:variable</elcode>.
                  The mechanism does not apply to shadow attributes (that is, it is not possible to
                  invoke two stages of preprocessing by using two leading underscores). It does not
                  apply to attributes of literal result elements, nor to attributes in a namespace
                  such as the XML or XSLT namespace, nor to namespace declarations.</p><note><p>If a shadow attribute and its corresponding target attribute are both present in
                     the stylesheet, the non-shadow attribute is ignored.
                     This may be useful to make stylesheet code compatible across XSLT versions; an
                     XSLT 2.0 processor operating in forwards compatible mode will ignore shadow
                     attributes, and will require the target attribute to be valid.</p></note><note><p>The statement that the non-shadow attribute is
                     ignored extends to error detection: it is not an error if the non-shadow
                     attribute has an invalid value. However, this is not reflected in the schema
                     for XSLT stylesheets, so validation using this schema may raise errors in such
                     cases.</p></note><note><p>An attribute whose name begins with an underscore is
                  treated specially only when it appears on an element in the XSLT namespace. On a 
                  <termref def="dt-literal-result-element"/>, it is treated in the same way as any other attribute (that is,
                     its <termref def="dt-effective-value"/> is copied to the result tree). On an
                     <termref def="dt-extension-instruction"/> or
                  <termref def="dt-data-element"/>, as with other attributes
                  on these elements, its meaning is entirely <termref def="dt-implementation-defined"/>.</p></note><example><head>Using Shadow Attributes to Parameterize XPath Default Namespace</head><p>Although it is not usually considered good practice, it sometimes happens that
                     variants or versions of an XML vocabulary exist in which the same local names
                     are used, but in different namespaces. There is then a requirement to write
                     code that will process source documents in a variety of different
                     namespaces.</p><p>It is possible to define a static stylesheet parameter containing the target
                     namespace, for example:</p><eg role="xslt-declaration" xml:space="preserve">&lt;xsl:param name="NS" as="xs:string" static="yes" 
                          select="'http://example.com/ns/one'"/&gt;</eg><p>And this can then be used to set the default namespace for XPath
                     expressions:</p><eg role="non-xml" xml:space="preserve">_xpath-default-namespace="{ $NS }"</eg><p>However, it is not possible to put this shadow attribute on the
                        <elcode>xsl:stylesheet</elcode> or <elcode>xsl:package</elcode> element of
                     the principal stylesheet module, because at that point the variable
                        <code nobreak="false">$NS</code> is not in scope. A workaround is to create a stub
                     stylesheet module which contains nothing but the static parameter declaration
                     and an <elcode>xsl:include</elcode> of the stylesheet module containing the
                     real logic. The static stylesheet parameter will then be in scope on the
                        <elcode>xsl:stylesheet</elcode> element of the included stylesheet module,
                     and the shadow attribute <code nobreak="false">_xpath-default-namespace="{ $NS }"</code> can
                     therefore appear on this <elcode>xsl:stylesheet</elcode> element.</p></example><example><head>Using Shadow Attributes to Parameterize Selection of Elements</head><p>The following stylesheet produces a report giving information about selected
                     employees. The predicate defining which employees are to be included in the
                     report is supplied (as a string containing an XPath expression) in a static
                     stylesheet parameter:</p><eg role="xslt-declaration xmlns:local='local'" xml:space="preserve">
&lt;xsl:param name="filter" static="yes"
           as="xs:string" select="'true()'"/&gt;
&lt;xsl:function name="local:filter" as="xs:boolean"&gt;
   &lt;xsl:param name="e" as="element(employee)"/&gt;
   &lt;xsl:sequence _select="$e/({ $filter })"/&gt;
&lt;/xsl:function&gt;
&lt;xsl:template match="/"&gt;
   &lt;report&gt;
      &lt;xsl:apply-templates mode="report" select="//employee[local:filter(.)]"/&gt;
   &lt;/report&gt;
&lt;/xsl:template&gt;</eg><p>If the supplied value of the filter parameter is, say <code nobreak="false">location =
                        "UK"</code>, then the report will cover employees based in the UK.</p><note><p>The stylesheet function <code nobreak="false">local:filter</code> is used here in preference
                        to direct use of the supplied predicate within the <code nobreak="false">select</code>
                        attribute of the <elcode>xsl:apply-templates</elcode> instruction because it
                        reduces exposure to code injection attacks. It does not necessarily
                        eliminate all such risks, however. For example, it would be possible for a
                        caller to supply an expression that never terminates, thus creating a
                        denial-of-service risk.</p></note></example></div3></div2><div2 id="built-in-types"><head>Built-in Types</head><p>Every XSLT 4.0 processor includes the following
               named type definitions in the <termref def="dt-in-scope-schema-component">in-scope
                  schema components</termref>:</p><ulist><item><p>
                     All built-in types defined in <bibref ref="xmlschema-2"/>, including <code nobreak="false">xs:anyType</code> and
                           <code nobreak="false">xs:anySimpleType</code>.</p></item><item><p>The following types defined in <bibref ref="xpath-40"/>:
                        <code nobreak="false">xs:yearMonthDuration</code>, <code nobreak="false">xs:dayTimeDuration</code>,
                        <code nobreak="false">xs:anyAtomicType</code>, <code nobreak="false">xs:untyped</code>, and
                        <code nobreak="false">xs:untypedAtomic</code>.</p></item></ulist><p>XSLT 4.0 processors <rfc2119>may</rfc2119> optionally include types
               defined in XSD 1.1 (see <bibref ref="xmlschema11-1"/>). XSD 1.1 adopts the types
                  <code nobreak="false">xs:yearMonthDuration</code>, <code nobreak="false">xs:dayTimeDuration</code>, and
                  <code nobreak="false">xs:anyAtomicType</code> previously defined in XPath 2.0, and adds one new
               type: <code nobreak="false">xs:dateTimeStamp</code>. XSD 1.1 also allows implementers to define
               additional primitive types, and XSLT 4.0 permits such types to be supported by an
               XSLT processor.</p><p>A <termref def="dt-schema-aware-xslt-processor">schema-aware XSLT processor</termref>
               additionally supports:</p><ulist><item><p>User-defined types, and element and attribute declarations, that are imported
                     using an <elcode>xsl:import-schema</elcode> declaration as described in
                        <specref ref="import-schema"/>. These may include both simple and complex
                     types.</p></item></ulist><note><p>The names that are imported from the XML Schema namespace do not include all the
                  names of top-level types defined in either the Schema for Schema Documents or the
                  Schema for Schema Documents (Datatypes). The Schema for Schema Documents, as well
                  as defining built-in types such as <code nobreak="false">xs:integer</code> and
                     <code nobreak="false">xs:double</code>, also defines types that are intended for use only
                  within that schema, such as <code nobreak="false">xs:derivationControl</code>. A <termref def="dt-stylesheet">stylesheet</termref> that is designed to process XML Schema
                  documents as its input or output may import the Schema for Schema Documents.</p></note><p>An implementation may define mechanisms that allow additional <termref def="dt-schema-component">schema components</termref> to be added to the <termref def="dt-in-scope-schema-component">in-scope schema components</termref> for the
               stylesheet. For example, the mechanisms used to define <termref def="dt-extension-function">extension functions</termref> (see <specref ref="extension-functions"/>) may also be used to import the types used in the
               interface to such functions.</p><imp-def-feature id="idf-ext-importtypes">An implementation may define mechanisms, above
               and beyond <elcode>xsl:import-schema</elcode>, that allow <termref def="dt-schema-component">schema components</termref> such as type definitions to
               be made available within a stylesheet.</imp-def-feature><p>These <termref def="dt-schema-component">schema components</termref> are the only
               ones that may be referenced in XPath expressions within the stylesheet, or in the
                  <code nobreak="false">[xsl:]type</code> and <code nobreak="false">as</code> attributes of those elements that
               permit these attributes.</p></div2><div2 id="import-schema"><head>Importing Schema Components</head><changes><change issue="451" PR="635" date="2023-10-24">
                  The rules concerning the compatibility of schemas imported by different packages have 
                  been clarified. It is now explicitly stated that instructions that trigger validation 
                  must use the imported schema of the package in which validation is invoked. 
                  This differs from the current practice of some XSLT 3.0 processors, which may 
                  use (for example) a schema formed from the union of the imported schemas in all 
                  packages.
               </change><change issue="451" PR="1819" date="2025-02-18">
                  Different parts of a stylesheet may now use different imported schemas.
               </change></changes><note><p>The facilities described in this section are not available with a <termref def="dt-basic-xslt-processor">basic XSLT processor</termref>. They require a
                     <termref def="dt-schema-aware-xslt-processor">schema-aware XSLT
                     processor</termref>, as described in <specref ref="conformance"/>.</p></note><e:element-syntax xmlns:e="http://www.w3.org/1999/XSL/Spec/ElementSyntax" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" name="import-schema">
      <e:in-category name="declaration"/>
      <e:attribute name="role">
         <e:data-type name="ncname"/>
      </e:attribute>
      <e:attribute name="namespace">
         <e:data-type name="uri"/>
      </e:attribute>
      <e:attribute name="schema-location">
         <e:data-type name="uri"/>
      </e:attribute>
      <e:element repeat="zero-or-one" name="xs:schema"/>
      <e:allowed-parents>
         <e:parent name="package"/>
         <e:parent name="stylesheet"/>
         <e:parent name="transform"/>
      </e:allowed-parents>
   </e:element-syntax><p>The <elcode>xsl:import-schema</elcode> declaration is used to identify <termref def="dt-schema-component">schema components</termref> (that is, top-level type
               definitions and top-level element and attribute declarations) that need to be
               available statically, that is, before any source document is available. Names of such
               components used statically within the <termref def="dt-stylesheet">stylesheet</termref> must refer to an <termref def="dt-in-scope-schema-component">in-scope schema component</termref>, which means they must either be built-in
               types as defined in <specref ref="built-in-types"/>, or they must be imported using
               an <elcode>xsl:import-schema</elcode> declaration.</p><p>The <elcode>xsl:import-schema</elcode> declaration identifies a namespace containing
               the names of the components to be imported (or indicates that components whose names
               are in no namespace are to be imported). The effect is that the names of top-level
               element and attribute declarations and type definitions from this namespace (or
               non-namespace) become available for use within XPath expressions in the <termref def="dt-package">package</termref>, and within
               other stylesheet constructs such as the <code nobreak="false">type</code> and <code nobreak="false">as</code>
               attributes of various <termref def="dt-xslt-element">XSLT elements</termref>.</p><p>If the <code nobreak="false">role</code> attribute is absent,
               the relevant schema components are available in all stylesheet modules
                  within the <termref def="dt-declaring-package">declaring
                     package</termref>, except within subtrees of a stylesheet module
               where a different schema is selected using an <code nobreak="false">[xsl:]schema-role</code>
               attribute. Importing components in one stylesheet module makes
               them available throughout the <termref def="dt-package">package</termref>, subject
               to the constraints imposed by the <code nobreak="false">[xsl:]schema-role</code> attribute.
            </p><p>The schema components imported into different 
               <termref def="dt-package">packages</termref> within a <termref def="dt-stylesheet">stylesheet</termref>
               (regardless of the schema role)
               must be <phrase diff="chg" at="Issue451"><xtermref spec="DM40" ref="dt-schema-compatible">compatible</xtermref></phrase>. 
               Specifically, it is not permitted to use
               the same name in the same XSD symbol space to refer to different schema components
               within different packages; and the union of the schema components imported into the
               packages of a stylesheet must constitute a valid schema (as well as the set of schema
               components imported into each package forming a valid schema in its own right).</p><note><p diff="chg" at="Issue451">The fact that the schemas used in different packages
            must be compatible does not mean they must be identical. There are circumstances
            where validating an element using one schema might produce a different outcome from
            validation with a different schema, despite these consistency rules: an example
            is where the two schemas define different membership for a substitution group.</p><p>Nevertheless, the consistency rules are strong enough to ensure that an element
            node validated using one schema can safely be passed to a function declared in another
            package, where the function declares the required
            type of an argument as (say) <code nobreak="false">element(*, T)</code>.</p></note><p>The <code nobreak="false">namespace</code> and <code nobreak="false">schema-location</code> attributes are both
               optional.</p><p>If the <elcode>xsl:import-schema</elcode> element contains an <code nobreak="false">xs:schema</code>
               element, then the <code nobreak="false">schema-location</code> attribute <rfc2119>must</rfc2119> be
               absent, and one of the following <rfc2119>must</rfc2119> be true:</p><ulist><item><p>the <code nobreak="false">namespace</code> attribute of the <elcode>xsl:import-schema</elcode>
                     element and the <code nobreak="false">targetNamespace</code> attribute of the
                        <code nobreak="false">xs:schema</code> element are both absent (indicating a no-namespace
                     schema), or</p></item><item><p>the <code nobreak="false">namespace</code> attribute of the <elcode>xsl:import-schema</elcode>
                     element and the <code nobreak="false">targetNamespace</code> attribute of the
                        <code nobreak="false">xs:schema</code> element are both present and both have the same
                     value, or</p></item><item><p>the <code nobreak="false">namespace</code> attribute of the <elcode>xsl:import-schema</elcode>
                     element is absent and the <code nobreak="false">targetNamespace</code> attribute of the
                        <code nobreak="false">xs:schema</code> element is present, in which case the target
                     namespace is as given on the <code nobreak="false">xs:schema</code> element.</p></item></ulist><p>
               <error spec="XT" type="static" class="SE" code="0215"><p>It is a <termref def="dt-static-error">static error</termref> if an
                        <elcode>xsl:import-schema</elcode> element that contains an
                        <code nobreak="false">xs:schema</code> element has a <code nobreak="false">schema-location</code> attribute,
                     or if it has a <code nobreak="false">namespace</code> attribute that conflicts with the target
                     namespace of the contained schema.</p></error>
            </p><p>If two <elcode>xsl:import-schema</elcode> declarations with the same effective <code nobreak="false">role</code>
               name specify the same namespace, or
               if both specify no namespace, then only the one with highest <termref def="dt-import-precedence">import precedence</termref> is used. If this leaves
               more than one, then all the declarations at the highest import precedence are used
               (which may cause conflicts, as described below).</p><p>After discarding any <elcode>xsl:import-schema</elcode> declarations under the above
               rule, the effect of the remaining <elcode>xsl:import-schema</elcode> declarations 
               for each distinct schema role is
               defined in terms of a hypothetical document called the synthetic schema document,
               which is constructed as follows. The synthetic schema document defines an arbitrary
               target namespace that is different from any namespace actually used by the
               application, and it contains <code nobreak="false">xs:import</code> elements corresponding
               one-for-one with the <elcode>xsl:import-schema</elcode> declarations 
               with that effective schema role
               in the <termref def="dt-stylesheet">stylesheet</termref>, with the following correspondence:</p><ulist><item><p>The <code nobreak="false">namespace</code> attribute of the <code nobreak="false">xs:import</code> element is
                     copied from the <code nobreak="false">namespace</code> attribute of the
                        <elcode>xsl:import-schema</elcode> declaration if it is explicitly present,
                     or is implied by the <code nobreak="false">targetNamespace</code> attribute of a contained
                        <code nobreak="false">xs:schema</code> element, and is absent if it is absent.</p></item><item><p>The <code nobreak="false">schemaLocation</code> attribute of the <code nobreak="false">xs:import</code> element
                     is copied from the <code nobreak="false">schema-location</code> attribute of the
                        <elcode>xsl:import-schema</elcode> declaration if present, and is absent if
                     it is absent. If there is a contained <code nobreak="false">xs:schema</code> element, the
                     effective value of the <code nobreak="false">schemaLocation</code> attribute is a URI
                     referencing a document containing a copy of the <code nobreak="false">xs:schema</code>
                     element.</p></item><item><p>The base URI of the <code nobreak="false">xs:import</code> element is the same as the base URI
                     of the <elcode>xsl:import-schema</elcode> declaration.</p></item></ulist><p>The schema components included in the 
               <termref def="dt-in-scope-schema-component">in-scope schema components</termref> 
               of an XPath expression or other construct within a stylesheet (that is, the components whose names are
               available for use within that construct) depend on the effective schema role for that
               construct, which is determined by the value of the <code nobreak="false">[xsl:]schema-role</code> attribute
               of the innermost ancestor element having such an attribute; in the absence of such an attribute,
               the unnamed schema role applies. The schema components whose names are available
               are the top-level element and attribute
               declarations and type definitions that are available for reference within the
               synthetic schema document for that schema role. See <bibref ref="xmlschema-1"/> (section 4.2.3,
                  <emph>References to schema components across namespaces</emph>).</p><p>
               <error spec="XT" type="static" class="SE" code="0220"><p>It is a <termref def="dt-static-error">static error</termref> if the synthetic
                     schema document does not satisfy the constraints described in <bibref ref="xmlschema-1"/> (section 5.1, <emph>Errors in Schema Construction and
                        Structure</emph>). This includes, without loss of generality, conflicts such
                     as multiple definitions of the same name.</p></error>
            </p><note><p>The synthetic schema document does not need to be constructed by a real
                  implementation. It is purely a mechanism for defining the semantics of
                     <elcode>xsl:import-schema</elcode> in terms of rules that already exist within
                  the XML Schema specification. In particular, it implicitly defines the rules that
                  determine whether the set of <elcode>xsl:import-schema</elcode> declarations are
                  mutually consistent.</p><p>These rules do not cause names to be imported transitively. The fact that a name
                  is available for reference within a schema document <var>A</var> does not of itself make the
                  name available for reference in a stylesheet that imports the target namespace of
                  schema document <var>A</var>. (See <bibref ref="xmlschema-1"/> section 3.15.3, Constraints on
                  XML Representations of Schemas.) The stylesheet must import all the namespaces
                  containing names that it actually references.</p><p>The <code nobreak="false">namespace</code> attribute indicates that a schema for the given
                  namespace is required by the <termref def="dt-stylesheet">stylesheet</termref>.
                  This information may be enough on its own to enable an implementation to locate
                  the required schema components. The <code nobreak="false">namespace</code> attribute may be
                  omitted to indicate that a schema for names in no namespace is being imported. The
                  zero-length string is not a valid namespace URI, and is therefore not a valid
                  value for the <code nobreak="false">namespace</code> attribute.</p><p>The <code nobreak="false">schema-location</code> attribute is a <termref def="dt-uri-reference">URI Reference</termref> that gives a hint indicating where a schema document
                  or other resource containing the required definitions may be found. It is likely
                  that a <termref def="dt-schema-aware-xslt-processor">schema-aware XSLT
                     processor</termref> will be able to process a schema document found at this
                  location.</p><p>The XML Schema specification gives implementations flexibility in how to handle
                  multiple imports for the same namespace. Multiple imports do not cause errors if
                  the definitions do not conflict.</p><p>A consequence of these rules is that it is not intrinsically an error if no schema
                  document can be located for a namespace identified in an
                     <elcode>xsl:import-schema</elcode> declaration. This will cause an error only
                  if it results in the stylesheet containing references to names that have not been
                  imported.</p><p>An inline schema document (using an <code nobreak="false">xs:schema</code> element as a child of
                  the <code nobreak="false">xsl:import-schema</code> element) has the same status as an external
                  schema document, in the sense that it acts as a hint for a source of schema
                  components in the relevant namespace. To ensure that the inline schema document is
                  always used, it is advisable to use a target namespace that is unique to this
                  schema document.</p></note><p>The use of a namespace in an <elcode>xsl:import-schema</elcode> declaration does not
               by itself associate any namespace prefix with the namespace. If names from the
               namespace are used within the stylesheet module then a namespace declaration must be
               included in the stylesheet module, in the usual way.</p><example><head>An Inline Schema Document</head><p>The following example shows an inline schema document. This declares a simple type
                     <code nobreak="false">local:yes-no</code>, which the stylesheet then uses in the declaration of
                  a variable.</p><p>The example assumes the namespace declaration
                     <code nobreak="false">xmlns:local="http://example.com/ns/yes-no"</code>
               </p><eg xml:space="preserve" role="xslt-declarations">&lt;xsl:import-schema&gt;
  &lt;xs:schema targetNamespace="http://example.com/ns/yes-no"
             xmlns:xs="http://www.w3.org/2001/XMLSchema"
             xmlns:local="http://example.com/ns/yes-no"&gt;
    &lt;xs:simpleType name="yes-no"&gt;
      &lt;xs:restriction base="xs:string"&gt;
        &lt;xs:enumeration value="yes"/&gt;
        &lt;xs:enumeration value="no"/&gt;
      &lt;/xs:restriction&gt;
    &lt;/xs:simpleType&gt;
  &lt;/xs:schema&gt;
&lt;/xsl:import-schema&gt;

&lt;xsl:variable name="condition" select="local:yes-no('yes')" 
                               as="local:yes-no"/&gt;
</eg></example><p>There are two built-in functions
                  (<xfunction>analyze-string</xfunction> and <function>json-to-xml</function>) whose
               result is an XML structure for which a schema is defined. The namespace for these
               schema definitions is (in both cases) <code nobreak="false">http://www.w3.org/2005/xpath-functions</code>. Schema
               components for these namespaces are available for reference within the stylesheet if
               and only if an <elcode>xsl:import-schema</elcode> declaration is present referencing
               this namespace. If such a declaration is present, then the schema that is
               imported is the schema defined in the specification of these functions: the <code nobreak="false">schemaLocation</code>
               attribute has no effect.</p><div3 id="multiple-schemas"><head>Multiple Schemas</head><changes><change issue="451" PR="1819" date="2025-02-18">
                     A stylesheet can import multiple schemas with different schema role names.
                  </change></changes><p>A stylesheet might perform a transformation from an input document conforming to
               one schema, to an output document conforming to a different schema. To facilitate this,
               a schema can be imported with a specific role name, and it is then used only in parts
               of the stylesheet within the scope of an <code nobreak="false">[xsl:]schema-role</code> attribute specifying
               this role name.
               </p><p>More specifically, within the subtree rooted at an element having an 
               <code nobreak="false">[xsl:]schema-role</code> attribute, the static context uses in-scope schema
                  definitions taken from the named schema role.</p><p><error spec="XT" type="static" class="SE" code="4045"><p>It is a <termref def="dt-static-error">static error</termref> if the value
                  of any <code nobreak="false">[xsl:]schema-role</code> in a stylesheet package does
                  not match the value of the <code nobreak="false">role</code> attribute on some
                  <elcode>xsl:import-schema</elcode> element in the same package.</p></error></p><note><p>The introduction of multiple schema roles in XSLT 4.0 enables
                  different input and output documents to be validated against different
                  schemas. For example, a stylesheet might contain the instruction:</p><eg xml:space="preserve">&lt;xsl:result-document validation="strict" schema-role="output"&gt;
   ...
&lt;/xsl:result-document&gt;</eg><p>to control which schema is used to validate the result document.
                  Any instructions used to create validated element nodes
                  in this result document should normally also be within the scope of
                  the same <code nobreak="false">[xsl:]schema-role</code>.</p><p>The fact that multiple schemas can be imported does not relax 
                     the requirement that all
                  schemas used in a transformation must be 
                     <xtermref spec="DM40" ref="dt-schema-compatible">compatible</xtermref>. This may mean,
                  for example, that a transformation designed to convert documents
                  from one version of a defined schema to a later version of the
                  same schema may be unable to import both.</p><p>The reason for this restriction is to ensure that stylesheet components
                  (such as functions) using schema components in their type signatures
                  are compatible across the stylesheet as a whole, and that instance
                  documents whose nodes have type annotations resulting from validation
                  against a schema can be checked for conformance with types declared
                  anywhere in the stylesheet.</p><p>It is possible to validate different parts of a constructed document
                  against different schemas. However, validating an element in a document
                  validates the entire subtree rooted at that element, so requesting 
                  validation at more than one level may be redundant.</p></note></div3></div2></div1><div1 id="data-model"><head>Data Model</head><p>The data model used by XSLT is the XPath 4.0 and XQuery
               4.0 data model (XDM), as defined in <bibref ref="xpath-datamodel-40"/>. XSLT
            operates on source, result and stylesheet documents using the same data model.</p><p>This section elaborates on some particular features of XDM as it is used by XSLT:</p><p>The rules in <specref ref="stylesheet-stripping"/> and <specref ref="strip"/> make use
            of the concept of a whitespace text node.</p><p>
            <termdef id="dt-whitespace-text-node" term="whitespace text node">A <term>whitespace
                  text node</term> is a text node whose content consists entirely of whitespace
               characters (that is, <char>U+0009</char>, <char>U+000A</char>,
               <char>U+000D</char>, or <char>U+0020</char>).</termdef>
         </p><note><p>Features of a source XML document that are not represented in the XDM tree will have
               no effect on the operation of an XSLT stylesheet. Examples of such features are
               entity references, CDATA sections, character references, whitespace within element
               tags, and the choice of single or double quotes around attribute values.</p></note><div2 id="xml-versions"><head>XML Versions</head><p>The XDM data model defined in <bibref ref="xpath-datamodel-40"/> is capable of
               representing either an XML 1.0 document (conforming to <bibref ref="REC-xml"/> and
                  <bibref ref="xml-names"/>) or an XML 1.1 document (conforming to <bibref ref="xml11"/> and <bibref ref="xml-names11"/>), and it makes no distinction
               between the two. In principle, therefore, XSLT 4.0
               can be used with either of these XML versions.</p><p>Construction of the XDM tree is outside the scope of this specification, so XSLT
                  4.0 places no formal requirements on an XSLT
               processor to accept input from either XML 1.0 documents or XML 1.1 documents or both.
               This specification does define a serialization capability (see <specref ref="serialization"/>), though from a conformance point of view it is an optional
               feature. Although facilities are described for serializing the XDM tree as either XML
               1.0 or XML 1.1 (and controlling the choice), there is again no formal requirement on
               an XSLT processor to support either or both of these XML versions as serialization
               targets.</p><p>Because the XDM tree is the same whether the original document was XML 1.0 or XML
               1.1, the semantics of XSLT processing do not depend on the version of XML used by the
               original document. There is no reason in principle why all the input and output
               documents used in a single transformation must conform to the same version of
               XML.</p><p>Some of the syntactic constructs in XSLT 4.0 and
                  XPath 3.0, for example the productions <xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="XML" ref="Char" xlink:type="simple">Char</xnt> and <xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="Names" ref="NT-NCName" xlink:type="simple">NCName</xnt>, are defined by reference to the XML and XML Namespaces
               specifications. There are slight variations between the XML 1.0 and XML 1.1 versions
               of these productions (and, indeed, between different
                  editions of XML 1.0). Implementations <rfc2119>may</rfc2119> support
                  any version; it is
                  <rfc2119>recommended</rfc2119> that an XSLT 4.0
               processor that implements the 1.1 versions <rfc2119>should</rfc2119> also provide a
               mode that supports the 1.0 versions. It is thus <termref def="dt-implementation-defined">implementation-defined</termref> which versions
               and editions of XML and XML Namespaces are supported by the implementation.</p><note><p>The specification referenced as <bibref ref="xml-names"/> was actually published
                  without a version number.</p></note><imp-def-feature id="idf-spec-xml">It is implementation-defined which versions and
               editions of XML and XML Namespaces (1.0 and/or 1.1) are supported.</imp-def-feature><p>Atomic types such as <code nobreak="false">xs:string</code> and <code nobreak="false">xs:dateTime</code> are defined
            in <bibref ref="xpath-datamodel-40"/> by reference to <bibref ref="xmlschema11-2"/>.
            This means for example, that:</p><ulist><item><p>The value space of <code nobreak="false">xs:string</code> includes all Unicode characters
               other than <code nobreak="false">U+0000</code> (but not non-characters such as unpaired surrogates).</p></item><item><p>The type <code nobreak="false">xs:anyURI</code> imposes no constraints on the form of the value.</p></item><item><p>If the range of dates supports negative years, then it must also support year zero.</p></item><item><p>The value space for <code nobreak="false">xs:double</code> and <code nobreak="false">xs:float</code> includes
               negative zero and positive zero as distinct values.</p></item></ulist><p>However, for operations that necessarily involve use of a schema processor (such as
            <elcode>xsl:import-schema</elcode> and schema validation), it is acceptable to use
            a processor that supports only XSD 1.0.</p></div2><div2 id="preprocessing-source-docs"><head>Preprocessing Source Documents</head><p>Source documents supplied as input to a transformation may be subject to preprocessing. 
               Two kinds of preprocessing are defined: stripping of type annotations (see <specref ref="stripping-annotations"/>), 
               and stripping of whitespace text nodes (see <specref ref="strip"/>).
            </p><p>Stripping of type annotations happens before stripping of whitespace text nodes.
            </p><p>The source documents to which this applies are as follows:
            </p><ulist><item><p>The document containing the <termref def="dt-global-context-item"/> if it is a node;</p></item><item><p>Any documents containing a node present in the <termref def="dt-initial-match-selection"/>;</p></item><item><p>Any document containing a node that is returned by the functions <function>document</function>, <xfunction>doc</xfunction>,
                  or <xfunction>collection</xfunction>;</p></item><item><p>Any document read using <code nobreak="false">xsl:source-document</code>.</p></item></ulist><note><p>This list excludes documents passed as the values of 
               <termref def="dt-stylesheet-parameter">stylesheet parameters</termref> or parameters 
               of the <termref def="dt-initial-named-template"/> or <termref def="dt-initial-function"/>, 
               trees created by functions such as <xfunction>parse-xml</xfunction>, <code nobreak="false">parse-xml-fragment</code>,
               <xfunction>analyze-string</xfunction>, or <function>json-to-xml</function>,
               and values returned from <termref def="dt-extension-function">extension
                  functions</termref>.
            </p></note><p>If a node other than a document node is supplied (for example as the global context item), 
               then the preprocessing is applied to the entire document containing that node. If several nodes within the same 
               document are supplied (for example as nodes in the initial match selection, or as nodes returned by the 
               <xfunction>collection</xfunction> function), then the preprocessing is only applied to that document once.
               If a whitespace text node is supplied (for example as the global context item) and the rules cause this node
               to be stripped from its containing tree, then the behavior is as if this node had not been supplied 
               (which may cause an error, for example if a global context item is required.)
            </p><p>The rules determining whether or not stripping of annotations and/or whitespace 
               happens are defined at the level of a <termref def="dt-package"/>. Declarations within a <termref def="dt-library-package"/> 
               only affect the handling of documents loaded using a call on the <function>document</function>, <xfunction>doc</xfunction>,
               or <xfunction>collection</xfunction> functions or an evaluation of an <elcode>xsl:source-document</elcode> instruction 
               appearing lexically within the same package. Declarations within the <termref def="dt-top-level-package"/> also affect the processing 
               of the <termref def="dt-global-context-item"/> and the <termref def="dt-initial-match-selection"/>.
            </p><p>The semantics of the <function>document</function>, <xfunction>doc</xfunction>,
               and <xfunction>collection</xfunction> functions are formally defined in terms of mappings from URIs to document nodes 
               maintained within the dynamic context (see <specref ref="xpath-dynamic-context"/>). The effect of the 
               declarations that control stripping of type annotations 
               and whitespace is therefore to modify this mapping (so it now maps the URI to a stripped document). The modification 
               applies to the dynamic context for calls to these function appearing within a particular package; each package therefore 
               has a different set of mappings. This means that when two calls to the <xfunction>doc</xfunction> function appear in 
               different packages, specifying the same absolute URI, then in general different documents are returned. An implementation 
               <rfc2119>may</rfc2119> return the same document for two such calls if it is able to determine that the effect of the annotation 
               and whitespace stripping rules in both packages is the same.
            </p><p>The effect of dynamic calls to the <function>document</function>, <xfunction>doc</xfunction>,
               and <xfunction>collection</xfunction> functions is defined in the same way as for other functions with dependencies on 
               the dynamic context. As described in <specref ref="additional-dynamic-context"/>, named function references 
               (such as <code nobreak="false">doc#1</code>) and calls on <xfunction>function-lookup</xfunction> (for example, <code nobreak="false">function-lookup("doc", 1)</code>) 
               are defined to retain the XPath static and dynamic context at the point of invocation as part of the closure of the 
               resulting function item, and to use this preserved context when a dynamic function call is subsequently made using the function item.
            </p><div3 id="stripping-annotations"><head>Stripping Type Annotations from a Source Tree</head><p>
               <termdef id="dt-type-annotation" term="type annotation">The term <term>type
                     annotation</term> is used in this specification to refer to the value returned
                  by the <code nobreak="false">dm:type-name</code> accessor of a node: see <xspecref spec="DM40" ref="dm-type-name"/>.</termdef>
            </p><p>There is sometimes a requirement to write stylesheets that produce the same results
               whether or not the source documents have been validated against a schema. To achieve
               this, an option is provided to remove any <termref def="dt-type-annotation">type
                  annotations</termref> on element and attribute nodes in a <termref def="dt-source-tree">source tree</termref>, replacing them with an annotation of
                  <code nobreak="false">xs:untyped</code> in the case of element nodes, and
                  <code nobreak="false">xs:untypedAtomic</code> in the case of attribute nodes.</p><p>Such stripping of <termref def="dt-type-annotation">type annotations</termref> can be
               requested by specifying <code nobreak="false">input-type-annotations="strip"</code> on the <elcode>xsl:package</elcode> element. This
               attribute has three permitted values: <code nobreak="false">strip</code>, <code nobreak="false">preserve</code>, and
                  <code nobreak="false">unspecified</code>. The default value is <code nobreak="false">unspecified</code>. 
            <phrase diff="add" at="2022-01-01">Specifying <code nobreak="false">unspecified</code> has the same effect
            as omitting the attribute.</phrase></p><p>The <code nobreak="false">input-type-annotations</code> attribute may also
               be specified on the <elcode>xsl:stylesheet</elcode> element; if it is specified at
               this level then it must be consistent for all stylesheet modules within the same
               package.</p><p>
               <error spec="XT" type="static" class="SE" code="0265"><p> It is a <termref def="dt-static-error">static error</termref> if there is a
                        <termref def="dt-stylesheet-module">stylesheet module</termref> in a
                        <termref def="dt-package">package</termref> that specifies
                        <code nobreak="false">input-type-annotations="strip"</code> and another <termref def="dt-stylesheet-module">stylesheet module</termref> that specifies
                        <code nobreak="false">input-type-annotations="preserve"</code>, or if a stylesheet module specifies the value
                           <code nobreak="false">strip</code> or <code nobreak="false">preserve</code> and the same value is not
                        specified on the <elcode>xsl:package</elcode> element of the containing
                        package.</p></error>
            </p><p diff="add" at="2022-01-01">Type annotations are stripped from relevant source documents if 
               at least one <termref def="dt-stylesheet-module"/> in the <termref def="dt-stylesheet"/>
               specifies <code nobreak="false">input-type-annotations="strip"</code> on the <elcode>xsl:package</elcode>, 
               <elcode>xsl:stylesheet</elcode>, or <elcode>xsl:transform</elcode> element.</p><p>When type annotations are stripped, the following changes are made to the source
               tree:</p><ulist><item><p>The type annotation of every element node is changed to <code nobreak="false">xs:untyped</code>
                  </p></item><item><p>The type annotation of every attribute node is changed to
                        <code nobreak="false">xs:untypedAtomic</code>
                  </p></item><item><p>The typed value of every element and attribute node is set to be the same as
                     its string value, as an instance of <code nobreak="false">xs:untypedAtomic</code>.</p></item><item><p>The <code nobreak="false">is-nilled</code> property of every element node is set to
                        <code nobreak="false">false</code>.</p></item></ulist><p>The values of the <code nobreak="false">is-id</code> and <code nobreak="false">is-idrefs</code> properties are not
               changed.</p><note><p>Stripping <termref def="dt-type-annotation">type annotations</termref> does not
                  necessarily return the document to the state it would be in had validation not
                  taken place. In particular, any defaulted elements and attributes that were added
                  to the tree by the validation process will still be present, and elements and
                  attributes validated as IDs will still be accessible using the
                     <xfunction>id</xfunction> function.</p></note></div3><div3 id="strip"><head>Stripping Whitespace from a Source Tree</head><p>A <termref def="dt-source-tree">source tree</termref> supplied as input to the
               transformation process may contain <termref def="dt-whitespace-text-node">whitespace
                  text nodes</termref> that are of no interest, and that do not need to be retained
               by the transformation. Conceptually, an XSLT <termref def="dt-processor">processor</termref> makes a copy of the source tree from which unwanted <termref def="dt-whitespace-text-node">whitespace text nodes</termref> have been removed.
               This process is referred to as whitespace stripping. </p><p>The stripping process takes as input a set of element names whose child <termref def="dt-whitespace-text-node">whitespace text nodes</termref> are to be preserved.
               The way in which this set of element names is established using the
                  <elcode>xsl:strip-space</elcode> and <elcode>xsl:preserve-space</elcode>
               declarations is described later in this section.</p><p>The stripping process that applies for a particular
               <termref def="dt-package"/> is determined by the <elcode>xsl:strip-space</elcode>
               and <elcode>xsl:preserve-space</elcode> declarations within that package.</p><p>A <termref def="dt-whitespace-text-node">whitespace text node</termref> is preserved
               if either of the following apply:</p><ulist><item><p>The element name of the parent of the text node is in the set of
                     whitespace-preserving element names.</p></item><item><p>An ancestor element of the text node has an <code nobreak="false">xml:space</code> attribute
                     with a value of <code nobreak="false">preserve</code>, and no closer ancestor element has
                        <code nobreak="false">xml:space</code> with a value of <code nobreak="false">default</code>.</p></item></ulist><p>Otherwise, the <termref def="dt-whitespace-text-node">whitespace text node</termref>
               is stripped.</p><p>The <code nobreak="false">xml:space</code> attributes are not removed from the tree.</p><e:element-syntax xmlns:e="http://www.w3.org/1999/XSL/Spec/ElementSyntax" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" name="strip-space">
      <e:in-category name="declaration"/>
      <e:attribute name="elements" required="yes">
         <e:data-type name="tokens"/>
      </e:attribute>
      <e:empty/>
      <e:allowed-parents>
         <e:parent name="package"/>
         <e:parent name="stylesheet"/>
         <e:parent name="transform"/>
      </e:allowed-parents>
   </e:element-syntax><e:element-syntax xmlns:e="http://www.w3.org/1999/XSL/Spec/ElementSyntax" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" name="preserve-space">
      <e:in-category name="declaration"/>
      <e:attribute name="elements" required="yes">
         <e:data-type name="tokens"/>
      </e:attribute>
      <e:empty/>
      <e:allowed-parents>
         <e:parent name="package"/>
         <e:parent name="stylesheet"/>
         <e:parent name="transform"/>
      </e:allowed-parents>
   </e:element-syntax><p>The set of whitespace-preserving element names is specified by
                  <elcode>xsl:strip-space</elcode> and <elcode>xsl:preserve-space</elcode>
               <termref def="dt-declaration">declarations</termref>. Whether an element name is
               included in the set of whitespace-preserving names is determined by the best match
               among all the <elcode>xsl:strip-space</elcode> or <elcode>xsl:preserve-space</elcode>
               declarations: it is included if and only if there is no match or the best match is an
                  <elcode>xsl:preserve-space</elcode> element. The <elcode>xsl:strip-space</elcode>
               and <elcode>xsl:preserve-space</elcode> elements each have an <code nobreak="false">elements</code>
               attribute whose value is a whitespace-separated list of <xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="XP40" ref="prod-xpath40-NameTest" xlink:type="simple">NameTests</xnt>; an element name matches an
                  <elcode>xsl:strip-space</elcode> or <elcode>xsl:preserve-space</elcode> element if
               it matches one of the <xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="XP40" ref="prod-xpath40-NameTest" xlink:type="simple">NameTests</xnt>.
               An element matches a <xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="XP40" ref="prod-xpath40-NameTest" xlink:type="simple">NameTest</xnt> if
               and only if the <xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="XP40" ref="prod-xpath40-NameTest" xlink:type="simple">NameTest</xnt> would be
               true for the element as an XPath node test.</p><p><error spec="XT" type="static" class="SE" code="0270"><p>It is a <termref def="dt-static-error">static error</termref> if within any <termref def="dt-package">package</termref> the same <xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="XP40" ref="prod-xpath40-NameTest" xlink:type="simple">NameTest</xnt> appears in both an
                        <elcode>xsl:strip-space</elcode> and an <elcode>xsl:preserve-space</elcode>
                     declaration if both have the same <termref def="dt-import-precedence">import
                        precedence</termref>. Two NameTests are considered the same if they match
                     the same set of names (which can be determined by comparing them after
                     expanding namespace prefixes to URIs).</p></error></p><p>Otherwise, when more than one
                  <elcode>xsl:strip-space</elcode> and <elcode>xsl:preserve-space</elcode> element
                  within the relevant <termref def="dt-package">package</termref> matches, the best matching element is determined by
               the best matching <xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="XP40" ref="prod-xpath40-NameTest" xlink:type="simple">NameTest</xnt>.
                  
               The rules are similar to those for
               <termref def="dt-template-rule">template rules</termref>:</p><ulist><item><p>First, any match with lower <termref def="dt-import-precedence">import
                        precedence</termref> than another match is ignored.</p></item><item><p>Next, any match that has a lower <termref def="dt-default-priority">default
                        priority</termref> than the <termref def="dt-default-priority">default
                        priority</termref> of another match is ignored.</p></item><item><p>If several matches have the same <termref def="dt-default-priority">default priority</termref> (which can only happen
                     if one of the NameTests takes the form <code nobreak="false">*:local</code> and the other takes
                     the form <code nobreak="false">prefix:*</code>), then the declaration that appears last in
                        <termref def="dt-declaration-order">declaration order</termref> is used.</p></item></ulist><p>If an element in a source document has a <termref def="dt-type-annotation">type
                  annotation</termref> that is a simple type or a complex type with simple content,
               then any whitespace text nodes among its children are preserved, regardless of any
                  <elcode>xsl:strip-space</elcode> declarations. The reason for this is that
               stripping a whitespace text node from an element with simple content could make the
               element invalid: for example, it could cause the <code nobreak="false">minLength</code> facet to be
               violated.</p><p>Stripping of <termref def="dt-type-annotation">type annotations</termref> happens
               before stripping of whitespace text nodes, so this situation will not occur if
                  <code nobreak="false">input-type-annotations="strip"</code> is specified.</p><note><p>In <bibref ref="xpath-datamodel-40"/>, processes are described for constructing an
                  XDM tree from an Infoset or from a PSVI. Those processes deal with whitespace
                  according to their own rules, and the provisions in this section apply to the
                  resulting tree. In practice this means that elements that are defined in a DTD or
                  a Schema to contain element-only content will have <termref def="dt-whitespace-text-node">whitespace text nodes</termref> stripped,
                  regardless of the <elcode>xsl:strip-space</elcode> and
                     <elcode>xsl:preserve-space</elcode> declarations in the stylesheet.</p><p>However, source trees are not necessarily constructed using those processes;
                  indeed, they are not necessarily constructed by parsing XML documents. Nothing in
                  the XSLT specification constrains how the source tree is constructed, or what
                  happens to <termref def="dt-whitespace-text-node">whitespace text nodes</termref>
                  during its construction. The provisions in this section relate only to whitespace
                  text nodes that are present in the tree supplied as input to the XSLT processor.
                  The XSLT processor cannot preserve whitespace text nodes unless they were actually
                  present in the supplied tree.</p></note></div3></div2><div2 id="id-in-data-model"><head>Attribute Types and DTD Validation</head><p>The mapping from the Infoset to the XDM data model, described in <bibref ref="xpath-datamodel-40"/>, does not retain attribute types. This means, for
               example, that an attribute described in the DTD as having attribute type
                  <code nobreak="false">NMTOKENS</code> will be annotated in the XDM tree as
                  <code nobreak="false">xs:untypedAtomic</code> rather than <code nobreak="false">xs:NMTOKENS</code>, and its typed
               value will consist of a single <code nobreak="false">xs:untypedAtomic</code> item rather than a
               sequence of <code nobreak="false">xs:NMTOKEN</code> items.</p><p>Attributes with a DTD-derived type of ID, IDREF, or IDREFS will be marked in the XDM
               tree as having the <code nobreak="false">is-id</code> or <code nobreak="false">is-idrefs</code> properties. It is
               these properties, rather than any <termref def="dt-type-annotation">type
                  annotation</termref>, that are examined by the functions <xfunction>id</xfunction>
               and <xfunction>idref</xfunction> described in <bibref ref="xpath-functions-40"/>.</p></div2><div2 id="limits"><head>Limits</head><p>The XDM data model (see <bibref ref="xpath-datamodel-40"/>) generally leaves
               limits on the ranges and precision of values as <termref def="dt-implementation-defined"/>,
               though some minimum limits are defined: see <xspecref spec="DM40" ref="limits"/>.</p><imp-def-feature id="idf-defaults-limits">Limits on the value space of primitive
               datatypes, where not fixed by <bibref ref="xmlschema-2"/> or <bibref ref="xpath-datamodel-40"/>, are
               implementation-defined.</imp-def-feature></div2><div2 id="d-o-e-in-data-model"><head>Disable Output Escaping</head><p>For backwards compatibility reasons, XSLT 4.0
               continues to support the <code nobreak="false">disable-output-escaping</code> feature introduced in
               XSLT 1.0. This is an optional feature and implementations are not
                  <rfc2119>required</rfc2119> to support it. A new facility, that of named <termref def="dt-character-map">character maps</termref> (see <specref ref="character-maps"/>) was introduced in XSLT 2.0. It provides
               similar capabilities to <code nobreak="false">disable-output-escaping</code>, but without distorting
               the data model.</p><p>If an <termref def="dt-implementation">implementation</termref> supports the
                  <code nobreak="false">disable-output-escaping</code> attribute of <elcode>xsl:text</elcode> and
                  <elcode>xsl:value-of</elcode>, (see <specref ref="disable-output-escaping"/>),
               then the data model for trees constructed by the <termref def="dt-processor">processor</termref> is augmented with a boolean value representing the value of
               this property. This boolean value, however, can be set only within a <termref def="dt-final-result-tree">final result tree</termref> that is being passed to the
               serializer.</p><p>Conceptually, each character in a text node on such a result tree has a boolean
               property indicating whether the serializer is to disable the normal rules for
               escaping of special characters (for example, outputting of <code nobreak="false">&amp;</code> as
                  <code nobreak="false">&amp;amp;</code>) in respect of this character.</p><note><p>In practice, the nodes in a <termref def="dt-final-result-tree">final result
                     tree</termref> will often be streamed directly from the XSLT processor to the
                  serializer. In such an implementation, <code nobreak="false">disable-output-escaping</code> can be
                  viewed not so much a property stored with nodes in the tree, but rather as
                  additional information passed across the interface between the XSLT processor and
                  the serializer.</p></note></div2></div1><div1 id="constructs"><head>Features of the XSLT Language</head><div2 id="names"><head>Names</head><div3 id="qname"><head>Qualified Names</head><p>Many constructs appearing in a stylesheet, for example <termref def="dt-named-template">named templates</termref>, <termref def="dt-mode">modes</termref>, and <termref def="dt-attribute-set">attribute sets</termref>,
                  are named using a qualified name: this consists of a local name and an optional
                  namespace URI.</p><p>In most cases where such names are written in a <termref def="dt-stylesheet">stylesheet</termref>, 
                  the syntax for expressing the name is given by the
                  production <xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="XP40" ref="prod-xpath40-EQName" xlink:type="simple">EQName</xnt> in the XPath
                  specification. In practice, this means that three forms are permitted:</p><ulist><item><p>A simple <code nobreak="false">NCName</code> appearing on its own (without any prefix). This
                        represents the local name of the object. The interpretation of unprefixed
                        names is described below.</p></item><item><p>A <termref def="dt-lexical-qname">lexical QName</termref> written in the
                        form <code nobreak="false">NCName ":" NCName</code> where the first part is a namespace
                        prefix and the second part is the local name. The namespace part of the
                        object’s name is then derived from the prefix by examining the
                        <phrase diff="chg" at="2023-05-04"><termref def="dt-applicable-static-namespaces"/></phrase> 
                        for the element node in the stylesheet where the
                        name appears.</p></item><item><p>A <xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="XP40" ref="prod-xpath40-URIQualifiedName" xlink:type="simple">URIQualifiedName</xnt> in the form <code nobreak="false">"Q{" URI? "}" NCName</code>
                        where the two parts of the name, that is the namespace part and the local
                        part, both appear explicitly. If the URI part is omitted (for example
                           <code nobreak="false">Q{}local</code>), the resulting expanded QName is a QName whose
                        namespace part is absent.</p></item></ulist><p diff="add" at="2022-11-01">The rules for the use of these constructs generally permit
               leading and trailing whitespace, which is ignored.</p><note><p>There are a few places where the third form, a URIQualifiedName, is not
                     permitted. These include the <code nobreak="false">name</code> attribute of
                        <elcode>xsl:element</elcode> and <elcode>xsl:attribute</elcode> (which have
                     a separate <code nobreak="false">namespace</code> attribute for the purpose), and constructs
                     defined by other specifications. For example, names appearing within an
                     embedded <code nobreak="false">xs:schema</code> element must follow the XSD rules.</p></note><p>
                  <termdef id="dt-expanded-qname" term="expanded QName">An <term>expanded
                        QName</term> is a value in the value space of the <code nobreak="false">xs:QName</code>
                     datatype as defined in the XDM data model (see <bibref ref="xpath-datamodel-40"/>): 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><termdef id="dt-eqname" term="EQName">An <term>EQName</term> is a string
                     representing an <termref def="dt-expanded-qname">expanded QName</termref> where
                     the string, after removing leading and trailing whitespace, is in the form
                     defined by the <xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="XP40" ref="prod-xpath40-EQName" xlink:type="simple">EQName</xnt>
                     production in the XPath specification.</termdef></p><p>
                  <termdef id="dt-lexical-qname" term="lexical QName">A <term>lexical QName</term>
                     is a string representing an <termref def="dt-expanded-qname">expanded
                        QName</termref> where the string, after removing leading and trailing
                     whitespace, is within the lexical space of the <code nobreak="false">xs:QName</code> datatype
                     as defined in XML Schema (see <bibref ref="xmlschema-2"/>): that is, a local
                     name optionally preceded by a namespace prefix and a colon.</termdef>
               </p><p>Note that every <termref def="dt-lexical-qname">lexical QName</termref> is an
                     <termref def="dt-eqname">EQName</termref>, but the converse is not true.</p><p>The following rules are used when interpreting a <termref def="dt-lexical-qname">lexical QName</termref>:</p><olist><item><p>
                        <termdef id="dt-defining-element" term="defining element">A string in the
                           form of a lexical QName may occur as the value of an attribute node in a
                           stylesheet module, or within an XPath <termref def="dt-expression">expression</termref> contained in an attribute or text node within a stylesheet module, or as the
                           result of evaluating an XPath expression contained in such a node. The
                           element containing this attribute or
                              text node is referred to as the <term>defining element</term>
                           of the lexical QName.</termdef>
                     </p></item><item><p>If the lexical QName has a prefix, then the prefix is expanded into a URI
                        reference using the namespace declarations in effect on its <termref def="dt-defining-element">defining element</termref>. The <termref def="dt-expanded-qname">expanded QName</termref> consisting of the local
                        part of the name and the possibly null URI reference is used as the name of
                        the object. The default namespace of the defining element (see <xspecref spec="DM40" ref="ElementNode"/>) is <emph>not</emph> used for unprefixed
                        names.</p><p>
                        <error spec="XT" type="static" class="SE" code="0280"><p>In the case of a prefixed <termref def="dt-lexical-qname">lexical
                                 QName</termref> used as the value (or as
                                 part of the value) of an attribute in the <termref def="dt-stylesheet">stylesheet</termref>, or appearing within an
                              XPath <termref def="dt-expression">expression</termref> in the
                              stylesheet, it is a <termref def="dt-static-error">static
                                 error</termref> if the <termref def="dt-defining-element">defining
                                 element</termref> has no namespace node whose name matches the
                              prefix of the <termref def="dt-lexical-qname">lexical
                              QName</termref>.</p></error>
                     </p><p>
                        <error spec="XT" type="dynamic" class="DE" code="0290"><p>Where the result of evaluating an XPath expression (or an attribute
                              value template) is required to be a <termref def="dt-lexical-qname">lexical QName</termref>, or if it is permitted to be a <termref def="dt-lexical-qname">lexical QName</termref> and the actual value
                              takes the form of a <termref def="dt-lexical-qname">lexical
                                 QName</termref>, then unless otherwise specified it is a <termref def="dt-dynamic-error"> dynamic error</termref> if the value
                              has a prefix and the <termref def="dt-defining-element">defining
                                 element</termref> has no namespace node whose name matches that
                              prefix. This error <rfc2119>may</rfc2119> be raised as a <termref def="dt-static-error">static error</termref> if the value of the
                              expression can be determined statically.</p></error>
                     </p></item><item><p>If the lexical QName has no prefix, then:</p><olist><item><p>In the case of an unprefixed QName used as a <code nobreak="false">NameTest</code>
                              within an XPath <termref def="dt-expression">expression</termref> (see
                                 <specref ref="expressions"/>), and in certain other contexts, the
                              namespace to be used in expanding the QName may be specified by means
                              of the <code nobreak="false">[xsl:]xpath-default-namespace</code> attribute, as
                              specified in <specref ref="unprefixed-qnames"/>.</p></item><item><p>If the name is in one of the following categories, then the default
                              namespace of the <termref def="dt-defining-element">defining
                                 element</termref> is used:</p><olist><item><p>Where a QName is used to define the name of an element being
                                    constructed. This applies both to cases where the name is known
                                    statically (that is, the name of a literal result element) and
                                    to cases where it is computed dynamically (the value of the
                                       <code nobreak="false">name</code> attribute of the
                                       <elcode>xsl:element</elcode> instruction).</p></item><item><p>The default namespace is used when expanding the first argument
                                    of the function <function>element-available</function>.</p></item><item><p>The default namespace applies to any unqualified element names
                                    appearing in the <code nobreak="false">cdata-section-elements</code>
                                    or
                                          <code nobreak="false">suppress-indentation</code> attributes of
                                       <elcode>xsl:output</elcode> or
                                       <elcode>xsl:result-document</elcode>
                                 </p></item></olist></item><item><p>In all other cases, a <termref def="dt-lexical-qname">lexical
                                 QName</termref> with no prefix represents an <termref def="dt-expanded-qname">expanded QName</termref> in no namespace
                              (that is, an <code nobreak="false">xs:QName</code> value in which both the prefix and
                              the namespace URI are absent).</p></item></olist></item></olist></div3><div3 id="unprefixed-qnames" diff="chg" at="2022-01-01"><head>Unprefixed Lexical QNames in Expressions and Patterns</head><changes><change issue="296" PR="1181" date="2024-04-30">
                     The <code nobreak="false">[xsl:]xpath-default-namespace</code> attribute can be set to the value
                     <code nobreak="false">##any</code>, which causes unprefixed element names to match in any namespace
                     or none.
                  </change></changes><div4 id="unprefixed-element-names"><head>Unprefixed Element Names</head><p>The attribute <code nobreak="false">[xsl:]xpath-default-namespace</code> (see <specref ref="standard-attributes"/>) 
                  may be used on an element in the <termref def="dt-stylesheet">stylesheet</termref> to define the 
                  namespace that will be used for an unprefixed element or type name within an XPath expression, and
                  in certain other contexts listed below.</p><p>The value of the attribute is either the namespace URI to be used, or a zero-length string,
                  or the value <code nobreak="false">##any</code>.</p><p>For any element in the stylesheet, this attribute has an effective value, which is the value of 
                     the <code nobreak="false">[xsl:]xpath-default-namespace</code> on that element or on the innermost containing 
                     element that specifies such an attribute, or the zero-length string if no containing 
                     element specifies such an attribute.</p><p>For any element in the <termref def="dt-stylesheet">stylesheet</termref>, the
                     effective value of the attribute determines the value of the 
                     <xtermref ref="dt-default-namespace-elements-and-types" spec="XP40"/>
                     in the static context of any XPath
                     expression contained in an attribute or text
                     node of that element (including XPath expressions in <termref def="dt-attribute-value-template">attribute value templates</termref>
                     and <termref def="dt-text-value-template">text value
                        templates</termref>). The effect of this is specified in <bibref ref="xpath-40"/>; in summary, 
                     it determines the namespace used for any
                     unprefixed type name or element name.</p><p>The special value <code nobreak="false">##any</code> only affects:</p><ulist><item><p>An unprefixed element name used in a 
                        <xnt xmlns:xlink="http://www.w3.org/1999/xlink" ref="prod-xpath40-NameTest" spec="XP40" xlink:type="simple">NameTest</xnt>, 
                        either within an XPath expression or a <termref def="dt-pattern"/>.
                        Its effect is that an unprefixed name matches any element having the required local name,
                        irrespective of the namespace URI (or lack of it). A pattern such as <code nobreak="false">match="title"</code>
                        is therefore interpreted as a wildcard match <code nobreak="false">match="*:title</code>. The default priority
                        of such a pattern changes accordingly.</p></item><item><p>An unprefixed type name; the effect is to treat the name as
                     referring to a type whose namespace is <code nobreak="false">http://www.w3.org/2001/XMLSchema</code>.</p></item></ulist><note><p>To take an example, older versions of the internet index of RFCs (requests for comments)
                     use the namespace URI <code nobreak="false">http://www.rfc-editor.org/rfc-index</code>, while newer
                     versions use <code nobreak="false">https://www.rfc-editor.org/rfc-index</code> (note the change of URI scheme).
                     XSLT code that needs to work with either version can be simplified by setting the
                     default namespace to <code nobreak="false">##any</code>: but be aware that this might lead to spurious matching
                     of names in an unrelated namespace.</p></note><p>Any other value of this attribute sets the default namespace for any of the following
                     constructs appearing within its scope:</p><ulist><item><p>any unprefixed element name used in a <termref def="dt-pattern">pattern</termref>
                        </p></item><item><p>any unprefixed element name used in the <code nobreak="false">elements</code> attribute of
                           the <elcode>xsl:strip-space</elcode> or <elcode>xsl:preserve-space</elcode>
                           instructions</p></item><item><p>any unprefixed element name used in the <code nobreak="false">as</code>
                           attribute of an <termref def="dt-xslt-element">XSLT element</termref>
                        </p></item><item><p>any unprefixed type name used in the <code nobreak="false">type</code> attribute of an 
                           <termref def="dt-xslt-element">XSLT element</termref>
                        </p></item><item><p>any unprefixed type name used in the <code nobreak="false">xsl:type</code> attribute of a 
                           literal result element.
                        </p></item></ulist><p>The <code nobreak="false">[xsl:]xpath-default-namespace</code> attribute <rfc2119>must</rfc2119>
                  be in the <termref def="dt-xslt-namespace">XSLT namespace</termref> if and only if
                  its parent element is <emph>not</emph> in the XSLT namespace.</p><p>If the effective value of the attribute is a zero-length string, which will be the
                  case if it is explicitly set to a zero-length string or if it is not specified at
                  all, then an unprefixed element name or type name refers to a name that is in no
                  namespace. The default namespace of the parent element (see <xspecref spec="DM40" ref="ElementNode"/>) 
                  is <emph>not</emph> used.</p><p>The attribute does not affect other names, for example function names, 
                     variable names, or template names, or strings that are interpreted 
                     as lexical QNames during stylesheet evaluation, such as the effective value 
                     of the name attribute of <elcode>xsl:element</elcode> or the string supplied as the first 
                     argument to the <code nobreak="false">key</code> function.
                  </p></div4><div4 id="unprefixed-function-names"><head>Unprefixed Function Names</head><p>Unprefixed function names are treated as names in the 
                     <termref def="dt-standard-function-namespace"/>.</p></div4><div4 id="other-unprefixed-names"><head>Other Unprefixed Names</head><p>For other unprefixed names, for example variable
                     names, template names, mode names, or strings that are interpreted as <termref def="dt-lexical-qname">lexical QNames</termref> during stylesheet evaluation,
                     such as the <termref def="dt-effective-value">effective value</termref> of the
                     <code nobreak="false">name</code> attribute of <elcode>xsl:element</elcode> or the string
                     supplied as the first argument to the <function>key</function> function, any unprefixed
                  lexical QName is taken as being a no-namespace name.</p></div4></div3><div3 id="reserved-namespaces"><head>Reserved Namespaces</head><p>
                  <termdef id="dt-reserved-namespace" term="reserved namespace">The XSLT namespace,
                     together with certain other namespaces recognized by an XSLT processor, are
                     classified as <term>reserved namespaces</term> and <rfc2119>must</rfc2119> be
                     used only as specified in this and related specifications.</termdef> The
                  reserved namespaces are those listed below.</p><p diff="add" at="2023-05-04">Each of the reserved namespaces has a conventional
               prefix. As described in <specref ref="fixed-namespaces"/>, the <code nobreak="false">fixed-namespaces</code>
               attribute may bind one of the reserved namespaces simply by referring to its conventional
               prefix. For example, <code nobreak="false">fixed-namespaces="xs"</code> has the effect of binding the prefix
               <code nobreak="false">xs</code> to the namespace <code nobreak="false">http://www.w3.org/2001/XMLSchema</code>.</p><ulist><item><p>The <termref def="dt-xslt-namespace">XSLT namespace</termref> described in
                        <specref ref="xslt-namespace"/>, is reserved, 
                        <phrase diff="add" at="2023-05-04">with conventional prefix <code nobreak="false">xsl</code></phrase>.</p></item><item><p>
                        <termdef id="dt-standard-function-namespace" term="standard function namespace">The <term>standard function
                              namespace</term>
                           <code nobreak="false">http://www.w3.org/2005/xpath-functions</code>,
                           <phrase diff="add" at="2023-05-04">with conventional prefix <code nobreak="false">fn</code></phrase>,
                           is used for functions
                           in the function library defined in <bibref ref="xpath-functions-40"/> and
                           for standard functions defined in this specification.</termdef>
                     </p></item><item><p> The namespace
                           <code nobreak="false">http://www.w3.org/2005/xpath-functions/math</code>,
                        <phrase diff="add" at="2023-05-04">with conventional prefix <code nobreak="false">math</code></phrase>,
                        is used for
                        mathematical functions in the function library defined in <bibref ref="xpath-functions-40"/>. </p></item><item><p> The namespace
                           <code nobreak="false">http://www.w3.org/2005/xpath-functions/map</code>,
                        <phrase diff="add" at="2023-05-04">with conventional prefix <code nobreak="false">map</code></phrase>,
                        is used for
                        functions defined in this specification relating to the manipulation of
                           maps. </p></item><item><p> The namespace
                           <code nobreak="false">http://www.w3.org/2005/xpath-functions/array</code>,
                        <phrase diff="add" at="2023-05-04">with conventional prefix <code nobreak="false">array</code></phrase>,
                        is reserved for
                        use as described in <bibref ref="xpath-functions-40"/>.<phrase diff="del" at="2022-01-01"> The namespace is
                        reserved whether or not the processor actually supports XPath 3.1.</phrase></p></item><item><p>
                        <termdef id="xml-namespace" term="XML namespace">The <term>XML
                              namespace</term>, defined in <bibref ref="xml-names"/> as
                              <code nobreak="false">http://www.w3.org/XML/1998/namespace</code>, is used for
                           attributes such as <code nobreak="false">xml:lang</code>, <code nobreak="false">xml:space</code>, and
                              <code nobreak="false">xml:id</code>.</termdef> 
                        <phrase diff="add" at="2023-05-04">This namespace is always bound to the prefix <code nobreak="false">xml</code>.</phrase>
                     </p></item><item><p><termdef id="dt-schema-namespace" term="schema namespace">The <term>schema
                              namespace</term>
                           <code nobreak="false">http://www.w3.org/2001/XMLSchema</code>,
                        <phrase diff="add" at="2023-05-04">with conventional prefix <code nobreak="false">xs</code></phrase>,
                        is used as defined in
                              <bibref ref="xmlschema-1"/></termdef>. In a <termref def="dt-stylesheet">stylesheet</termref> this namespace may be used to
                        refer to built-in schema datatypes and to the constructor functions
                        associated with those datatypes.</p></item><item><p><termdef id="dt-schema-instance-namespace" term="schema instance namespace">The <term>schema instance namespace</term>
                           <code nobreak="false">http://www.w3.org/2001/XMLSchema-instance</code>,
                        <phrase diff="add" at="2023-05-04">with conventional prefix <code nobreak="false">xsi</code></phrase>,
                        is used as defined
                           in <bibref ref="xmlschema-1"/></termdef>. Attributes in this namespace,
                        if they appear in a <termref def="dt-stylesheet">stylesheet</termref>, are
                        treated by the XSLT processor in the same way as any other attributes.</p></item><item><p><termdef id="dt-standard-error-namespace" term="standard error namespace">The <term>standard error namespace</term>
                           <code nobreak="false">http://www.w3.org/2005/xqt-errors</code>,
                        <phrase diff="add" at="2023-05-04">with conventional prefix <code nobreak="false">err</code></phrase>,
                        is used for error codes
                           defined in this specification and related specifications. It is also used
                           for the names of certain predefined variables accessible within the scope
                           of an <elcode>xsl:catch</elcode> element.</termdef></p></item><item><p>The namespace <code nobreak="false">http://www.w3.org/2000/xmlns/</code> is reserved for use
                        as described in <bibref ref="xml-names"/>. No element or attribute node can
                        have a name in this namespace, and although the prefix <code nobreak="false">xmlns</code> is
                        implicitly bound to this namespace, no namespace node will ever define this
                        binding.</p></item></ulist><note><p>With the exception of the XML namespace, any of the above namespaces that are
                     used in a stylesheet must be explicitly declared with a namespace declaration.
                     Although conventional prefixes are used for these namespaces in this
                     specification, any prefix may be used in a user stylesheet.</p></note><p>Reserved namespaces may be used without restriction to refer to the names of
                  elements and attributes in source documents and result documents. As far as the
                  XSLT processor is concerned, reserved namespaces other than the XSLT namespace may
                  be used without restriction in the names of <termref def="dt-literal-result-element">literal result elements</termref> and <termref def="dt-data-element">user-defined data elements</termref>, and in the names of
                  attributes of literal result elements or of <termref def="dt-xslt-element">XSLT
                     elements</termref>: but other processors <rfc2119>may</rfc2119> impose
                  restrictions or attach special meaning to them. Reserved namespaces <rfc2119>must
                     not</rfc2119> be used, however, in the names of stylesheet-defined objects such
                  as <termref def="dt-variable">variables</termref> and <termref def="dt-stylesheet-function">stylesheet functions</termref>,
                     nor in the names of <termref def="dt-extension-function">extension functions</termref>
                     or <termref def="dt-extension-instruction">extension instructions</termref>.</p><p>It is not an error to use a reserved namespace in the name of an 
                  <termref def="dt-extension-attribute">extension attribute</termref>: 
                  attributes such as <code nobreak="false">xml:space</code> and <code nobreak="false">xsi:type</code> 
                  fall into this category. XSLT processors <rfc2119>must not</rfc2119> reject such attributes, 
                  and <rfc2119>must not</rfc2119> attach any meaning to them other than any meaning 
                  defined by the relevant specification.</p><p>
                  <error spec="XT" type="static" class="SE" code="0080"><p>It is a <termref def="dt-static-error">static error</termref> to use a
                           <termref def="dt-reserved-namespace">reserved namespace</termref> in the
                        name of a <termref def="dt-named-template">named template</termref>, a
                           <termref def="dt-mode">mode</termref>, an <termref def="dt-attribute-set">attribute set</termref>, a <termref def="dt-key">key</termref>, a
                           <termref def="dt-decimal-format">decimal-format</termref>, a <termref def="dt-variable">variable</termref> or <termref def="dt-parameter">parameter</termref>, a <termref def="dt-stylesheet-function">stylesheet
                           function</termref>, a named <termref def="dt-output-definition">output
                           definition</termref>, an <termref def="dt-accumulator"/>, or a <termref def="dt-character-map">character map</termref><phrase>; except that the name
                              <code nobreak="false">xsl:initial-template</code> is permitted as a template
                           name.</phrase></p></error>
               </p><note><p>The name <code nobreak="false">xsl:original</code> is used within <elcode>xsl:override</elcode>
                     to refer to a <termref def="dt-component"/> that is being overridden. Although
                     the name <code nobreak="false">xsl:original</code> is used to refer to the component, the
                     component has its own name, and no component ever has the name
                        <code nobreak="false">xsl:original</code>. </p></note></div3></div2><div2 id="expressions"><head>Expressions</head><p>XSLT uses the expression language defined by XPath 4.0
               <bibref ref="xpath-40"/>. Expressions are used in XSLT for a variety of purposes
               including:</p><ulist><item><p>selecting nodes for processing;</p></item><item><p>specifying conditions for different ways of processing a node;</p></item><item><p>generating text to be inserted in a <termref def="dt-result-tree">result
                        tree</termref>.</p></item></ulist><p>
               <termdef id="dt-expression" term="expression">Within this specification, the term
                     <term>XPath expression</term>, or simply <term>expression</term>, means a
                  string that matches the production <xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="XP40" ref="prod-xpath40-Expr" xlink:type="simple">Expr</xnt> 
                  defined in <bibref ref="xpath-40"/><phrase diff="del">, with the extensions defined in <specref ref="map"/></phrase>.</termdef>
            </p><p>XPath expressions may occur:</p><ulist><item><p>As the value of certain attributes on XSLT-defined instructions (for example,
            the <code nobreak="false">select</code> attribute of the <elcode>xsl:apply-templates</elcode> instruction)</p></item><item><p>Within curly brackets in <termref def="dt-attribute-value-template">attribute value templates</termref>
               and <termref def="dt-text-value-template">text value templates</termref>.</p></item><item><p>As the content of a text node within an <elcode>xsl:select</elcode> instruction.</p></item></ulist><p>In the above cases, the static processing (compilation) of XPath expressions takes place at the same time
               as the static processing of the stylesheet itself, while evaluation of the XPath expressions takes
               place dynamically during stylesheet evaluation. There are also, however:</p><ulist><item><p>XPath expressions where both the static processing and dynamic evaluation of the XPath expression
               takes place during static processing of the stylesheet. These are referred to as 
                  <termref def="dt-static-expression">static expressions</termref>,
               and they perform the same function as preprocessing directives in other languages.</p></item><item><p>XPath expressions that are dynamically constructed (as character strings):
               both the static processing and dynamic evaluation of these expressions occurs during stylesheet
               evaluation. See <specref ref="dynamic-xpath"/>.</p></item></ulist><p>In general:</p><ulist><item><p>It is a <termref def="dt-static-error"/> if an XPath <termref def="dt-expression"/> does not match 
                  the XPath production <xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="XP40" ref="prod-xpath40-Expr" xlink:type="simple">Expr</xnt>, or if it fails to satisfy other
               static constraints defined in the XPath specification, for example that all variable
               references <rfc2119>must</rfc2119> refer to <termref def="dt-variable">variables</termref> 
                  that are in scope. Error codes are defined in <bibref ref="xpath-40"/>.</p></item><item><p>The transformation fails with a <termref def="dt-dynamic-error"/> 
                  if any XPath <termref def="dt-expression"/> is evaluated and raises a dynamic error.
               Error codes are defined in <bibref ref="xpath-40"/>.</p></item><item><p>The transformation fails with a <termref def="dt-type-error">type error</termref> if
               an XPath <termref def="dt-expression">expression</termref> raises a type error, or if
               the result of evaluating the XPath <termref def="dt-expression">expression</termref>
               is evaluated and raises a type error, or if the XPath processor raises a type error
               during static analysis of an <termref def="dt-expression">expression</termref>. Error
               codes are defined in <bibref ref="xpath-40"/>.</p></item></ulist><p>There are some exceptions to these rules, for example:</p><ulist><item><p>Static errors may be suppressed where <termref def="dt-forwards-compatible-behavior"/> is enabled (see
                  <specref ref="forwards"/>).</p></item><item><p>Dynamic errors may be caught using <elcode>xsl:try</elcode> and <elcode>xsl:catch</elcode>.</p></item><item><p>Dynamic errors evaluating a predicate within a pattern do not cause the transformation to fail,
               they merely cause the pattern not to match.</p></item></ulist><p>
               <termdef id="dt-required-type" term="required type">The context within a 
                  <termref def="dt-stylesheet">stylesheet</termref> where an XPath 
                  <termref def="dt-expression">expression</termref> appears may specify the <term>required
                     type</term> of the expression. The required type indicates the type of the
                  value that the expression is expected to return.</termdef> If no required type is
               specified, the expression may return any value: in effect, the required type is then
                  <code nobreak="false">item()*</code>. </p><p>
               <termdef id="dt-coercion-rules" term="coercion rules"> The term <term>coercion rules</term> 
                  means the coercion rules defined in <bibref ref="xpath-40"/>, applied 
                  unless otherwise specified with XPath 1.0 
                  compatibility mode set to <code nobreak="false">false</code>.</termdef>
            </p><note><p>In earlier versions of this specification, the coercion rules were referred to as the
               <term>function conversion rules.</term></p></note><note><p> These are the rules defined in <bibref ref="xpath-40"/> for converting the
                  supplied argument of a function call to the required type of that argument, as
                  defined in the function signature. The same rules are used in XSLT for converting
                  the value of a variable to the declared type of the variable, or the result of
                  evaluating a function or template body to the declared type of the function or
                  template. They are also used when parameters are supplied to a template using
                     <elcode>xsl:with-param</elcode>. In all such cases, the rules that apply are
                  the XPath 4.0 rules without XPath 1.0 compatibility mode. The rules with XPath 1.0
                  compatibility mode set to <code nobreak="false">true</code> are used only for XPath function calls, and for the
                  operands of certain XPath operators. </p></note><p>This specification also invokes the XPath
               <termref def="dt-coercion-rules"/> to
               convert the result of evaluating an XSLT <termref def="dt-sequence-constructor">sequence constructor</termref> to a required type (for example, the sequence
               constructor enclosed in an <elcode>xsl:variable</elcode>,
                  <elcode>xsl:template</elcode>, or <elcode>xsl:function</elcode> element).</p><p>Any <termref def="dt-dynamic-error">dynamic error</termref> or <termref def="dt-type-error">type error</termref> 
               that occurs when applying the <termref def="dt-coercion-rules"/> to convert
               a value to a required type results in the transformation failing, in the same way as
               if the error had occurred while evaluating an expression.</p><note><p>Note the distinction between the two kinds of error that may occur. Attempting to
                  convert an integer to a date is a type error, because such a conversion is never
                  possible. Type errors can be raised statically if they can be detected
                  statically, whether or not the construct in question is ever evaluated. Attempting
                  to convert the <phrase diff="chg" at="2022-01-01"><code nobreak="false">xs:untypedAtomic</code></phrase> item 
                  <code nobreak="false">2003-02-29</code> to a date is a dynamic error rather
                  than a type error, because the problem is with this particular value, not with its
                  type. Dynamic errors are raised only if the instructions or expressions that
                  cause them are actually evaluated. </p></note><p>The XPath specification states (see <xspecref spec="XP40" ref="id-eol-handling"/>)
               that the host language must
               specify whether the XPath processor normalizes all line breaks on input, before
               parsing, and if it does so, whether it uses the rules of [XML 1.0] or [XML 1.1]. In
               the case of XSLT, all handling of line breaks is the responsibility of the XML parser
               (which may support either XML 1.0 or XML 1.1); the XSLT and XPath processors perform
               no further changes.</p><note><p>Most XPath expressions in a stylesheet appear within
                  XML attributes. They are therefore subject to XML line-ending normalization (for
                  example, a CRLF sequence is normalized to LF) and also to XML attribute-value
                  normalization, which replaces tabs and newlines by spaces. Normalization of whitespace can be
                  prevented by using character references such as <code nobreak="false">&amp;#x9;</code>.</p><p>XPath expressions appearing in text nodes, (specifically, in text value templates
                  — see <specref ref="text-value-templates"/>,  
                  or in the <elcode>xsl:select</elcode> instruction) 
                  are subject to line-ending normalization but not
                  attribute-value normalization.</p><p>In both cases it is unwise to include the characters <char>U+0009</char>,
               <char>U+000A</char>, and <char>U+000D</char>, as literal characters within string literals.
               Instead they should be escaped as <code nobreak="false">&amp;#x9;</code>, <code nobreak="false">&amp;#xA;</code>,
               and <code nobreak="false">&amp;#xD;</code> respectively, or constructed dynamically by a call on 
               the <xfunction>char</xfunction> function. This can be conveniently embedded
               within a string template delimited by backticks: for example <code nobreak="false">`Width:{char(9)}8mm`</code>.
               (The advantage of using this form in preference to XML character references is that
               they are more likely to survive when the stylesheet is processed using tools such as XML editors.)</p></note></div2><div2 id="static-and-dynamic-context"><head>The Static and Dynamic Context</head><p>XPath defines the concept of an <xtermref spec="XP40" ref="dt-expression-context">expression context</xtermref> which contains all the information that can affect
               the result of evaluating an <termref def="dt-expression">expression</termref>. The
               expression context has two parts, the <xtermref spec="XP40" ref="dt-static-context">static context</xtermref>, and the <xtermref spec="XP40" ref="dt-dynamic-context">dynamic context</xtermref>. The components that make up the expression context
               are defined in the XPath specification (see <xspecref spec="XP40" ref="context"/>).
               This section describes the way in which these components are initialized when an
               XPath expression is contained within an XSLT stylesheet.</p><p diff="add" at="2022-01-01">
               This section does not apply to <termref def="dt-static-expression">static expressions</termref> 
               (whose context is defined in <specref ref="static-expression"/>), nor to XPath expressions 
               evaluated using <elcode>xsl:evaluate</elcode> (whose context is defined in 
               <specref ref="evaluate-dynamic-context"/>).
            </p><p>As well as providing values for the static and dynamic context components defined in
               the XPath specification, XSLT defines additional context components of its own. These
               context components are used by XSLT instructions (for example,
                  <elcode>xsl:next-match</elcode> and <elcode>xsl:apply-imports</elcode>), and also
               by the functions in the extended function library described in this
               specification.</p><p>The following four sections describe:</p><slist><sitem>
                  <specref ref="static-context"/>
               </sitem><sitem>
                  <specref ref="additional-static-context"/>
               </sitem><sitem>
                  <specref ref="xpath-dynamic-context"/>
               </sitem><sitem>
                  <specref ref="additional-dynamic-context"/>
               </sitem></slist><div3 id="static-context"><head>Initializing the Static Context</head><p>The <xtermref spec="XP40" ref="dt-static-context">static context</xtermref> of an
                  XPath expression appearing in an XSLT stylesheet is initialized as follows. In
                  these rules, the term <term>containing element</term> means the element within the
                  stylesheet that is the parent of the attribute or text
                     node whose value contains the XPath expression in question, and the
                  term <term>enclosing element</term> means the containing element or any of its
                  ancestors.</p><ulist><item><p>
                        <termref def="dt-xpath-compat-mode">XPath 1.0 compatibility mode</termref>
                        is set to <code nobreak="false">true</code> if and only if the containing element is processed with
                           <termref def="dt-xslt-10-behavior">XSLT 1.0 behavior</termref> (see
                           <specref ref="backwards"/>).</p></item><item><p>The <xtermref spec="XP40" ref="dt-static-namespaces">statically known
                           namespaces</xtermref> are the 
                        <phrase diff="chg" at="2023-05-04"><termref def="dt-applicable-static-namespaces"/></phrase>
                        for the containing element.</p></item><item><p>The <xtermref spec="XP40" ref="dt-default-namespace-elements-and-types">default namespace
                           for elements and types</xtermref> is determined as described in
                        <specref ref="unprefixed-element-names"/>.</p></item><item><p diff="chg" at="2022-11-25">The <xtermref ref="dt-default-function-namespace" spec="XP40">default function namespace</xtermref> is
                        <code nobreak="false">http://www.w3.org/2005/xpath-functions</code> (and cannot be changed).</p></item><item><p>The <xtermref spec="XP40" ref="dt-issd">in-scope schema
                           definitions</xtermref> for the XPath expression are the same as the
                           <termref def="dt-in-scope-schema-component">in-scope schema
                           components</termref> for the <termref def="dt-stylesheet">stylesheet</termref>, and are as specified in <specref ref="built-in-types"/>.</p></item><item><p>The <xtermref spec="XP40" ref="dt-in-scope-variables">in-scope
                           variables</xtermref> are defined by the <termref def="dt-variable-binding-element">variable binding elements</termref>
                        that are in scope for the containing element (see <specref ref="variables-and-parameters"/>).</p></item><item><p>The <xtermref spec="XP40" ref="dt-statically-known-function-definitions">statically known
                           function definitions</xtermref> are:</p><ulist><item><p>The functions defined in <bibref ref="xpath-functions-40"/> in
                              namespaces <code nobreak="false">http://www.w3.org/2005/xpath-functions</code> and
                                 <code nobreak="false">http://www.w3.org/2005/xpath-functions/math</code>;</p></item><item><p>The functions defined in this specification in namespaces
                                 <code nobreak="false">http://www.w3.org/2005/xpath-functions</code> and
                                 <code nobreak="false">http://www.w3.org/2005/xpath-functions/map</code>;</p></item><item><p>Constructor functions for all the simple types in the <xtermref spec="XP40" ref="dt-issd">in-scope schema definitions</xtermref>, including both built-in
                              types and user-defined types;</p></item><item><p>The <termref def="dt-stylesheet-function">stylesheet
                                 functions</termref> defined in the containing <termref def="dt-package"/>;</p></item><item><p>Stylesheet functions defined in used packages, subject to visibility:
                              see <specref ref="package-dependencies"/>;</p></item><item><p>any <termref def="dt-extension-function">extension functions</termref>
                              bound using <termref def="dt-implementation-defined">implementation-defined</termref> mechanisms (see <specref ref="extension"/>).</p><note><p>The term <termref def="dt-extension-function"/> includes both
                                 vendor-supplied and user-written extension functions.</p></note></item></ulist><note><p>It follows from the above that a conformant XSLT processor must implement
                           the entire library of functions defined in
                                 <bibref ref="xpath-functions-40"/> as well as those defined
                           in this specification.</p></note></item><item><p>The <xtermref spec="XP40" ref="dt-static-collations">statically known
                           collations</xtermref> are <termref def="dt-implementation-defined">implementation-defined</termref>, except that they <rfc2119>must</rfc2119> always include (a) the Unicode
                           codepoint collation, defined in <xspecref spec="FO40" ref="string-compare"/>, and (b) the family of UCA collations described
                           in <xspecref spec="FO40" ref="uca-collations"/>.</p></item><item><p><term>Static base URI</term>: In a conventional interpreted 
                        environment, the static base URI of an expression in the stylesheet is the base URI 
                        of the containing element in the stylesheet. The concept of the base URI of a node 
                        is defined in <xspecref spec="DM40" ref="dm-base-uri"/>.</p><p>When stylesheets are executed in an environment where no source code is present
                        (for example, because the code of the stylesheet has been compiled and is distributed 
                        as executable object code), it is <rfc2119>recommended</rfc2119> (subject to operational
                        constraints such as security) that the static base URI used during stylesheet evaluation
                        should be the location from which the stylesheet was loaded for execution 
                        (its “deployed location”). This means, for example, that when the <xfunction>doc</xfunction>
                        or <function>document</function> functions are called with a relative URI, the required document
                        is by default located relative to the deployed location of the stylesheet.
                     </p><p>Whether or not the stylesheet is executed directly from source code,
                     it is possible that no static base URI is available, for example because the code was supplied
                     as an anonymous input stream, or because security policies are set to prevent executable code discovering
                     the location from which it was loaded. If the static base URI is not known, the <xfunction>static-base-uri</xfunction>
                     function returns the empty sequence, and other operations that depend on the static base URI may fail with
                     a dynamic error.</p></item><item><p>The set of <xtermref spec="XP40" ref="dt-static-decimal-formats">statically
                           known decimal formats</xtermref> is the set of decimal formats defined by
                           <elcode>xsl:decimal-format</elcode> declarations in the stylesheet. </p></item></ulist></div3><div3 id="additional-static-context"><head>Additional Static Context Components used by XSLT</head><p>Some of the components of the XPath static context are used also by <termref def="dt-xslt-element">XSLT elements</termref>. For example, the
                     <elcode>xsl:sort</elcode> element makes use of the collations defined in the
                  static context, and attributes such as <code nobreak="false">type</code> and <code nobreak="false">as</code> may
                  reference types defined in the <termref def="dt-in-scope-schema-component">in-scope schema components</termref>.</p><p>Many top-level declarations in a stylesheet, and attributes on the
                     <elcode>xsl:stylesheet</elcode> element, affect the behavior of instructions
                  within the stylesheet. Each of these constructs is described in its appropriate
                  place in this specification.</p><p>A number of these constructs are of particular significance because they are used
                  by functions defined in XSLT, which are added to the library of functions
                  available for use in XPath expressions within the stylesheet. These are:</p><ulist><item><p>The set of named keys, used by the <function>key</function> function</p></item><item><p>The set of named character maps, used by the <function>character-map</function> function</p></item><item><p>The values of system properties, used by the
                           <function>system-property</function> function</p></item><item><p>The set of available instructions, used by the
                           <function>element-available</function> function</p></item><item><p>The <termref def="dt-default-mode"/>, used by the
                     <function>apply-templates</function> function</p></item></ulist><note><p>If these functions are called within a <termref def="dt-static-expression"/>, the results will reflect the capabilities and
                     configuration of the processor used to perform static analysis, while if they
                     are called elsewhere, the results should reflect the capabilities and
                     configuration of the processor used to perform dynamic evaluation, which might
                     give a different result. These calls should not be pre-evaluated at compile
                     time unless it is known that this will give the same result.</p></note></div3><div3 id="xpath-dynamic-context"><head>Initializing the Dynamic Context</head><p>For convenience, the dynamic context is described in two parts: the <termref def="dt-focus">focus</termref>, which represents the place in the source
                  document that is currently being processed, and a collection of additional context
                  variables.</p><p>A number of functions specified in <bibref ref="xpath-functions-40"/> are defined
                  to be <xtermref spec="FO40" ref="dt-deterministic">deterministic</xtermref>,
                  meaning that if they are called twice during the same <xtermref spec="FO40" ref="execution-scope">execution scope</xtermref>, with the same arguments, then
                  they return the same results (see <xspecref spec="FO40" ref="terminology"/>). In
                  XSLT, the execution of a stylesheet defines the execution scope. This means, for
                  example, that if the function <xfunction>current-dateTime</xfunction> is called
                  repeatedly during a transformation, it produces the same result each time. By
                  implication, the components of the dynamic context on which these functions depend
                  are also stable for the duration of the transformation. Specifically, the
                  following components defined in <xspecref spec="XP40" ref="eval_context"/> must be
                  stable: <emph>function implementations</emph>, <emph>current dateTime</emph>,
                     <emph>implicit timezone</emph>, <emph>available documents</emph>,
                     <emph>available collections</emph>, and <emph>default collection</emph>. The
                  values of global variables and stylesheet parameters are also stable for the
                  duration of a transformation. The focus is <emph>not</emph> stable; the additional
                  dynamic context components defined in <specref ref="additional-dynamic-context"/>
                  are also <emph>not</emph> stable.</p><p>As specified in <bibref ref="xpath-functions-40"/>, implementations may provide
                  user options that relax the requirement for the <xfunction>doc</xfunction> and
                     <xfunction>collection</xfunction> functions (and therefore, by implication, the
                     <function>document</function> function) to return stable results. By default,
                  however, the functions must be stable. The manner in which such user options are
                  provided, if at all, is <termref def="dt-implementation-defined">implementation-defined</termref>.</p><imp-def-feature id="idf-api-stability">Implementations may provide user options that
                  relax the requirement for the <xfunction>doc</xfunction> and
                     <xfunction>collection</xfunction> functions (and therefore, by implication, the
                     <function>document</function> function) to return stable results. The manner in
                  which such user options are provided, if at all, is <termref def="dt-implementation-defined"/>. </imp-def-feature><p>XPath expressions contained in <code nobreak="false">[xsl:]use-when</code> attributes are not
                  considered to be evaluated “during the transformation” as defined above. For
                  details see <specref ref="conditional-inclusion"/>.</p><p><termdef id="dt-absent" term="absent">A component of the context
                     that has no value is said to be <term>absent</term>.</termdef> This is a
                  distinguishable state, and is not the same as having the empty sequence as its
                  value.</p><div4 id="focus"><head>Maintaining Position: the Focus</head><p>
                     <termdef id="dt-focus" term="focus">When a <termref def="dt-sequence-constructor">sequence constructor</termref> is
                        evaluated, the <termref def="dt-processor">processor</termref> keeps track
                        of which items are being processed by means of a set of implicit variables
                        referred to collectively as the <term>focus</term>.</termdef> More
                     specifically, the focus consists of the following three values:</p><ulist><item><p><termdef id="dt-context-item" term="context item">The <term>context
                                 item</term> is the item currently being processed. An item (see
                                 <bibref ref="xpath-datamodel-40"/>) is either an atomic item (such
                              as an integer, date, or string), a node, or
                                 a function item. It changes whenever instructions such as
                                 <elcode>xsl:apply-templates</elcode> and
                                 <elcode>xsl:for-each</elcode> are used to process a sequence of
                              items; each item in such a sequence becomes the context item while
                              that item is being processed.</termdef> The context item is returned
                           by the XPath <termref def="dt-expression">expression</termref>
                           <code nobreak="false">.</code> (dot).</p><note diff="add" at="2023-10-30"><p>Although XPath 4.0 allows the context value to be an arbitrary sequence,
                           at the interface between XSLT 4.0 and XPath 4.0 it is always either a single item,
                           or absent. XSLT 4.0 therefore continues to use the term <termref def="dt-context-item"/>
                        rather than <xtermref spec="XP40" ref="dt-context-value"/>.</p></note></item><item><p><termdef id="dt-context-position" term="context position">The
                                 <term>context position</term> is the position of the context item
                              within the sequence of items currently being processed. It changes
                              whenever the context item changes. When an instruction such as
                                 <elcode>xsl:apply-templates</elcode> or
                                 <elcode>xsl:for-each</elcode> is used to process a sequence of
                              items, the first item in the sequence is processed with a context
                              position of 1, the second item with a context position of 2, and so
                              on.</termdef> The context position is returned by the XPath <termref def="dt-expression">expression</termref>
                           <code nobreak="false">position()</code>.</p></item><item><p><termdef id="dt-context-size" term="context size">The <term>context
                                 size</term> is the number of items in the sequence of items
                              currently being processed. It changes whenever instructions such as
                                 <elcode>xsl:apply-templates</elcode> and
                                 <elcode>xsl:for-each</elcode> are used to process a sequence of
                              items; during the processing of each one of those items, the context
                              size is set to the count of the number of items in the sequence (or
                              equivalently, the position of the last item in the
                              sequence).</termdef> The context size is returned by the XPath
                              <termref def="dt-expression">expression</termref>
                           <code nobreak="false">last()</code>.</p></item></ulist><p>
                     <termdef id="dt-context-node" term="context node">If the <termref def="dt-context-item">context item</termref> is a node (as distinct from
                        an atomic item such as an integer), then it is also referred to as the
                           <term>context node</term>. The context node is not an independent
                        variable, it changes whenever the context item changes. When the context
                        item is an atomic item or a function
                           item, there is no context node.</termdef> The context node is
                     returned by the XPath <termref def="dt-expression">expression</termref>
                     <code nobreak="false">self::node()</code>, and it is used as the starting node for all relative
                     path expressions.</p><p>Where the containing element of an XPath expression is an <termref def="dt-instruction">instruction</termref> or a <termref def="dt-literal-result-element">literal result element</termref>, the
                     initial context item, context position, and context size for the XPath <termref def="dt-expression">expression</termref> are the same as the <termref def="dt-context-item">context item</termref>, <termref def="dt-context-position">context position</termref>, and <termref def="dt-context-size">context size</termref> for the evaluation of the
                     containing instruction or literal result element.</p><p>The <xtermref spec="XP40" ref="dt-context-value"/> for evaluating global
                        variables <phrase diff="add" at="2022-01-01">declared</phrase>
                     in the <termref def="dt-top-level-package"/> is set to the <termref def="dt-global-context-item"/>
                        supplied when the transformation is invoked (see <specref ref="initiating"/>).
                     <phrase diff="add" at="2022-01-01">For global variables declared in a </phrase> <termref def="dt-library-package">library
                           package</termref>, the context value <phrase diff="del" at="2022-01-01">for evaluating global variables</phrase> is
                     <termref def="dt-absent"/>. </p><p>For an XPath expression contained in a <termref def="dt-value-template"/>, the initial context item, context position, and
                     context size for the XPath <termref def="dt-expression">expression</termref>
                     are the same as the <termref def="dt-context-item">context item</termref>,
                        <termref def="dt-context-position">context position</termref>, and <termref def="dt-context-size">context size</termref> for the evaluation of the
                     containing <termref def="dt-sequence-constructor"/>.</p><p>In other cases (for example, where the containing element is
                        <elcode>xsl:sort</elcode>, <elcode>xsl:with-param</elcode>, or
                        <elcode>xsl:key</elcode>), the rules are given in the specification of the
                     containing element.</p><p>The <function>current</function> function can be used within any XPath <termref def="dt-expression">expression</termref> to select the item that was
                     supplied as the context item to the XPath expression by the XSLT processor.
                     Unlike <code nobreak="false">.</code> (dot) this is unaffected by changes to the context item
                     that occur within the XPath expression. The <function>current</function>
                     function is described in <specref ref="func-current"/>.</p><p>On completion of an instruction that changes the <termref def="dt-focus">focus</termref> (such as <elcode>xsl:apply-templates</elcode> or
                        <elcode>xsl:for-each</elcode>), the focus reverts to its previous value.</p><p>When a <termref def="dt-stylesheet-function">stylesheet function</termref> is
                     called, the focus within the body of the function is initially <termref def="dt-absent">absent</termref>.</p><p>When the focus is <termref def="dt-absent">absent</termref>, evaluation of any
                        <termref def="dt-expression">expression</termref> that references the
                     context item, context position, or context size results in a <termref def="dt-type-error"/>
                     <xerrorref spec="XP40" class="DY" code="0002"/></p><p>The description above gives an outline of the way the <termref def="dt-focus">focus</termref> works. Detailed rules for the effect of each instruction
                     are given separately with the description of that instruction. In the absence
                     of specific rules, an instruction uses the same focus as its parent
                     instruction. </p><p>
                     <termdef id="dt-singleton-focus" term="singleton focus">A <term>singleton
                           focus</term> based on an item <var>J</var> has the <termref def="dt-context-item">context item</termref> (and
                           therefore the <termref def="dt-context-node">context node</termref>, if
                              <var>J</var> is a node) set to <var>J</var>, and the <termref def="dt-context-position">context position</termref> and <termref def="dt-context-size">context size</termref> both set to 1
                        (one).</termdef>
                  </p></div4><div4 id="evaluation-context"><head>Other Components of the XPath Dynamic Context</head><p>The previous section explained how the <termref def="dt-focus">focus</termref>
                     for an XPath expression appearing in an XSLT stylesheet is initialized. This
                     section explains how the other components of the <xtermref spec="XP40" ref="dt-dynamic-context">dynamic context</xtermref> of an XPath expression
                     are initialized.</p><ulist><item><p>The <xtermref spec="XP40" ref="dt-variable-values">dynamic
                              variables</xtermref> are the current values of the in-scope <termref def="dt-variable-binding-element">variable binding
                           elements</termref>.</p></item><item><p diff="chg" at="2022-11-25">The <xtermref spec="XP40" ref="dt-dynamically-known-function-definitions">dynamically known function definitions</xtermref>
                        (representing the functions accessible using <function>function-available</function> or <xfunction>function-lookup</xfunction>)
                           include all the functions available in the static context, and may also include an additional 
                           <termref def="dt-implementation-defined"/> set of functions that are available dynamically but not statically.
                        </p><note><p>This set therefore includes some functions that are not available for
                        dynamic calling using <elcode>xsl:evaluate</elcode>, for example <termref def="dt-stylesheet-function">stylesheet functions</termref>
                        whose visibility is private, and XSLT-defined functions such as <function>current</function> and <function>key</function>.</p></note><note><p>The rule that all functions present in the static context must always be present in 
                           the dynamic context is a consistency constraint. The effect of violating a consistency constraint is 
                           <termref def="dt-implementation-defined"/>: it does not necessarily lead to an error. 
                           For example, if the version of a used package that is available
                           at evaluation time does not include all public user-defined functions that were available in the version that was
                           used at analysis time, then a processor <rfc2119>may</rfc2119> recover by raising an error only if the function
                           is actually called. Conversely, if the evaluation-time version of the package includes additional public functions, these <rfc2119>may</rfc2119>
                        be included in the dynamic context even though they were absent from the static context. 
                        Dynamic calling of functions using <xfunction>function-lookup</xfunction>
                        may therefore be an effective strategy for coping with variations between versions of a library package on which a stylesheet
                        depends.</p></note></item><item><p>The <xtermref spec="XP40" ref="dt-def-collation">default
                           collation</xtermref> is defined by the value of the
                           <code nobreak="false">[xsl:]default-collation</code> attribute on the innermost enclosing
                           element that has such an attribute. For details, see <specref ref="default-collation-attribute"/>.</p><p>
                           <termdef id="dt-default-collation" term="default collation">In this
                              specification the term <term>default collation</term> means the collation
                              that is used by XPath operators such as <code nobreak="false">eq</code> and
                              <code nobreak="false">lt</code> appearing in XPath expressions within the
                              stylesheet.</termdef>
                        </p><p>This collation is also used by default when comparing strings in the
                           evaluation of the <elcode>xsl:key</elcode> and
                           <elcode>xsl:for-each-group</elcode> elements. This <rfc2119>may</rfc2119>
                           also (but need not necessarily) be the same as the default collation used
                           for <elcode>xsl:sort</elcode> elements within the stylesheet. Collations
                           used by <elcode>xsl:sort</elcode> are described in <specref ref="collating-sequences"/>.</p><note diff="add" at="2023-05-19"><p>The default collation is usually known
                        statically. One notable exception is when the function call <code nobreak="false">default-collation()</code>
                        appears in the initializing expression of an optional <elcode>xsl:function</elcode> parameter,
                           for example:</p><eg xml:space="preserve">&lt;xsl:function name="f:myfunc"&gt;
  &lt;xsl:param name="collation" required="no" select="default-collation()"/&gt;
&lt;/xsl:function&gt;</eg><p>In this situation the call on <code nobreak="false">default-collation()</code> returns the default
                              collation from the context of the function call, which may differ from the default
                              collation of the function declaration.
                        </p></note></item><item><p>The <xtermref spec="XP40" ref="dt-available-docs">available
                              documents</xtermref> are defined as part of the XPath 3.0 dynamic context to support the
                              <xfunction>doc</xfunction> function, but this component is also
                           referenced by the similar XSLT <function>document</function> function:
                           see <specref ref="func-document"/>. This variable defines a mapping
                           between URIs passed to the <xfunction>doc</xfunction> or
                              <function>document</function> function and the document nodes that are
                           returned.</p><p>The mapping from URIs to document nodes is
                           affected by <elcode>xsl:strip-space</elcode> declarations and by the
                              <code nobreak="false">input-type-annotations</code> attribute, and may therefore vary
                           from one package to another.</p><note><p>Defining this as part of the evaluation context is a formal way of
                              specifying that the way in which URIs get turned into document nodes
                              is outside the control of the language specification, and depends
                              entirely on the run-time environment in which the transformation takes
                              place.</p></note><p>The XSLT-defined <function>document</function> function allows the use of
                           URI references containing fragment identifiers. The interpretation of a
                           fragment identifier depends on the media type of the resource
                           representation. Therefore, the information supplied in 
                           <xtermref spec="XP40" ref="dt-available-docs">available documents</xtermref> for
                           XSLT processing must provide not only a mapping from URIs to document
                           nodes as required by XPath, but also a mapping from URIs to media
                           types.</p></item><item><p>All other aspects of the dynamic context (for example,
                           the current date and time, the implicit timezone, the default language, calendar, and place,
                           the available documents, text resources, and collections, and the default collection<phrase diff="del" at="2022-01-01"> — details
                           vary slightly between XPath 3.0 and XPath 3.1</phrase>) are <termref def="dt-implementation-defined"/>,
                        and do not change in the course of a single transformation, except to the extent that they
                        <rfc2119>may</rfc2119> be different from one <termref def="dt-package"/> to another.</p></item></ulist></div4></div3><div3 id="additional-dynamic-context"><head>Additional Dynamic Context Components used by XSLT</head><changes><change issue="407" PR="2274" date="2026-01-06">
                     <p>XSLT-specific components of the dynamic context can now be retained in the captured
                     context of a function item, in the same way as XPath-defined components of the dynamic context.</p>
                  </change></changes><p>In addition to the values that make up the <termref def="dt-focus">focus</termref>, an XSLT processor maintains a number of other dynamic context
                  components that reflect aspects of the evaluation context. These components are
                  fully described in the sections of the specification that maintain and use them.
                  They are:</p><ulist><item><p>The <termref def="dt-current-template-rule">current template rule</termref>,
                        which is the <termref def="dt-template-rule">template rule</termref> most
                        recently invoked by an <elcode>xsl:apply-templates</elcode>,
                           <elcode>xsl:apply-imports</elcode>, or <elcode>xsl:next-match</elcode>
                        instruction: see <specref ref="apply-imports"/>; </p></item><item><p>The <termref def="dt-current-mode">current mode</termref>, which is the
                           <termref def="dt-mode">mode</termref> set by the most recent call of
                           <elcode>xsl:apply-templates</elcode> (for a full definition see <specref ref="modes"/>);</p></item><item><p>The <termref def="dt-current-group">current group</termref> and <termref def="dt-current-grouping-key">current grouping key</termref>, which
                        provide information about the collection of items currently being processed
                        by an <elcode>xsl:for-each-group</elcode>
                        
                        instruction: see <specref ref="func-current-group"/> and <specref ref="func-current-grouping-key"/>;</p><note><p>In XSLT 3.0 the initial value of these two properties is “absent”, which
                           means that any reference to their values causes a dynamic error.
                           Previously, the initial value was the empty sequence. </p></note></item><item><p>The <termref def="dt-current-merge-group"/> and <termref def="dt-current-merge-key"/>, which provide information about the
                        collection of items currently being processed by an
                           <elcode>xsl:merge</elcode> instruction.</p></item><item><p>The <termref def="dt-current-captured-groups"/>: this is maintained
                        when a string is matched against a regular expression using the
                           <elcode>xsl:analyze-string</elcode> instruction. It is a map
                        from integer group numbers (reflecting the ordering of capturing
                        parentheses with the regular expression) to string segments: a string segment
                        is a contiguous substring of the input string being matched, characterized
                        by the position of the first and last characters of the substring within the input. 
                        The current captured groups are accessible to applications using 
                        the <function>regex-groups</function> and <function>regex-group</function> 
                        functions: see <specref ref="func-regex-group"/>.</p></item><item><p>The <termref def="dt-output-state">output state</termref>: this is a flag
                        whose two possible values are <termref def="dt-final-output-state">final
                           output state</termref> and <termref def="dt-temporary-output-state">temporary output state</termref>.  The initial setting when the stylesheet is invoked by executing a
                           template is <termref def="dt-final-output-state">final output
                           state</termref>, and it is switched to <termref def="dt-temporary-output-state">temporary output state</termref> by
                        instructions such as <elcode>xsl:variable</elcode>. For more details, see
                           <specref ref="result-document-restrictions"/>.</p></item><item><p>The <termref def="dt-current-output-uri">current output URI</termref>: this
                        is the URI associated with the result tree to which instructions are
                        currently writing. The current output URI is initially the same as the
                           <termref def="dt-base-output-uri"/>. During the evaluation of an
                           <elcode>xsl:result-document</elcode> instruction, the current output URI
                        is set to the absolute URI identified by the <code nobreak="false">href</code> attribute of
                        that instruction.</p></item></ulist><p>The following non-normative table summarizes the initial state of each of the
                  components in the evaluation context, and the instructions which cause the state
                  of the component to change.</p><table class="data" border="1" cellpadding="5" width="100%"><caption>Components of the Dynamic Evaluation Context</caption><thead><tr><th align="left" rowspan="1" colspan="1" valign="top">Component</th><th align="left" rowspan="1" colspan="1" valign="top">Initial Setting</th><th align="left" rowspan="1" colspan="1" valign="top">Set by</th><th align="left" rowspan="1" colspan="1" valign="top">Cleared by</th></tr></thead><tbody><tr><td valign="top" rowspan="1" colspan="1" align="left">
                           <termref def="dt-focus">focus</termref>
                        </td><td valign="top" rowspan="1" colspan="1" align="left">See <specref ref="initiating"/>.</td><td valign="top" rowspan="1" colspan="1" align="left">
                           <elcode>xsl:apply-templates</elcode>, <elcode>xsl:for-each</elcode>,
                              <elcode>xsl:for-each-group</elcode>,
                              <elcode>xsl:analyze-string</elcode>, evaluation of <termref def="dt-pattern">patterns</termref>
                        </td><td valign="top" rowspan="1" colspan="1" align="left">Calls to <termref def="dt-stylesheet-function">stylesheet
                              functions</termref>
                        </td></tr><tr><td valign="top" rowspan="1" colspan="1" align="left">
                           <termref def="dt-current-template-rule">current template rule</termref>
                        </td><td valign="top" rowspan="1" colspan="1" align="left">If apply-templates invocation is used
                           (see <specref ref="invoking-initial-mode"/>), then for each item in the 
                           <termref def="dt-initial-match-selection"/>, the <termref def="dt-current-template-rule"/>
                           is initially set to the template rule chosen for processing that item. Otherwise,
                           <termref def="dt-absent"/>.
                        </td><td valign="top" rowspan="1" colspan="1" align="left">
                           <elcode>xsl:apply-templates</elcode>, <elcode>xsl:apply-imports</elcode>,
                              <elcode>xsl:next-match</elcode>
                        </td><td valign="top" rowspan="1" colspan="1" align="left">See <specref ref="apply-imports"/>.
                           </td></tr><tr><td valign="top" rowspan="1" colspan="1" align="left">
                           <termref def="dt-current-mode">current mode</termref>
                        </td><td valign="top" rowspan="1" colspan="1" align="left">the initial <termref def="dt-mode">mode</termref>
                        </td><td valign="top" rowspan="1" colspan="1" align="left">
                           <elcode>xsl:apply-templates</elcode>
                        </td><td valign="top" rowspan="1" colspan="1" align="left">Calls to <termref def="dt-stylesheet-function">stylesheet
                              functions</termref>. Also cleared while evaluating global
                           variables and stylesheet parameters, <termref def="dt-pattern">patterns</termref>, and the sequence
                           constructor contained in <elcode>xsl:key</elcode> or
                              <elcode>xsl:sort</elcode>. Clearing the current mode causes the
                           current mode to be set to the default (unnamed) mode.</td></tr><tr><td valign="top" rowspan="1" colspan="1" align="left">
                           <termref def="dt-current-group">current group</termref>
                        </td><td valign="top" rowspan="1" colspan="1" align="left">absent</td><td valign="top" rowspan="1" colspan="1" align="left">
                           <elcode>xsl:for-each-group</elcode>
                        </td><td valign="top" rowspan="1" colspan="1" align="left">See <specref ref="func-current-group"/>.</td></tr><tr><td valign="top" rowspan="1" colspan="1" align="left">
                           <termref def="dt-current-grouping-key">current grouping key</termref>
                        </td><td valign="top" rowspan="1" colspan="1" align="left">absent</td><td valign="top" rowspan="1" colspan="1" align="left">
                           <elcode>xsl:for-each-group</elcode>
                        </td><td valign="top" rowspan="1" colspan="1" align="left">See <specref ref="func-current-grouping-key"/>.</td></tr><tr><td valign="top" rowspan="1" colspan="1" align="left">
                           <termref def="dt-current-merge-group">current merge group</termref>
                        </td><td valign="top" rowspan="1" colspan="1" align="left">absent</td><td valign="top" rowspan="1" colspan="1" align="left">
                           <elcode>xsl:merge</elcode>
                        </td><td valign="top" rowspan="1" colspan="1" align="left">See <specref ref="func-current-merge-group"/>.</td></tr><tr><td valign="top" rowspan="1" colspan="1" align="left">
                           <termref def="dt-current-merge-key">current merge key</termref>
                        </td><td valign="top" rowspan="1" colspan="1" align="left"><phrase>absent</phrase></td><td valign="top" rowspan="1" colspan="1" align="left">
                           <elcode>xsl:merge</elcode>
                        </td><td valign="top" rowspan="1" colspan="1" align="left">See <specref ref="func-current-merge-key"/> and
                           <specref ref="func-current-merge-key-array"/>.</td></tr><tr><td valign="top" rowspan="1" colspan="1" align="left">
                           <termref def="dt-current-captured-groups">current captured
                              substrings</termref>
                        </td><td valign="top" rowspan="1" colspan="1" align="left">empty sequence</td><td valign="top" rowspan="1" colspan="1" align="left">
                           <elcode>xsl:matching-substring</elcode>
                        </td><td valign="top" rowspan="1" colspan="1" align="left">
                           <elcode>xsl:non-matching-substring</elcode>; Calls to <termref def="dt-stylesheet-function">stylesheet functions</termref>, dynamic function calls,
                              evaluation of global variables, stylesheet
                              parameters, and <termref def="dt-pattern">patterns</termref>
                        </td></tr><tr><td valign="top" rowspan="1" colspan="1" align="left">
                           <termref def="dt-output-state">output state</termref>
                        </td><td valign="top" rowspan="1" colspan="1" align="left">
                           <termref def="dt-final-output-state">final output state</termref>
                        </td><td valign="top" rowspan="1" colspan="1" align="left">Set to <termref def="dt-temporary-output-state">temporary
                              output state</termref> by instructions such as
                              <elcode>xsl:variable</elcode>, <elcode>xsl:attribute</elcode>, etc.,
                           and by calls on <termref def="dt-stylesheet-function">stylesheet
                              functions</termref>
                        </td><td valign="top" rowspan="1" colspan="1" align="left">None</td></tr><tr><td valign="top" rowspan="1" colspan="1" align="left">
                           <termref def="dt-current-output-uri">current output URI</termref>
                        </td><td valign="top" rowspan="1" colspan="1" align="left">
                           <termref def="dt-base-output-uri">base output URI</termref>
                        </td><td valign="top" rowspan="1" colspan="1" align="left"><elcode>xsl:result-document</elcode></td><td valign="top" rowspan="1" colspan="1" align="left">Calls to <termref def="dt-stylesheet-function">stylesheet
                              functions</termref>, dynamic function calls, evaluation of <termref def="dt-global-variable">global variables</termref>, <termref def="dt-stylesheet-parameter">stylesheet parameters</termref>, and
                              <termref def="dt-pattern">patterns</termref>.</td></tr></tbody></table><p><termdef id="dt-initial-setting" term="initial setting">The <term>initial setting</term> of a component of the dynamic context is used
                     when evaluating <termref def="dt-global-variable">global variables</termref>
                     and <termref def="dt-stylesheet-parameter">stylesheet parameters</termref>,
                     when evaluating the <code nobreak="false">use</code> and <code nobreak="false">match</code> attributes of
                        <elcode>xsl:key</elcode>, and when evaluating the <code nobreak="false">initial-value</code> of
                        <elcode>xsl:accumulator</elcode> and the <code nobreak="false">select</code> expressions or
                     contained sequence constructors of
                     <elcode>xsl:accumulator-rule</elcode></termdef>.</p><p><termdef id="dt-non-contextual-function-call" term="non-contextual function call">The term <term>non-contextual function
                        call</term> is used to refer to function calls that do not pass the dynamic
                     context to the called function. This includes all calls on <termref def="dt-stylesheet-function">stylesheet functions</termref> and all
                        <xtermref spec="XP40" ref="dt-dynamic-function-call">dynamic function
                        calls</xtermref>, (that is calls to function items). It excludes calls to some
                        functions in the namespace
                           <code nobreak="false">http://www.w3.org/2005/xpath-functions</code>, in
                     particular those that explicitly depend on the context, such as the
                        <function>current-group</function> and <function>regex-group</function>
                     functions. It is <termref def="dt-implementation-defined">implementation-defined</termref> whether, and under what circumstances,
                     calls to <termref def="dt-extension-function">extension functions</termref> are
                     non-contextual.</termdef></p><imp-def-feature id="id-ext-accesstoconttext">The availability of dynamic context
                  information within <termref def="dt-extension-function">extension
                     functions</termref> is <termref def="dt-implementation-defined">implementation-defined</termref>.</imp-def-feature><p>Named function references (such as <code nobreak="false">position#0</code>) and
                  calls on <xfunction>function-lookup</xfunction> (for example,
                     <code nobreak="false">function-lookup("position", 0)</code>) are defined to retain the XPath
                  static and dynamic context at the point of invocation as part of the closure of
                  the resulting function item, and to use this preserved context when a dynamic
                  function call is subsequently made using the function item. In XSLT 4.0 this rule 
                  extends to the XSLT extensions to the dynamic context defined in this section. 
                  For example the call <code nobreak="false">regex-group#1</code>) delivers a function item that holds a snapshot
                  of the <xtermref spec="FO40" ref="dt-current-captured-substrings"/> in its closure, and subsequent
                  evaluation of that function item will return the relevant value from that snapshot.</p></div3></div2><div2 id="named-types"><head>Named Types</head><p>XSLT 4.0 introduces two new and closely-related constructs allowing item
            types to be given names, and to be referred to by name anywhere that item types
            are used, for example in function declarations and variable declarations.</p><p>The <elcode>xsl:item-type</elcode> declaration allows any item type to be given
            a name. It is particularly useful to avoid repetitive use of the same choice types,
            enumeration types, or function types, and means that if the definition changes, the change only
            needs to be made in one place.</p><p>The <elcode>xsl:record-type</elcode> declaration takes this a step further.
            Like <elcode>xsl:item-type</elcode>, it allows a name to be given to any
            record type. In addition, though, it offers two further capabilities:</p><ulist><item><p>Named record types can be recursive, allowing definitions of
               recursive data structures such as lists and trees.</p></item><item><p>Declaring a named record type automatically establishes
               a constructor function for records of that type; the constructor
               function has the same name as the record type itself.</p></item></ulist><div3 id="named-item-types"><head>Named Item Types</head><changes><change date="2022-01-01" issue="1606" PR="1617">
                     Named item types can be declared using the new <elcode>xsl:item-type</elcode>
                     element. This is designed to avoid repeating lengthy type definitions (for example
                     function types) every time they are used.
                  </change></changes><e:element-syntax xmlns:e="http://www.w3.org/1999/XSL/Spec/ElementSyntax" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" name="item-type">
      <e:in-category name="declaration"/>
      <e:attribute name="name" required="yes">
         <e:data-type name="eqname"/>
      </e:attribute>
      <e:attribute name="as" default="'item()*'">
         <e:data-type name="item-type"/>
      </e:attribute>
      <e:attribute name="visibility" default="'private'">
         <e:constant value="private"/>
         <e:constant value="public"/>
      </e:attribute>
      <e:empty/>
      <e:allowed-parents>
         <e:parent name="package"/>
         <e:parent name="stylesheet"/>
         <e:parent name="transform"/>
      </e:allowed-parents>
   </e:element-syntax><p>An <elcode>xsl:item-type</elcode> declaration associates a name with an item type, and allows the type
               to be referenced by name throughout the stylesheet package.</p><example id="e-item-type-colors"><p>The following example declares a named item type for colors, and uses it in three variable
                     declarations and a function declaration.</p><eg xml:space="preserve">&lt;xsl:item-type name="my:color" as="enum('red', 'green', 'blue')"/&gt;
   
&lt;xsl:variable name="RED" as="my:color" select="'red'"/&gt;
&lt;xsl:variable name="GREEN" as="my:color" select="'green'"/&gt;
&lt;xsl:variable name="BLUE" as="my:color" select="'blue'"/&gt;

&lt;xsl:function name="my:html-color" as="xs:string"&gt;
  &lt;xsl:param name="color" as="my:color"/&gt;
  &lt;xsl:switch select="$color"&gt;
    &lt;xsl:when test="$RED"&gt;#FF0000&lt;/xsl:when&gt;
    &lt;xsl:when test="$GREEN"&gt;#008000&lt;/xsl:when&gt;
    &lt;xsl:when test="$BLUE"&gt;#0000FF&lt;/xsl:when&gt;
  &lt;/xsl:switch&gt;
&lt;/xsl:function&gt;
                     </eg></example><example id="e-item-type-colors"><p>The following example declares a named choice type for the two binary
                     types <code nobreak="false">xs:hexBinary</code> and <code nobreak="false">xs:base64Binary</code>
                     and uses it in a function declaration that compares two such values
                     for equality.</p><eg xml:space="preserve">&lt;xsl:item-type name="my:binary" as="(xs:hexBinary | xs:base64Binary)"/&gt;

&lt;xsl:function name="my:binary-equal" as="xs:boolean"&gt;
  &lt;xsl:param name="x" as="my:binary"/&gt;
  &lt;xsl:param name="y" as="my:binary"/&gt;
  &lt;xsl:sequence select="$x eq $y"/&gt;
&lt;/xsl:function&gt;
                     </eg></example><p>Using named item types makes the stylesheet more readable, and improves potential for change: a change
               to the set of colors allowed by the type <code nobreak="false">my:color</code> is less likely to affect users of a function
               library. However, named item types do not provide true encapsulation or information hiding; users of the 
               function library can still treat enumeration values as simple strings if they wish.</p><p>The <elcode>xsl:item-type</elcode> declaration adds an entry to the 
                  <xtermref spec="XP40" ref="dt-in-scope-named-item-types"/>
               component of the static context for XPath expressions, and also becomes available for use wherever
               XSLT allows an <code nobreak="false">ItemType</code> to appear.</p><p>The scope of a named item type is the <termref def="dt-package"/> in which it is declared. If it
               is declared with <code nobreak="false">visibility="public"</code> then it also becomes available for use in using
               packages. (Since there is no mechanism for the using package to override the definition,
               <code nobreak="false">public</code> effectively means <code nobreak="false">final</code>.)</p><p>A named item type is essentially an abbreviation for the item type designator appearing in the
               <code nobreak="false">as</code> attribute, and the semantics can be defined in terms of textual replacement
               of the name by its definition. In consequence, named item types cannot be recursive, since
               this would make the textual expansion non-terminating.</p><p>The name of the item type is the expanded name formed by resolving the <code nobreak="false">name</code> attribute.
               A lexical QName with no prefix is treated as being in the 
               <xtermref spec="XP40" ref="dt-default-namespace-elements-and-types"/>.</p><p>If two <elcode>xsl:item-type</elcode> declarations in a <termref def="dt-package"/> have the same
               name, then the one with higher <termref def="dt-import-precedence"/> is used. </p><p><error spec="XT" type="static" class="SE" code="4030"><p>It is a <termref def="dt-static-error">static error</termref> if a package contains two 
                     <elcode>xsl:item-type</elcode> or <elcode>xsl:record-type</elcode>
                     declarations having the same name and the same <termref def="dt-import-precedence">import
                        precedence</termref>, unless there is another definition with the same
                     name and higher import precedence. It is also a static error if the name
                  of the item type uses a <termref def="dt-reserved-namespace"/>, or if it has the same
                  name as a type in the <xtermref spec="XP40" ref="dt-is-types">in-scope schema types</xtermref> of
                  the static context.</p></error></p><p><error spec="XT" type="static" class="SE" code="4035"><p>It is a <termref def="dt-static-error">static error</termref> for an item type named
                     <var>N</var> to contain in its <code nobreak="false">as</code> attribute a reference to <var>N</var>,
                     or to an item type that references <var>N</var> directly or indirectly.</p></error></p><p>It is permissible to use a private named item type in the declaration of a public
               variable, function, or template. A package that uses (or overrides) such a component
               will not be able to use the type name, but it can use the underlying type definition,
               or provide its own declaration of the relevant item type, using the same name or
               a different name.</p></div3><div3 id="named-record-types"><head>Named Record Types</head><changes><change issue="1485" PR="1708" date="2025-01-16">
                     Named record types are introduced.
                  </change></changes><e:element-syntax xmlns:e="http://www.w3.org/1999/XSL/Spec/ElementSyntax" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" name="record-type">
      <e:in-category name="declaration"/>
      <e:attribute name="name" required="yes">
         <e:data-type name="eqname"/>
      </e:attribute>
      <e:attribute name="constructor" default="'no'">
         <e:data-type name="boolean"/>
      </e:attribute>
      <e:attribute name="extensible" default="'no'">
         <e:data-type name="boolean"/>
      </e:attribute>
      <e:attribute name="visibility" default="'private'">
         <e:constant value="private"/>
         <e:constant value="public"/>
      </e:attribute>
      <e:sequence>
         <e:element repeat="zero-or-more" name="field"/>
      </e:sequence>
      <e:allowed-parents>
         <e:parent name="package"/>
         <e:parent name="stylesheet"/>
         <e:parent name="transform"/>
      </e:allowed-parents>
   </e:element-syntax><e:element-syntax xmlns:e="http://www.w3.org/1999/XSL/Spec/ElementSyntax" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" name="field">
      <e:attribute name="name" required="yes">
         <e:data-type name="ncname"/>
      </e:attribute>
      <e:attribute name="as" default="'item()*'">
         <e:data-type name="sequence-type"/>
      </e:attribute>
      <e:attribute name="required" default="'yes'">
         <e:data-type name="boolean"/>
      </e:attribute>
      <e:attribute name="default">
         <e:data-type name="expression"/>
      </e:attribute>
      <e:empty/>
      <e:allowed-parents>
         <e:parent name="record-type"/>
      </e:allowed-parents>
   </e:element-syntax><p>An <elcode>xsl:record-type</elcode> declaration associates a name 
                  with a record type, and allows the record type
                  to be referenced by name throughout the stylesheet package.</p><example id="e-item-type-complex"><p>The following example declares a named record type for complex numbers, 
                     and uses it in a variable
                     declaration and a function declaration.</p><eg xml:space="preserve">&lt;xsl:record-type name="cx:complex"&gt;
    &lt;xsl:field name="r" as="xs:double"/&gt;
    &lt;xsl:field name="i" as="xs:double"/&gt;
&lt;/xsl:record-type&gt;
   
&lt;xsl:variable name="i" as="cx:complex" select="cx:complex(0, 1)"/&gt;
   
&lt;xsl:function name="cx:add" as="cx:complex"&gt;
  &lt;xsl:param name="x" as="cx:complex"/&gt;
  &lt;xsl:param name="y" as="cx:complex"/&gt;
  &lt;xsl:sequence select="cx:complex($x?r + $y?r, $x?i + $y?i)"/&gt;
&lt;/xsl:function&gt;
</eg><p>Note how the record type declaration has implicitly declared a constructor function
                     <code nobreak="false">cx:complex</code> that can be used to create instances of the item type.</p></example><p><error spec="XT" class="SE" code="4050" type="static"><p>It is a <termref def="dt-static-error"/> 
                     if the names of the fields in an <elcode>xsl:record-type</elcode>
                     declaration are not distinct.</p></error></p><p><error spec="XT" class="SE" code="4051" type="static"><p>It is a <termref def="dt-static-error"/> 
                     if an <elcode>xsl:field</elcode> element has a <code nobreak="false">default</code>
                     attribute unless it specifies <code nobreak="false">required="no"</code>.</p></error></p><p>An <elcode>xsl:record-type</elcode> declaration has two effects:</p><ulist><item><p>In the same way as <elcode>xsl:item-type</elcode>, it defines
                  a named item type in the static context, allowing the record type to
                  be referenced by name anywhere an <code nobreak="false">ItemType</code> can appear,
                  for example in the declarations of functions and variables. Unlike
                  types declared in <elcode>xsl:item-type</elcode>, however,
                  named record types can be recursive.</p></item><item><p>An <elcode>xsl:record-type</elcode> declaration also
                  implicitly defines a constructor function, of the same name,
                  and adds this to the set of 
                  <xtermref spec="XP40" ref="dt-statically-known-function-definitions"/>
                  in the static context.</p></item></ulist><p>Because of its dual role, the name of an <elcode>xsl:record-type</elcode>
               declaration must be valid both as an item type name and as a function name.
               This means the name must be distinct from other type names and function names
               in the static context. It also means that the name must be in a namespace.</p><p>Considered as an item type, the <elcode>xsl:record-type</elcode>
               declaration is equivalent to an <elcode>xsl:item-type</elcode> declaration
               formed by the following template rule, evaluated in the context of 
               a namespace alias <code nobreak="false">&lt;xsl:namespace-alias stylesheet-prefix="t"
               result-prefix="xsl"/&gt;</code>:</p><eg xml:space="preserve">&lt;xsl:template match="xsl:record-type" expand-text="yes"&gt;
   &lt;t:item-type name="{@name}"
                visibility="{@visibility otherwise 'private'}"&gt;
     &lt;xsl:attribute name="as"&gt;
        &lt;xsl:text&gt;record(&lt;/xsl:text&gt;
        &lt;xsl:for-each select="xsl:field" separator=", "&gt;
           &lt;xsl:variable name="optional"
                         as="xs:boolean"
                         select="normalize-space(@required) = ('no','false','0')"/&gt;
           {@name}{'?'[$optional]} as {@as otherwise 'item()*'}
        &lt;/xsl:for-each&gt;
        &lt;xsl:text&gt;)&lt;/xsl:text&gt;
      &lt;/xsl:attribute&gt;  
   &lt;/t:item-type&gt;
&lt;/xsl:template&gt;   
</eg><p>This generated <elcode>xsl:item-type</elcode> declaration must
               meet all the constraints placed on user-written 
               <elcode>xsl:item-type</elcode> declarations, including the rule
               requiring names to be unique, but not including the rule
               disallowing recursive references.</p><p>For example, the declaration:</p><eg xml:space="preserve">&lt;xsl:record-type name="cx:complex"&gt;
    &lt;xsl:field name="r" as="xs:double"/&gt;
    &lt;xsl:field name="i" as="xs:double" required="no" default="0"/&gt;
&lt;/xsl:record-type&gt;</eg><p>produces the equivalent item type declaration:</p><eg xml:space="preserve">&lt;xsl:item-type name="cx:complex"
       as="record(r as xs:double, i? as xs:double)"/&gt;</eg><p>Considered as a function declaration, an <elcode>xsl:record-type</elcode>
               declaration is equivalent to an <elcode>xsl:function</elcode> declaration
               formed by the following template rule, evaluated in the context of 
               a namespace alias <code nobreak="false">&lt;xsl:namespace-alias stylesheet-prefix="t"
               result-prefix="xsl"/&gt;</code>:</p><eg xml:space="preserve">&lt;xsl:template match="xsl:record-type"&gt;
    &lt;t:function name="{@name}"
                as="{@name}"
                visibility="{(@visibility otherwise 'private')}"&gt;
                
             
      
      &lt;!-- declare the parameters --&gt;
      &lt;xsl:for-each select="xsl:field"&gt;
         &lt;t:param name="{@name}"
                  required="{@required otherwise 'yes'}"&gt;
            &lt;xsl:attribute name="as"&gt;
               &lt;xsl:variable name="as" 
                             select="normalize-space(@as otherwise 'item()*')"/&gt;
               &lt;xsl:variable name="optional" 
                             select="normalize-space(@required) = ('no', 'false', '0')"/&gt;
               &lt;xsl:choose&gt;
                  &lt;xsl:when test="not($optional)" select="$as"/&gt;
                  &lt;!-- for optional fields, amend the required type to allow () --&gt;
                  &lt;xsl:when test="matches($as, '[?*]$')" select="$as"/&gt;
                  &lt;xsl:when test="matches($as, '\+$')" select="replace($as, '\+$', '*')"/&gt;
                  &lt;xsl:otherwise select="$as || '?'"/&gt;
               &lt;/xsl:choose&gt;
            &lt;/xsl:attribute&gt;
            &lt;xsl:if test="@default"&gt;
               &lt;xsl:attribute name="select" select="@default"/&gt;
            &lt;/xsl:if&gt;   
         &lt;/t:param&gt;
      &lt;/xsl:for-each&gt;
      
        
      
      &lt;!-- function body: construct a map --&gt;
      &lt;t:map duplicates="fn($first, $second){{$first}}"&gt;
         &lt;xsl:for-each select="xsl:field"&gt;
            &lt;xsl:variable name="optional" 
                          select="normalize-space(@required) = ('no', 'false', '0')"/&gt;
            &lt;xsl:choose&gt;
              &lt;xsl:when test="$optional and not(@default)"&gt;
                 &lt;!-- omit map entries for optional fields if no value is supplied --&gt;
                 &lt;t:if test="exists(${@name})"&gt;
                    &lt;t:map-entry key="'{@name}'" select="${@name}"/&gt;
                 &lt;/t:if&gt;
              &lt;/xsl:when&gt;
              &lt;xsl:otherwise&gt;
                &lt;t:map-entry key="'{@name}'" select="${@name}"/&gt;
              &lt;/xsl:otherwise&gt;  
            &lt;/xsl:choose&gt;  
         &lt;/xsl:for-each&gt;
        


      &lt;/t:map&gt;
    &lt;/t:function&gt;          
&lt;/xsl:template&gt;</eg><p>For example, the declaration:</p><eg xml:space="preserve">&lt;xsl:record-type name="cx:complex"&gt;
    &lt;xsl:field name="r" as="xs:double"/&gt;
    &lt;xsl:field name="i" as="xs:double" required="no" default="0"/&gt;
&lt;/xsl:record-type&gt;</eg><p>produces the equivalent function declaration:</p><eg xml:space="preserve">&lt;xsl:function name="cx:complex" as="cx:complex" visibility="private"&gt;
    &lt;xsl:param name="r" as="xs:double"/&gt;
    &lt;xsl:param name="i" as="xs:double" required="no" select="0"/&gt;
    &lt;xsl:map&gt;
       &lt;xsl:map-entry key="'r'" select="$r"/&gt;
       &lt;xsl:map-entry key="'i'" select="$i"/&gt;
    &lt;/xsl:map&gt;
&lt;/xsl:function&gt;</eg><p>No entry is generated in the constructed map for a field that
               is declared as optional with no default. So the declaration:</p><eg xml:space="preserve">&lt;xsl:record-type name="cx:complex" visibility="public"&gt;
    &lt;xsl:field name="r" as="xs:double"/&gt;
    &lt;xsl:field name="i" as="xs:double" required="no"/&gt;
&lt;/xsl:record-type&gt;</eg><p>produces the equivalent function declaration:</p><eg xml:space="preserve">&lt;xsl:function name="cx:complex" as="cx:complex" visibility="public"&gt;
    &lt;xsl:param name="r" as="xs:double"/&gt;
    &lt;xsl:param name="i" as="xs:double?" required="no"/&gt;
    &lt;xsl:map&gt;
       &lt;xsl:map-entry key="'r'" select="$r"/&gt;
       &lt;xsl:if test="exists($i)"&gt;
          &lt;xsl:map-entry key="'i'" select="$i"/&gt;
       &lt;/xsl:if&gt;   
    &lt;/xsl:map&gt;
&lt;/xsl:function&gt;</eg><p>This generated <elcode>xsl:function</elcode> declaration must
               meet all the constraints placed on user-written 
               <elcode>xsl:function</elcode> declarations, including the rule
               requiring the combination of name and arity to be unique.</p><p>The generated <elcode>xsl:function</elcode> declaration has the
               import precedence associated with the stylesheet module in which the
               <elcode>xsl:record-type</elcode> declaration appears, and it may be
               overridden by another <elcode>xsl:function</elcode> declaration with
               higher import precedence. If the visibility is <code nobreak="false">public</code>
               then it can also be overridden using <elcode>xsl:override</elcode>
               in another <termref def="dt-package"/>.</p><p>The scope of a named record type is the <termref def="dt-package"/> in which it is declared. If it
               is declared with <code nobreak="false">visibility="public"</code> then it also becomes available for use in using
               packages. </p><p>The name of the record type is the expanded name formed by resolving the <code nobreak="false">name</code> attribute.
               Because function names are always in a namespace, the name must be prefixed.</p><p>If two <elcode>xsl:record-type</elcode> declarations in a <termref def="dt-package"/> have the same
               name, then the one with higher <termref def="dt-import-precedence"/> is used. </p><p>A record type declaration may refer directly or indirectly to itself if
                  it satisfies the conditions defined in <xspecref spec="XP40" ref="id-recursive-record-tests"/>.
               This allows types to be declared that match recursive data structures such as linked lists
               and trees.</p><p>A named record type with visibility <code nobreak="false">private</code> may be used in the definition of a 
                  component (such as a variable, a function, a template, or another named record 
                  type) that is itself public. Another package may reference such a component 
                  even though it cannot reference the types used in its definition. The fact that the
                  record type is private, however, means that it is impossible to
                  override a variable or function that references the record type.</p><example><head>Defining a Binary Tree</head><p>This example illustrates the definition of a recursive record type.
                  The record type represents a node of a binary tree containing a payload value
                  in each node, together with optional references to left and right subtrees.
                  As well as the data fields, the record type defines a <code nobreak="false">depth</code> function 
                  that returns the maximum depth of the tree, by making recursive calls on its
                  subtrees.</p><eg xml:space="preserve">&lt;xsl:record-type name="my:binary-tree"&gt;
   &lt;xsl:field name="left" as="my:binary-tree?"/&gt;
   &lt;xsl:field name="payload" as="item()*"/&gt;
   &lt;xsl:field name="right" as="my:binary-tree?"/&gt;
   &lt;xsl:field name="depth" as="fn(my:binary-tree) as xs:integer"
      default="fn {1 + max((?left =?&gt; depth(), ?right =?&gt; depth())) otherwise 0)}"/&gt;
&lt;/xsl:record-type&gt;</eg><p>Method calls (using the operator <code nobreak="false">=?&gt;</code>) are described in
                     <xspecref spec="XP40" ref="id-methods"/>. The effect is to
                     give a function item contained in a map access to the containing
                     map.
                  They thus mimic method invocation in object-oriented languages, though
                  there is no inheritance or encapsulation.</p><p>The following code builds a simple tree and calculates its depth:</p><eg xml:space="preserve">
let $tree := my:binary-tree(
               my:binary-tree((), 17, ()),
               18,
               my:binary-tree((), 19, 
                 my:binary-tree((), 20, ())))
return $tree =?&gt; depth()</eg><p>Returning the result 3.</p></example><p>A more detailed example that uses a recursive named record type
               appears in the following section.</p></div3><div3 id="id-atomic-set-example"><head>Example: Defining an Atomic Set</head><p>This example demonstrates a library package that provides a new data type
               to manipulate sets of atomic items.</p><p>A stylesheet that incorporates this package (by referencing
               it in an <elcode>xsl:use-package</elcode> declaration) can use constructs such as:</p><ulist><item><p>
                     <eg xml:space="preserve">&lt;xsl:variable name="empty" 
       as="set:atomic-set"
       select="set:build(())"/&gt;</eg>
                  </p></item><item><p>
                     <eg xml:space="preserve">&lt;xsl:variable name="evens"
      as="set:atomic-set"                        
      select="set:build((1 to 100)[. mod 2 = 0])"/&gt;</eg>
                  </p></item><item><p>
                     <eg xml:space="preserve">&lt;xsl:variable name="odds"
      as="set:atomic-set"
      select="set:build((1 to 100)) ? except($evens)"/&gt;</eg>
                  </p></item><item><p>
                     <eg xml:space="preserve">&lt;xsl:function name="my:is-even" as="xs:boolean"&gt;
   &lt;xsl:param name="n" as="xs:integer"/&gt;
   &lt;xsl:sequence select="$evens ? contains($n)"/&gt;
&lt;/xsl:function&gt;</eg>
                  </p></item></ulist><p>Here is the implementation of the package.</p><eg xml:space="preserve">
&lt;xsl:package name="http://qt4cg.org/atomic-set"
             package-version="1.0.0"
             xmlns:set="http://qt4cg.org/atomic-set"
             xmlns:map="http://www.w3.org/2005/xpath-functions/map"
             xmlns:xs="http://www.w3.org/2001/XMLSchema"&gt;
   
   &lt;xsl:note&gt;
      This package defines a type set:atomic-set which represents
      a set of distinct atomic items. Atomic items are considered
      distinct based on the comparison function fn:atomic-equal.
      
      An instance of an atomic set can be constructed using a function
      call such as set:build((1, 3, 5, 7, 9)).
      
      If $A and $B are instances of set:atomic-set, then they
      can be manipulated using methods including:
      
      $A =?&gt; size() - returns the number of items in the set
      $A =?&gt; empty() - returns true if the set is empty
      $A =?&gt; contains($k) - determines whether $k is a member of the set
      $A =?&gt; contains-all($B) - returns true if $B is a subset of $A
      $A =?&gt; values() - returns the items in $A, as a sequence
      $A =?&gt; add($k) - returns a new atomic set containing an additional item
      $A =?&gt; remove($k) - returns a new atomic set in which the given item is absent
      $A =?&gt; union($B) - returns a new atomic set holding the union of $A and $B
      $A =?&gt; intersect($B) - returns a new atomic set holding the intersection of $A and $B
      $A =?&gt; except($B) - returns a new atomic set holding the difference of $A and $B
   &lt;/xsl:note&gt;
   
   &lt;xsl:record-type name="set:atomic-set" 
                    visibility="public"&gt;
      &lt;xsl:field name="_data" 
                 as="map(xs:anyAtomicType, xs:boolean)"/&gt;
      &lt;xsl:field name="size" 
                 as="fn(set:atomic-set) as xs:integer"/&gt;
      &lt;xsl:field name="empty" 
                 as="fn(set:atomic-set) as xs:boolean"/&gt;
      &lt;xsl:field name="contains" 
                 as="fn(set:atomic-set, xs:anyAtomicType) as xs:boolean"/&gt; 
      &lt;xsl:field name="contains-all" 
                 as="fn(set:atomic-set, set:atomic-set) as xs:boolean"/&gt; 
      &lt;xsl:field name="add" 
                 as="fn(set:atomic-set, xs:anyAtomicType) as set:atomic-set"/&gt; 
      &lt;xsl:field name="remove" 
                 as="fn(set:atomic-set, xs:anyAtomicType) as set:atomic-set"/&gt;
      &lt;xsl:field name="union" 
                 as="fn(set:atomic-set, set:atomic-set) as set:atomic-set"/&gt;
      &lt;xsl:field name="intersect" 
                 as="fn(set:atomic-set, set:atomic-set) as set:atomic-set"/&gt; 
      &lt;xsl:field name="except" 
                 as="fn(set:atomic-set, set:atomic-set) as set:atomic-set"/&gt; 
   &lt;/xsl:record-type&gt;
   
   &lt;xsl:variable name="DATA" select="'_data'" visibility="private"/&gt;
   
   &lt;xsl:note&gt;
      The private function set:replaceData processes the internal map
      by applying a supplied function, and returns a new atomic set
      with the resulting internal map 
   &lt;/xsl:note&gt;
   
   &lt;xsl:function name="set:replaceData" 
                 visibility="private" 
                 as="map(xs:anyAtomicType, xs:boolean)"&gt;
      &lt;xsl:param name="input" as="set:atomic-set"/&gt;
      &lt;xsl:param name="update" as="fn(map(*)) as map(*)"/&gt;
      &lt;xsl:sequence select="map:put($input, $DATA, $update($input?$DATA))"/&gt;
   &lt;/xsl:function&gt;   
   
   &lt;xsl:function name="set:build" as="set:atomic-set" visibility="public"&gt;
      &lt;xsl:param name="values" as="xs:anyAtomicType*" default="()"/&gt;
      &lt;xsl:record as="set:atomic-set"
         _data=
            "map:build($values, values:=true#0, {'duplicates': 'use-first'})"
         size=
            "fn($this as set:atomic-set) as xs:integer 
                     { map:size($this?$DATA) }"
         empty=
            "fn($this as set:atomic-set) as xs:boolean 
                     { map:empty($this?$DATA) }"
         contains=
            "fn($this as set:atomic-set, $value as xs:anyAtomicType) as xs:boolean 
                     { map:contains($this?$DATA, $value) }"
         contains-all=
            "fn($this as set:atomic-set, $other as set:atomic-set) as xs:boolean 
                     { every($other, map:contains($this?$DATA, ?)) }"
         values=
            "fn($this as set:atomic-set) as xs:anyAtomicType* 
                     { keys($this?$DATA) }"
         add=
            "fn($this as set:atomic-set, $value as xs:anyAtomicType) as xs:anyAtomicType*
                     { set:replaceData($this, map:put(?, $value, true())) }"
         remove=
            "fn($this as set:atomic-set, $value as xs:anyAtomicType) as xs:anyAtomicType* 
                     { set:replaceData($this, map:remove(?, $value)) }"
         union=
            "fn($this as set:atomic-set, $other as set:atomic-set) as set:atomic-set 
                     { set:replaceData($this, fn($m) {map:merge(($m, $other?$DATA),
                                                    {'duplicates': 'use-first'})})
                     }"
         intersect=
            "fn($this as set:atomic-set, $other as set:atomic-set) as set:atomic-set 
                     { set:replaceData($this, map:filter(?, $other?contains)) }"
         except=
            "fn($this as set:atomic-set, $other as set:atomic-set) as set:atomic-set 
                     { set:replaceData($this, map:remove(?, $other?values())) }"/&gt;
      
   &lt;/xsl:function&gt;
   
   
&lt;/xsl:package&gt;                  
                  </eg><ednote><edtext><p>The example is not yet tested. </p></edtext></ednote></div3></div2><div2 id="defining-decimal-format"><head>Defining a Decimal Format</head><changes><change issue="1048" PR="1250" date="2024-06-03">
                  The strings used in the formatted number to represent 
                     a decimal separator, grouping separator, exponent
                  separator, percent sign, per mille sign, or minus sign,
                  are no longer constrained to be single characters.
               </change></changes><p>The definition of the <xfunction>format-number</xfunction> function
               is now in <bibref ref="xpath-functions-40"/>. This section is a specification of
               the <elcode>xsl:decimal-format</elcode> declaration, which provides the context for
               this function when used in an XSLT stylesheet.</p><e:element-syntax xmlns:e="http://www.w3.org/1999/XSL/Spec/ElementSyntax" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" name="decimal-format">
      <e:in-category name="declaration"/>
      <e:attribute name="name">
         <e:data-type name="eqname"/>
      </e:attribute>
      <e:attribute name="decimal-separator" default="'.'">
         <e:data-type name="string"/>
      </e:attribute>
      <e:attribute name="grouping-separator" default="','">
         <e:data-type name="string"/>
      </e:attribute>
      <e:attribute name="infinity" default="'Infinity'">
         <e:data-type name="string"/>
      </e:attribute>
      <e:attribute name="minus-sign" default="'-'">
         <e:data-type name="string"/>
      </e:attribute>
      <e:attribute name="exponent-separator" default="'e'">
         <e:data-type name="string"/>
      </e:attribute>
      <e:attribute name="NaN" default="'NaN'">
         <e:data-type name="string"/>
      </e:attribute>
      <e:attribute name="percent" default="'%'">
         <e:data-type name="string"/>
      </e:attribute>
      <e:attribute name="per-mille" default="'‰'">
         <e:data-type name="string"/>
      </e:attribute>
      <e:attribute name="zero-digit" default="'0'">
         <e:data-type name="char"/>
      </e:attribute>
      <e:attribute name="digit" default="'#'">
         <e:data-type name="char"/>
      </e:attribute>
      <e:attribute name="pattern-separator" default="';'">
         <e:data-type name="char"/>
      </e:attribute>
      <e:empty/>
      <e:allowed-parents>
         <e:parent name="package"/>
         <e:parent name="stylesheet"/>
         <e:parent name="transform"/>
      </e:allowed-parents>
   </e:element-syntax><p>The <elcode>xsl:decimal-format</elcode> element sets the
               <term>statically known decimal formats</term> component of the static context
               for XPath expressions, which controls the interpretation of a <termref def="dt-picture-string">picture string</termref> used by the
               <xfunction>format-number</xfunction> function.</p><p><termdef id="dt-picture-string" term="picture string">The <term>picture string</term>
               is the string supplied as the second argument of the
               <xfunction>format-number</xfunction> function.</termdef>
            </p><p>A <termref def="dt-package">package</termref> may
               contain multiple <elcode>xsl:decimal-format</elcode> declarations and may include or
               import <termref def="dt-stylesheet-module">stylesheet modules</termref> that also
               contain <elcode>xsl:decimal-format</elcode> declarations. The name of an
               <elcode>xsl:decimal-format</elcode> declaration is the value of its
               <code nobreak="false">name</code> attribute, if any.</p><p>
               <termdef id="dt-decimal-format" term="decimal format">All the
                  <elcode>xsl:decimal-format</elcode> declarations in a package that share the same name are grouped into a named
                  <term>decimal format</term>; those that have no name are grouped into a single
                  unnamed decimal format.</termdef>
            </p><p> The attributes of the <elcode>xsl:decimal-format</elcode>
               declaration define the value of the corresponding property in the relevant decimal
               format in the <xtermref spec="XP40" ref="dt-static-decimal-formats">statically known
                  decimal formats</xtermref> component of the static context for all XPath
               expressions in the package. The attribute names used in the XSLT 4.0 syntax are the
               same as the property names used in the definition of the static context. </p><p>The scope of an <elcode>xsl:decimal-format</elcode> name is the
               package in which it is declared; the name is available for use only in calls to
               <xfunction>format-number</xfunction> that appear within the same package.</p><p>If a <termref def="dt-package">package</termref> does not contain a declaration of
               the unnamed decimal format, a declaration equivalent to an
               <elcode>xsl:decimal-format</elcode> element with no attributes is implied.</p><p>The attributes of the <elcode>xsl:decimal-format</elcode> declaration establish
               values for a number of variables used as input to the algorithm followed by the
               <xfunction>format-number</xfunction> function. An outline of the purpose of each
               attribute is given below; however, the definitive explanations are given as part of the specification of
               <xfunction>format-number</xfunction>.</p><p>For any named <termref def="dt-decimal-format">decimal format</termref>, the
               <termref def="dt-effective-value"/> of each attribute is taken from an
               <elcode>xsl:decimal-format</elcode> declaration that has that name, and that
               specifies an explicit value for the required attribute. If there is no such
               declaration, the default value of the attribute is used. If there is more than one
               such declaration, the one with highest <termref def="dt-import-precedence">import
                  precedence</termref> is used.</p><p>For any unnamed <termref def="dt-decimal-format">decimal format</termref>, the
               <termref def="dt-effective-value"/> of each attribute is taken from an
               <elcode>xsl:decimal-format</elcode> declaration that is unnamed, and that
               specifies an explicit value for the required attribute. If there is no such
               declaration, the default value of the attribute is used. If there is more than one
               such declaration, the one with highest <termref def="dt-import-precedence">import
                  precedence</termref> is used.</p><p>
               <error spec="XT" type="static" class="SE" code="1290"><p>It is a <termref def="dt-static-error">static error</termref> if a named or
                     unnamed <termref def="dt-decimal-format">decimal format</termref> contains two
                     conflicting values for the same attribute in different
                     <elcode>xsl:decimal-format</elcode> declarations having the same <termref def="dt-import-precedence">import precedence</termref>, unless there is
                     another definition of the same attribute with higher import precedence.</p></error>
            </p><p>The following attributes control the interpretation of characters in the 
               <termref def="dt-picture-string">picture string</termref> supplied to the
               <xfunction>format-number</xfunction> function, and also specify characters that
               may appear in the result of formatting the number. In each case the value
               <rfc2119>must</rfc2119> either be a single character, or a string
               in the form <code nobreak="false">m:r</code> where <code nobreak="false">m</code> is a single character
               (the <term>marker</term>) used to represent the property in the picture
               string, and <code nobreak="false">r</code> (the <term>rendition</term>) 
               is an arbitrary string used to represent
               the property in the formatted result: <errorref class="SE" code="0020"/>.</p><ulist><item><p>
                     <code nobreak="false">decimal-separator</code> specifies the string used to separate the
                     integer part from the fractional part of the formatted number; the default
                     value is <char>U+002E</char>.</p></item><item><p diff="add" at="2023-07-04">
                     <code nobreak="false">exponent-separator</code> specifies the string used to separate the
                     mantissa from the exponent in scientific notation; the default value is 
                     <char>U+0065</char>.</p></item><item><p>
                     <code nobreak="false">grouping-separator</code> specifies the string typically used as a
                     thousands separator; the default value is <char>U+002C</char>.</p></item><item><p>
                     <code nobreak="false">percent</code> specifies the string used to indicate that the number
                     is represented as a per-hundred fraction; the default value is <char>U+0025</char>.</p></item><item><p>
                     <code nobreak="false">per-mille</code> specifies the string used to indicate that the number
                     is represented as a per-thousand fraction; the default value is <char>U+2030</char>.</p></item></ulist><p>
               <error spec="XT" type="static" class="SE" code="1295"><p>It is a <termref def="dt-static-error">static error</termref> if the character
                     specified in the <code nobreak="false">zero-digit</code> attribute is not a digit or is a digit
                     that does not have the numeric value zero. </p></error>
            </p><p>The following attributes control the interpretation of characters in the <termref def="dt-picture-string">picture string</termref> supplied to the
               <xfunction>format-number</xfunction> function. In each case the value
               <rfc2119>must</rfc2119> be a single character <errorref class="SE" code="0020"/>.
               The <code nobreak="false">zero-digit</code> property also affects the characters used to render
               digits in the formatted result:
            </p><ulist><item><p>
                     <code nobreak="false">zero-digit</code> specifies the character used to represent the digit
                     zero; the default value is <char>U+0030</char>. This
                     character <rfc2119>must</rfc2119> be a digit (category <code nobreak="false">Nd</code> in the
                     Unicode property database), and it <rfc2119>must</rfc2119> have the numeric
                     value zero. This attribute implicitly defines the Unicode character that is
                     used to represent each of the values 0 to 9 in the final result string: Unicode
                     is organized so that each set of decimal digits forms a contiguous block of
                     characters in numerical sequence.</p></item><item><p>
                     <code nobreak="false">digit</code> specifies the character used in the <termref def="dt-picture-string">picture string</termref> as a place-holder for an
                     optional digit; the default value is <char>U+0023</char>.</p></item><item><p>
                     <code nobreak="false">pattern-separator</code> specifies the character used to separate
                     positive and negative sub-pictures in a <termref def="dt-picture-string">picture string</termref>; 
                     the default value is <char>U+003B</char>.</p></item></ulist><p>The following attributes specify strings that may appear in the result
               of formatting the number:</p><ulist><item><p>
                     <code nobreak="false">infinity</code> specifies the string used to represent the
                     <code nobreak="false">xs:double</code> value <code nobreak="false">INF</code>; the default value is the
                     string <code nobreak="false">Infinity</code>
                  </p></item><item><p>
                     <code nobreak="false">NaN</code> specifies the string used to represent the
                     <code nobreak="false">xs:double</code> value <code nobreak="false">NaN</code> (not-a-number); the default
                     value is the string <code nobreak="false">NaN</code>
                  </p></item><item><p>
                     <code nobreak="false">minus-sign</code> specifies the string used to indicate a negative
                     number; the default value is <char>U+002D</char>.</p></item></ulist><p>
               <error spec="XT" type="static" class="SE" code="1300"><p>It is a <termref def="dt-static-error">static error</termref> if, for any named
                     or unnamed decimal format, the properties identifying <term>marker</term> 
                     characters to be used in a
                     <termref def="dt-picture-string">picture string</termref> do not identify
                     distinct values. These properties are <var>decimal-separator</var>,
                     <var>grouping-separator</var>, <var>exponent-separator</var>, <var>percent</var>,
                     <var>per-mille</var>, <var>zero-digit</var>, <var>digit</var>,
                     and <var>pattern-separator</var>.</p></error>
            </p><p>Every (named or unnamed) decimal format defined in a <termref def="dt-stylesheet">package</termref> is added to the <xtermref spec="XP40" ref="dt-static-decimal-formats">statically known decimal formats</xtermref> in the
               <xtermref spec="XP40" ref="dt-static-context">static context</xtermref> of every
               expression in the <termref def="dt-package">package</termref>, excluding expressions
               appearing in <code nobreak="false">[xsl:]use-when</code> attributes.</p></div2><div2 id="value-templates"><head>Value Templates</head><p>The string value of an attribute or text node in the stylesheet may in particular
               circumstances contain embedded expressions enclosed between curly brackets.
               Attributes and text nodes that use (or are permitted to use) this mechanism are
               referred to respectively as <termref def="dt-attribute-value-template">attribute
                  value templates</termref> and <termref def="dt-text-value-template">text value
                  templates</termref>.</p><p><termdef id="dt-value-template" term="value template">Collectively,
                  attribute value templates and text value templates are referred to as <term>value
                     templates</term>.</termdef></p><p>A value template is a string consisting of an alternating sequence of fixed parts and
               variable parts:</p><ulist><item><p>A variable part consists of an optional XPath <termref def="dt-expression">expression</termref> enclosed in curly brackets (<code nobreak="false">{}</code>):
                  more specifically, a string conforming 
                     to the XPath production <code nobreak="false">Expr?</code>.</p><note><p>An expression within a variable part may contain an unescaped curly bracket within
                        a <xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="XP40" ref="prod-xpath40-StringLiteral" xlink:type="simple">StringLiteral</xnt> or within
                        a comment.</p><p>Currently no XPath expression starts with an opening curly
                        bracket, so the use of <code nobreak="false">{{</code> creates no ambiguity. If an enclosed
                        expression ends with a closing curly bracket, no whitespace is required between
                        this and the closing delimiter.</p><p>The fact that the expression is optional means that the
                     string contained between the curly brackets may be zero-length, may comprise whitespace
                     only, or may contain XPath comments. The effective value in this case is a zero-length
                     string, which is equivalent to omitting the variable part entirely, together with its 
                     curly-bracket delimiters. </p></note></item><item><p>A fixed part
                  may contain any characters, except that a left curly bracket <rfc2119>must</rfc2119>
                  be written as <code nobreak="false">{{</code> and a right curly bracket <rfc2119>must</rfc2119> be
                  written as <code nobreak="false">}}</code>. </p></item></ulist><p>
               <error spec="XT" type="static" class="SE" code="0350"><p>It is a <termref def="dt-static-error">static error</termref> if an unescaped
                     left curly bracket appears in a fixed part of a value template without a
                     matching right curly bracket.</p></error>
            </p><p>It is a <termref def="dt-static-error">static error</termref> if the string contained
               between matching curly brackets in a value template does not match the XPath
               production <xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="XP40" ref="prod-xpath40-Expr" xlink:type="simple">Expr?</xnt>, or if it contains
               other XPath static errors. The error is raised using the appropriate XPath error
               code.</p><p>
               <error spec="XT" type="static" class="SE" code="0370"><p>It is a <termref def="dt-static-error">static error</termref> if an unescaped
                     right curly bracket occurs in a fixed part of a value template.</p></error>
            </p><p>The result of evaluating a
               value template is referred to as its <termref def="dt-effective-value"/>. The
               effective value is the string obtained by concatenating the expansions of the fixed
               and variable parts:</p><ulist><item><p>The expansion of a fixed part is obtained by replacing any double curly
                     brackets (<code nobreak="false">{{</code> or <code nobreak="false">}}</code>) by the corresponding single curly
                     bracket.</p></item><item><p>The expansion of a variable part is as follows:</p><ulist><item><p>If an expression is present, the result of evaluating the enclosed XPath
                        <termref def="dt-expression">expression</termref> and converting the
                        resulting value to a string. This conversion is done using the rules given in
                        <specref ref="constructing-simple-content"/>.</p></item><item><p>If the expression is omitted, a zero-length string.</p></item></ulist></item></ulist><note><p>This process can raise dynamic errors, for example if the sequence contains an
                  element with a complex content type (which cannot be atomized).</p></note><p>In the case of an attribute value template, the effective value becomes the string
               value of the new attribute node. In the case of a text value template, the effective
               value becomes the string value of the new text node.</p><div3 id="attribute-value-templates"><head>Attribute Value Templates</head><p>
                  <termdef id="dt-attribute-value-template" term="attribute value template">In an
                     attribute that is designated as an <term>attribute value template</term>, such
                     as an attribute of a <termref def="dt-literal-result-element">literal result
                        element</termref>, an <termref def="dt-expression">expression</termref> can
                     be used by surrounding the expression with curly brackets (<code nobreak="false">{}</code>),
                     following the general rules for <termref def="dt-value-template">value
                        templates</termref></termdef>.</p><p>Curly brackets are not treated specially in an attribute value in an XSLT <termref def="dt-stylesheet">stylesheet</termref> unless the attribute is specifically
                  designated as one that permits an attribute value template; in an element syntax
                  summary, the value of such attributes is surrounded by curly brackets.</p><note><p>Not all attributes are designated as attribute value templates. Attributes
                     whose value is an <termref def="dt-expression">expression</termref> or <termref def="dt-pattern">pattern</termref>, attributes of <termref def="dt-declaration">declaration</termref> elements and attributes that
                     refer to named XSLT objects are generally not designated as attribute value
                     templates (an exception is the <code nobreak="false">format</code> attribute of
                        <elcode>xsl:result-document</elcode>). Namespace declarations are not XDM
                     attribute nodes and are therefore never treated as attribute value
                     templates.</p></note><p>If the element containing the attribute is processed
                     with <termref def="dt-xslt-10-behavior">XSLT 1.0 behavior</termref>, then the
                     rules for converting the value of the expression to a string (given in <specref ref="value-templates"/>) are modified as follows. After <termref def="dt-atomization">atomizing</termref> the result of the expression, all
                     items other than the first item in the resulting sequence are discarded, and
                     the effective value is obtained by converting the first item in the sequence to
                     a string. If the atomized sequence is empty, the result is a zero-length
                     string.</p><note><p>The above rule applies to attribute value templates but not
                     to text value templates, since the latter were not available in XSLT 1.0.</p></note><example><head>Attribute Value Templates</head><p>The following example creates an <code nobreak="false">img</code> result element from a
                        <code nobreak="false">photograph</code> element in the source; the value of the
                        <code nobreak="false">src</code> and <code nobreak="false">width</code> attributes are computed using XPath
                     expressions enclosed in attribute value templates:</p><eg xml:space="preserve" role="xslt-declarations">&lt;xsl:variable name="image-dir" select="'/images'"/&gt;

&lt;xsl:template match="photograph"&gt;
  &lt;img src="{ $image-dir }/{ href }" width="{ size/@width }"/&gt;
&lt;/xsl:template&gt;</eg><p>With this source</p><eg xml:space="preserve" role="xml">&lt;photograph&gt;
  &lt;href&gt;headquarters.jpg&lt;/href&gt;
  &lt;size width="300"/&gt;
&lt;/photograph&gt;</eg><p>the result would be</p><eg xml:space="preserve" role="xml">&lt;img src="/images/headquarters.jpg" width="300"/&gt;</eg></example><example><head>Producing a Space-Separated List</head><p>The following example shows how the values in a sequence are output as a
                     space-separated list. The following literal result element:</p><eg xml:space="preserve" role="xml">&lt;temperature readings="{10.32, 5.50, 8.31}"/&gt;</eg><p>produces the output node:</p><eg xml:space="preserve" role="xml">&lt;temperature readings="10.32 5.5 8.31"/&gt;</eg></example><p>Curly brackets are <emph>not</emph> recognized recursively inside expressions.</p><example><head>Curly Brackets cannot be Nested</head><p>For example:</p><eg role="error" xml:space="preserve">&lt;a href="#{id({@ref})/title}"/&gt;</eg><p>is <emph>not</emph> allowed. Instead, use simply:</p><eg xml:space="preserve" role="xml">&lt;a href="#{id(@ref)/title}"/&gt;</eg></example></div3><div3 id="text-value-templates"><head>Text Value Templates</head><p>The <termref def="dt-standard-attributes">standard attribute</termref>
                  <code nobreak="false">[xsl:]expand-text</code> may appear on any element in the stylesheet, and
                  determines whether descendant text nodes of that element are treated as text value
                  templates. A text node in the stylesheet is treated as a text value template if
                  (a) it is part of a <termref def="dt-sequence-constructor">sequence
                     constructor</termref>, (b) there is an ancestor element with an
                     <code nobreak="false">[xsl:]expand-text</code> attribute, and (c) on the innermost ancestor
                  element that has such an attribute, the value of the attribute is
                  <code nobreak="false">yes</code>. The attribute is boolean and
                        <rfc2119>must</rfc2119> therefore take one of the values <code nobreak="false">yes</code>
                     (synonyms <code nobreak="false">true</code> or <code nobreak="false">1</code>) or <code nobreak="false">no</code> (synonyms
                        <code nobreak="false">false</code> or <code nobreak="false">0</code>). </p><p>This section describes how text nodes  are processed when the <termref def="dt-effective-value"/> is
                     <code nobreak="false">yes</code>. Such text nodes are referred to as text value templates.</p><p>
                  <termdef id="dt-text-value-template" term="text value template">In a text node
                     that is designated as a <term>text value template</term>, <termref def="dt-expression">expressions</termref> can be used by surrounding each
                     expression with curly brackets (<code nobreak="false">{}</code>).</termdef></p><p>The rules for text value templates are given in <specref ref="value-templates"/>.
                  A text node 
                  whose value is a text value template results in the construction of a text node in
                  the result of the containing sequence
                     constructor. The string value
                  of that text node is obtained by computing the <termref def="dt-effective-value"/> of the value
                  template.</p><note><p>The result of evaluating a text value template is a (possibly zero-length) text
                     node. This text node becomes part of the result of the containing sequence
                     constructor, and is thereafter handled
                     exactly as if the value had appeared explicitly as a text node in the
                     stylesheet.</p><p>The way in which the effective value is computed does not depend on any
                        <code nobreak="false">separator</code> attribute on a containing
                        <elcode>xsl:text</elcode>, <elcode>xsl:value-of</elcode> or 
                     <elcode>xsl:attribute</elcode> instruction.
                     The <code nobreak="false">separator</code> attribute only affects how the text node is combined
                     with adjacent items in the result of the containing sequence constructor.</p><p>Fixed parts consisting entirely of whitespace are significant and are handled
                     in the same way as any other fixed part. This is different from the default
                     treatment of “boundary space” in XQuery.</p></note><example><head>Using a text value template to construct message output</head><eg role="xslt-instructions" xml:space="preserve">&lt;xsl:variable name="id" select="'A123'"/&gt;
&lt;xsl:variable name="step" select="5"/&gt;
&lt;xsl:message expand-text="yes"
     &gt;Processing id={ $id }, step={ $step }&lt;/xsl:message&gt;
</eg><p>This will typically output the message text <code nobreak="false">Processing id=A123,
                        step=5</code>.</p></example><example><head>Using a text value template to define the result of a function</head><eg role="xslt-declaration xmlns:f='f'" xml:space="preserve">&lt;xsl:function name="f:sum" expand-text="yes" as="xs:integer"&gt;
&lt;xsl:param name="x" as="xs:integer"/&gt;
&lt;xsl:param name="y" as="xs:integer"/&gt;
  { $x + $y }
&lt;/xsl:function&gt;</eg><p>Note that although this is a very readable way of expressing the computation
                     performed by the function, the semantics are somewhat complex, and this could
                     mean that execution is inefficient. The function computes the value of <code nobreak="false">$x
                        + $y</code> as an integer, and then constructs a text node containing the
                     string representation of this integer (preceded and followed by whitespace).
                     Because the declared result type of the function is <code nobreak="false">xs:integer</code>,
                     this text node is then atomized, giving an <code nobreak="false">xs:untypedAtomic</code> item,
                     and the <code nobreak="false">xs:untypedAtomic</code> item is then cast to an
                        <code nobreak="false">xs:integer</code>.</p></example><note><p>The main motivations for adding text value templates to the XSLT language are
                     firstly, to make it easier to construct parameterized text in contexts such as
                        <elcode>xsl:text</elcode>, <elcode>xsl:value-of</elcode>, 
                     and <elcode>xsl:message</elcode>, and
                     secondly, to allow use of complex multi-line XPath expressions where
                     maintaining correct indentation is important for readability. The fact that XML
                     processors are required to normalize whitespace in attribute values means that
                     writing such expressions within a <code nobreak="false">select</code> attribute is not
                     ideal.</p><p>The facility is only present if enabled using the
                        <code nobreak="false">[xsl:]expand-text</code> attribute. This is partly for backwards
                     compatibility, and partly to avoid creating difficulties when constructing
                     content that is rich in curly brackets, for example JavaScript code or CSS
                     style sheets.</p></note></div3></div2><div2 id="sequence-constructors"><head>Sequence Constructors</head><p>
               <termdef id="dt-sequence-constructor" term="sequence constructor">A <term>sequence
                     constructor</term> is a sequence of zero or more sibling nodes in the <termref def="dt-stylesheet">stylesheet</termref> that can be evaluated to return a
                  sequence of nodes, atomic items, and function
                     items. The way that the resulting sequence is used depends on the
                  containing instruction.</termdef>
            </p><p>Many <termref def="dt-xslt-element">XSLT elements</termref>, and also <termref def="dt-literal-result-element">literal result elements</termref>, are defined to
               take a <termref def="dt-sequence-constructor"/> as their content.</p><p>Four kinds of nodes may be encountered in a sequence constructor:</p><olist><item><p> A <emph>Text node</emph> appearing in the <termref def="dt-stylesheet">stylesheet</termref> (if it has not been removed in the process of
                     whitespace stripping: see <specref ref="stylesheet-stripping"/>) is processed as follows:</p><olist><item><p>if the <termref def="dt-effective-value"/> of the standard attribute
                              <code nobreak="false">[xsl:]expand-text</code> is <code nobreak="false">no</code>, or in the absence
                           of this attribute, the text node in the stylesheet is copied to create a
                           new parentless text node in the result of the sequence constructor.</p></item><item><p>Otherwise (the <termref def="dt-effective-value"/> of <code nobreak="false">[xsl:]expand-text</code> is
                              <code nobreak="false">yes</code>), the text node in the stylesheet is processed as
                           described in <specref ref="text-value-templates"/>.</p></item></olist></item><item><p> A <termref def="dt-literal-result-element">literal result element</termref> is
                     evaluated to create a new parentless element node, having the same <termref def="dt-expanded-qname">expanded QName</termref> as the literal result
                     element: see <specref ref="literal-result-element"/>. </p></item><item><p>An XSLT <termref def="dt-instruction">instruction</termref> produces a sequence
                     of zero, one, or more items as its result. For most XSLT instructions, these
                     items are nodes, but some instructions (such
                        as <elcode>xsl:sequence</elcode>, <elcode>xsl:select</elcode>, 
                     <elcode>xsl:map</elcode>, <elcode>xsl:array</elcode>, and <elcode>xsl:copy-of</elcode>) can also
                     produce atomic items or function items.</p><p>Several instructions, such as <elcode>xsl:element</elcode>, return a newly
                     constructed parentless node (which may have its own attributes, namespaces,
                     children, and other descendants). Other instructions, such as
                        <elcode>xsl:if</elcode>, pass on the items produced by their own nested
                     sequence constructors.</p><p>Three instructions serve primarily to evaluate XPath expressions:</p><ulist><item><p>The <elcode>xsl:sequence</elcode> instruction evaluates an
                        XPath expression written statically in its <code nobreak="false">select</code>
                        attribute.</p></item><item><p>The <elcode>xsl:select</elcode> instruction evaluates
                        an XPath expression written statically in its contained text node.</p></item><item><p>The <elcode>xsl:evaluate</elcode> instruction
                        compiles and evaluates an XPath expression that is constructed
                        dynamically as a character string.</p></item></ulist><p>These three instructions may return
                     atomic items, function items, or nodes.</p></item><item><p> An <termref def="dt-extension-instruction"/> (see <specref ref="extension-instruction"/>) also produces a sequence of items as its
                     result.</p></item></olist><p><termdef id="dt-immediate-result" term="immediate result">The result of evaluating
               a <termref def="dt-sequence-constructor"/> is the sequence
               of items formed by concatenating the results of evaluating each of the nodes in the
               sequence constructor, retaining order. This is 
                  referred to as the <term>immediate result</term>
            of the sequence constructor.</termdef></p><p>However:</p><ulist><item><p>For the effect of the <elcode>xsl:fallback</elcode> instruction, see <specref ref="fallback"/>.</p></item><item><p>For the effect of the <elcode>xsl:on-empty</elcode> and
                        <elcode>xsl:on-non-empty</elcode> instructions, see <specref ref="conditional-content-construction"/>.</p></item></ulist><p>The way that <termref def="dt-immediate-result"/> of a <termref def="dt-sequence-constructor"/> 
               is used depends on the containing element in the stylesheet, and is specified in the rules 
               for that element. It is typically one of the following:</p><ulist><item><p>The <termref def="dt-immediate-result"/> may be bound to a <termref def="dt-variable"/> or 
                     delivered as the result of a <termref def="dt-stylesheet-function"/>.
                     In this case the <code nobreak="false">as</code> attribute of the containing <elcode>xsl:variable</elcode>
                     or <elcode>xsl:function</elcode> element may be used to declare its required type, 
                     and the <termref def="dt-immediate-result"/> is then converted to the required type 
                     by applying the <termref def="dt-coercion-rules"/>.</p><note><ulist><item><p>In the absence of an <code nobreak="false">as</code> attribute, the result of a 
                              function is the <termref def="dt-immediate-result"/> of the sequence constructor; 
                              but the value of a variable (for backwards compatibility reasons) is a document node 
                              whose content is formed by applying the rules in <specref ref="constructing-complex-content"/> 
                              to the <termref def="dt-immediate-result"/>.
                           </p></item><item><p>The coercion rules do not merge adjacent text nodes 
                              or insert separators between adjacent items. This means it is often inappropriate 
                              to use <elcode>xsl:value-of</elcode> in the body of <elcode>xsl:variable</elcode> or 
                              <elcode>xsl:function</elcode>, especially when the intent is to return an atomic result. 
                              The <elcode>xsl:sequence</elcode> instruction is designed for this purpose, and 
                              is usually a better choice.
                           </p></item><item><p>The result of a function, or the value of a variable, may contain nodes 
                              (such as elements, attributes, and text nodes) that are not attached to any parent node 
                              in a <termref def="dt-result-tree"/>.  The semantics of XPath expressions when applied to parentless nodes 
                              are well-defined; however, such expressions should be used with care. For example, 
                              the expression <code nobreak="false">/</code> causes a type error if the root of the tree containing 
                              the context node is not a document node.
                           </p></item><item><p>Parentless attribute nodes require particular care because they have no
                              namespace nodes associated with them. A parentless attribute node is not
                              permitted to contain namespace-sensitive content (for example, a QName or an
                              XPath expression) because there is no information enabling the prefix to be
                              resolved to a namespace URI. Parentless attributes can be useful in an
                              application (for example, they provide an alternative to the use of
                              attribute sets: see <specref ref="attribute-sets"/>) but they need to be
                              handled with care.</p></item></ulist></note></item><item><p>The sequence may be returned as the result of the containing element. This
                     happens, for example, when 
                     the element containing the
                     sequence constructor is 
                        <elcode>xsl:break</elcode>,
                        <elcode>xsl:catch</elcode>, 
                        <elcode>xsl:fallback</elcode>, <elcode>xsl:for-each</elcode>,
                        <elcode>xsl:for-each-group</elcode>, <elcode>xsl:fork</elcode>, <elcode>xsl:if</elcode>, <elcode>xsl:iterate</elcode>,
                        <elcode>xsl:matching-substring</elcode>, 
                        <elcode>xsl:non-matching-substring</elcode>, <elcode>xsl:on-completion</elcode>,
                        <elcode>xsl:otherwise</elcode>, <elcode>xsl:perform-sort</elcode>,
                        <elcode>xsl:sequence</elcode>, <elcode>xsl:try</elcode>, or <elcode>xsl:when</elcode>. </p></item><item><p>The sequence may be used to construct the content of a new element or document
                     node. This happens when the sequence constructor appears as the content of a
                        <termref def="dt-literal-result-element">literal result element</termref>,
                     or of one of the instructions <elcode>xsl:copy</elcode>,
                        <elcode>xsl:element</elcode>, <elcode>xsl:document</elcode>,
                        <elcode>xsl:result-document</elcode>, <elcode>xsl:assert</elcode>, or <elcode>xsl:message</elcode>.
                     It also happens when the sequence constructor is contained in one of the
                     elements <elcode>xsl:variable</elcode>, <elcode>xsl:param</elcode>, or
                        <elcode>xsl:with-param</elcode>,  when this instruction has no
                        <code nobreak="false">as</code> attribute. For details, see <specref ref="constructing-complex-content"/>.</p></item><item><p>The sequence may be used to construct the <termref def="dt-string-value">string
                        value</termref> of an attribute node, text node, namespace node, comment
                     node, or processing instruction node. This happens when the sequence
                     constructor is contained in one of the elements <elcode>xsl:attribute</elcode>,
                        <elcode>xsl:text</elcode>, <elcode>xsl:value-of</elcode>, <elcode>xsl:namespace</elcode>,
                        <elcode>xsl:comment</elcode>, or
                     <elcode>xsl:processing-instruction</elcode>. For details, see <specref ref="constructing-simple-content"/>.</p></item></ulist><div3 id="constructing-complex-content"><head>Constructing Complex Content</head><p>Many instructions, for example <elcode>xsl:copy</elcode>, <elcode>xsl:element</elcode>, 
                  <elcode>xsl:document</elcode>, <elcode>xsl:result-document</elcode>, and 
                  <termref def="dt-literal-result-element">literal result elements</termref>, 
                  create a new parent node, and evaluate a <termref def="dt-sequence-constructor"/> 
                  forming the content of the instruction to create the attributes, 
                  namespaces, and children of the new parent node. The <termref def="dt-immediate-result"/> 
                  of the sequence constructor is processed to create the content of the new parent 
                  node as described in this section.</p><p>When constructing the content of an element, the <code nobreak="false">inherit-namespaces</code>
                  attribute of the <elcode>xsl:element</elcode> or <elcode>xsl:copy</elcode>
                  instruction, or the <code nobreak="false">xsl:inherit-namespaces</code> property of the literal
                  result element, determines whether namespace nodes are to be inherited. The effect
                  of this attribute is described in the rules that follow.</p><p>The <termref def="dt-immediate-result"/> of the <termref def="dt-sequence-constructor"/>
                  is processed as follows (applying the rules in the order they are listed):</p><olist><item><p>The containing instruction may generate attribute nodes and/or namespace
                        nodes, as specified in the rules for the individual instruction. For
                        example, these nodes may be produced by expanding an
                           <code nobreak="false">[xsl:]use-attribute-sets</code> attribute, or by expanding the
                        attributes of a <termref def="dt-literal-result-element">literal result
                           element</termref>. Any such nodes are prepended to the 
                        <termref def="dt-immediate-result"/> of the <termref def="dt-sequence-constructor"/>.</p></item><item><p>Any array item in the sequence (see <specref ref="arrays"/>)
                     is replaced by its members, recursively. This is equivalent to applying
                     the <xfunction spec="FO40">array:flatten</xfunction> function defined in 
                     <bibref ref="xpath-functions-40"/>.</p><note diff="del" at="2022-01-01"><p>This situation only arises if the XPath 3.1 feature is implemented.
                     Note that if the array contains nodes, this operation leaves the nodes in the sequence: they
                     are not <termref def="dt-atomization">atomized</termref>.</p></note></item><item><p>Any atomic item in the sequence is cast to a string.</p><note><p>Casting from <code nobreak="false">xs:QName</code> or <code nobreak="false">xs:NOTATION</code> to
                              <code nobreak="false">xs:string</code> always succeeds, because these values retain a
                           prefix for this purpose. However, there is no guarantee that the prefix
                           used will always be meaningful in the context where the resulting string
                           is used.</p></note></item><item><p>Any consecutive sequence of strings in the sequence is converted
                        to a single text node, whose <termref def="dt-string-value">string
                           value</termref> contains the content of each of the strings in turn, with
                        <char>U+0020</char> used as a separator between successive strings.</p></item><item><p>Any document node within the sequence is replaced by a sequence
                        containing each of its children, in document order.</p></item><item><p>Zero-length text nodes within the sequence are removed.</p></item><item><p>Adjacent text nodes within the sequence are merged into a single text
                        node.</p></item><item><p>Invalid items in the sequence are
                        detected as follows.</p><p>
                        <error spec="XT" type="dynamic" class="DE" code="0410"><p>It is a <termref def="dt-dynamic-error"> dynamic error</termref> if the 
                              sequence used to construct the content of an element node contains a
                              namespace node or attribute node that is preceded in the sequence by a
                              node that is neither a namespace node nor an attribute node.</p></error>
                     </p><p>
                        <error spec="XT" type="dynamic" class="DE" code="0420"><p>It is a <termref def="dt-dynamic-error"> dynamic error</termref> if the 
                              sequence used to construct the content of a document node contains a
                              namespace node or attribute node.</p></error>
                     </p><p>
                        <error spec="XT" type="dynamic" class="DE" code="0430"><p>It is a <termref def="dt-dynamic-error"> dynamic error</termref> if the 
                              sequence contains two or more namespace nodes having the same name but
                              different <termref def="dt-string-value">string values</termref> (that
                              is, namespace nodes that map the same prefix to different namespace
                              URIs).</p></error>
                     </p><p>
                        <error spec="XT" type="dynamic" class="DE" code="0440"><p>It is a <termref def="dt-dynamic-error"> dynamic error</termref> if the 
                              sequence contains a namespace node with no name and the element node
                              being constructed has a null namespace URI (that is, it is an error to
                              define a default namespace when the element is in no namespace). </p></error>
                     </p><p diff="add" at="E">
                        <error spec="XT" type="type" class="DE" code="0450"><p>It is a <termref def="dt-type-error">type error</termref> if the result
                              sequence contains a function item. </p></error>
                     </p><note diff="add" at="E"><p>The error code reflects the fact that this error was at one time classified 
                           as a dynamic error rather than a type error.</p></note></item><item><p>If the sequence contains two or more namespace nodes with the same
                        name (or no name) and the same <termref def="dt-string-value">string
                           value</termref> (that is, two namespace nodes mapping the same prefix to
                        the same namespace URI), then all but one of the duplicate nodes are
                        discarded.</p><note><p>Since the order of namespace nodes is <termref def="dt-implementation-dependent">implementation-dependent</termref>,
                           it is not significant which of the duplicates is retained.</p></note></item><item><p>If an attribute <var>A</var> in the sequence has the same name as
                        another attribute <var>B</var> that appears later in the sequence,
                        then attribute <var>A</var> is discarded from the sequence. Before
                        discarding attribute <var>A</var>, the processor <rfc2119>may</rfc2119>
                        raise any <termref def="dt-type-error">type errors</termref> that would be
                        raised if attribute <var>B</var> were not present. </p></item><item><p>Each node in the resulting sequence is attached as a namespace, attribute,
                        or child of the newly constructed element or document node. Conceptually
                        this involves making a deep copy of the node; in practice, however, copying
                        the node will only be necessary if the existing node can be referenced
                        independently of the parent to which it is being attached. When copying an
                        element or processing instruction node, its base URI property is changed to
                        be the same as that of its new parent, unless it has an
                           <code nobreak="false">xml:base</code> attribute (see <bibref ref="xmlbase"/>) that
                        overrides this. If the copied element has an <code nobreak="false">xml:base</code>
                        attribute, its base URI is the value of that attribute, resolved (if it is
                        relative) against the base URI of the new parent node.</p><p>Except for the handling of base URI, the copying
                        of a node follows the rules of the <elcode>xsl:copy-of</elcode> instruction
                        with attributes <code nobreak="false">copy-namespaces="yes" copy-accumulators="no"
                           validation="preserve"</code>.</p><note><p>This has the consequence that the type annotation and the values of the
                              <code nobreak="false">nilled</code>, <code nobreak="false">is-id</code>, and <code nobreak="false">is-idrefs</code>
                           properties are retained. However, if the node under construction (the new
                           parent of the node being copied) uses a validation mode other than
                              <code nobreak="false">preserve</code>, this will be transient: the values will be
                           recomputed when the new parent node is validated.</p></note></item><item><p>If the newly constructed node is an element node, then namespace fixup is
                        applied to this node, as described in <specref ref="namespace-fixup"/>.</p></item><item><p>If the newly constructed node is an element node, and if namespaces are
                        inherited, then each namespace node of the newly constructed element
                        (including any produced as a result of the namespace fixup process) is
                        copied to each descendant element of the newly constructed element, unless
                        that element or an intermediate element already has a namespace node with
                        the same name (or absence of a name) or that descendant element or an
                        intermediate element is in no namespace and the namespace node has no
                        name.</p></item></olist><example><head>A Sequence Constructor for Complex Content</head><p>Consider the following stylesheet fragment:</p><eg xml:space="preserve" role="xslt-instruction">&lt;td&gt;
  &lt;xsl:attribute name="valign"&gt;top&lt;/xsl:attribute&gt;
  &lt;xsl:value-of select="@description"/&gt;
&lt;/td&gt;</eg><p>This fragment consists of a literal result element <code nobreak="false">td</code>, containing
                     a sequence constructor that consists of two instructions:
                        <elcode>xsl:attribute</elcode> and <elcode>xsl:value-of</elcode>. The
                     sequence constructor is evaluated to produce a sequence of two nodes: a
                     parentless attribute node, and a parentless text node. The <code nobreak="false">td</code>
                     instruction causes a <code nobreak="false">td</code> element to be created; the new attribute
                     therefore becomes an attribute of the new <code nobreak="false">td</code> element, while the
                     text node created by the <elcode>xsl:value-of</elcode> instruction becomes a
                     child of the <code nobreak="false">td</code> element (unless it is zero-length, in which case
                     it is discarded).</p></example><example><head>Space Separators in Element Content</head><p>Consider the following stylesheet fragment:</p><eg xml:space="preserve" role="xslt-instruction">&lt;doc&gt;
  &lt;e&gt;&lt;xsl:sequence select="1 to 5"/&gt;&lt;/e&gt;
  &lt;f&gt;
    &lt;xsl:for-each select="1 to 5"&gt;
      &lt;xsl:value-of select="."/&gt;
    &lt;/xsl:for-each&gt;
  &lt;/f&gt;
&lt;/doc&gt;</eg><p>This produces the output (when indented):</p><eg xml:space="preserve" role="xml">&lt;doc&gt;
  &lt;e&gt;1 2 3 4 5&lt;/e&gt;
  &lt;f&gt;12345&lt;/f&gt;
&lt;/doc&gt;</eg><p>The difference between the two cases is that for the <code nobreak="false">e</code> element,
                     the sequence constructor generates a sequence of five atomic items, which are
                     therefore separated by spaces. For the <code nobreak="false">f</code> element, the content is a
                     sequence of five text nodes, which are concatenated without space
                     separation.</p><p>It is important to be aware of the distinction between
                        <elcode>xsl:sequence</elcode>, which returns the value of its
                        <code nobreak="false">select</code> expression unchanged, and <elcode>xsl:value-of</elcode>,
                     which constructs a text node.</p></example></div3><div3 id="constructing-simple-content"><head>Constructing Simple Content</head><p>The instructions <elcode>xsl:attribute</elcode>, <elcode>xsl:comment</elcode>,
                     <elcode>xsl:processing-instruction</elcode>, <elcode>xsl:namespace</elcode>,
                  <elcode>xsl:text</elcode>, and <elcode>xsl:value-of</elcode> 
                  all create nodes that cannot have children.
                  Specifically, the <elcode>xsl:attribute</elcode> instruction creates an attribute
                  node, <elcode>xsl:comment</elcode> creates a comment node,
                     <elcode>xsl:processing-instruction</elcode> creates a processing instruction
                  node, <elcode>xsl:namespace</elcode> creates a namespace node, and
                     <elcode>xsl:text</elcode> and <elcode>xsl:value-of</elcode> create text nodes. 
                  The string value of the new
                  node is constructed using either the <code nobreak="false">select</code> attribute of the
                  instruction, or the <termref def="dt-sequence-constructor">sequence
                     constructor</termref> that forms the content of the instruction. The
                     <code nobreak="false">select</code> attribute allows the content to be specified by means of an
                  XPath expression, while the sequence constructor allows it to be specified by
                  means of a sequence of XSLT instructions. The <code nobreak="false">select</code> attribute or
                  sequence constructor is evaluated to produce a result sequence, and the <termref def="dt-string-value">string value</termref> of the new node is derived from
                  this result sequence according to the rules below.</p><p>These rules are also used to compute the <termref def="dt-effective-value">effective value</termref> of a <termref def="dt-value-template">value template</termref>. In this case the
                  sequence being processed is the result of evaluating an XPath expression enclosed
                  between curly brackets, and the separator is a single space character.</p><olist><item><p>Zero-length text nodes in the sequence are discarded.</p></item><item><p>Adjacent text nodes in the sequence are merged into a single text node.</p></item><item><p>The sequence is <termref def="dt-atomization">atomized</termref>
                        (which may cause a dynamic error).</p></item><item><p>Every value in the atomized sequence is cast to a string.</p></item><item><p>The strings within the resulting sequence are concatenated, with a (possibly
                        zero-length) separator inserted between successive strings. The default
                        separator depends on the containing instruction; except where
                        otherwise specified, it is a single space.</p><p>In the case of <elcode>xsl:attribute</elcode>,
                        <elcode>xsl:text</elcode>, and <elcode>xsl:value-of</elcode>,
                        the default separator is a single space
                     when the <code nobreak="false">select</code> attribute is used, or a zero-length string otherwise; 
                     a different separator can be specified
                        using the <code nobreak="false">separator</code> attribute of the instruction.</p><p>In the case of <elcode>xsl:comment</elcode>,
                        <elcode>xsl:processing-instruction</elcode>, and
                           <elcode>xsl:namespace</elcode>, and when expanding a <termref def="dt-value-template">value
                        template</termref>, the default separator cannot be changed.</p></item><item><p>In the case of <elcode>xsl:processing-instruction</elcode>, any leading
                        spaces in the resulting string are removed.</p></item><item><p>The resulting string forms the <termref def="dt-string-value">string
                           value</termref> of the new attribute, namespace, comment,
                        processing instruction, or text node.</p></item></olist><example><head>Space Separators in Attribute Content</head><p>Consider the following stylesheet fragment:</p><eg xml:space="preserve" role="xslt-instruction">&lt;doc&gt;
  &lt;xsl:attribute name="e" select="1 to 5"/&gt;
  &lt;xsl:attribute name="f"&gt;
    &lt;xsl:for-each select="1 to 5"&gt;
      &lt;xsl:value-of select="."/&gt;
    &lt;/xsl:for-each&gt;
  &lt;/xsl:attribute&gt;
  &lt;xsl:attribute name="g" expand-text="yes"&gt;{1 to 5}&lt;/xsl:attribute&gt;
&lt;/doc&gt;</eg><p>This produces the output:</p><eg xml:space="preserve" role="xml">&lt;doc e="1 2 3 4 5" f="12345" g="1 2 3 4 5"/&gt;</eg><p>The difference between the three cases is as follows. For the
                        <code nobreak="false">e</code> attribute, the sequence constructor generates a sequence of
                     five atomic items, which are therefore separated by spaces. For the
                        <code nobreak="false">f</code> attribute, the content is supplied as a sequence of five text
                     nodes, which are concatenated without space separation. For the <code nobreak="false">g</code>
                     attribute, the <termref def="dt-text-value-template"/> constructs a text node
                     using the rules for constructing simple content, which insert space separators
                     between atomic items; the text node is then atomized to form the value of the
                     attribute.</p><p>Specifying <code nobreak="false">separator=""</code> on the first
                        <elcode>xsl:attribute</elcode> instruction would cause the attribute value
                     to be <code nobreak="false">e="12345"</code>. A <code nobreak="false">separator</code> attribute on the second
                        <elcode>xsl:attribute</elcode> instruction would have no effect, since the
                     separator only affects the way adjacent atomic items are handled: separators
                     are never inserted between adjacent text nodes. A
                           <code nobreak="false">separator</code> on the third <elcode>xsl:attribute</elcode>
                        instruction would also have no effect, because text value templates are
                        evaluated without regard to the containing instruction.</p></example><note><p>If an attribute value template contains a sequence of fixed and variable parts,
                     no additional whitespace is inserted between the expansions of the fixed and
                     variable parts. For example, the <termref def="dt-effective-value">effective
                        value</termref> of the attribute <code nobreak="false">a="chapters{4 to 6}"</code> is
                        <code nobreak="false">a="chapters4 5 6"</code>.</p></note></div3><div3 id="namespace-fixup"><head>Namespace Fixup</head><p>In a tree supplied to or constructed by an XSLT processor, the constraints
                  relating to namespace nodes that are specified in <bibref ref="xpath-datamodel-40"/>
                  <rfc2119>must</rfc2119> be satisfied. For example:</p><ulist><item><p>If an element node has an <termref def="dt-expanded-qname">expanded
                           QName</termref> with a non-null namespace URI, then that element node
                           <rfc2119>must</rfc2119> have at least one namespace node whose <termref def="dt-string-value">string value</termref> is the same as that
                        namespace URI.</p></item><item><p>If an element node has an attribute node whose <termref def="dt-expanded-qname">expanded QName</termref> has a non-null namespace
                        URI, then the element <rfc2119>must</rfc2119> have at least one namespace
                        node whose <termref def="dt-string-value">string value</termref> is the same
                        as that namespace URI and whose name is non-empty.</p></item><item><p>Every element <rfc2119>must</rfc2119> have a namespace node whose <termref def="dt-expanded-qname">expanded QName</termref> has local-part
                           <code nobreak="false">xml</code> and whose <termref def="dt-string-value">string
                           value</termref> is <code nobreak="false">http://www.w3.org/XML/1998/namespace</code>. The
                        namespace prefix <code nobreak="false">xml</code>
                        <rfc2119>must</rfc2119> not be associated with any other namespace URI, and
                        the namespace URI <code nobreak="false">http://www.w3.org/XML/1998/namespace</code>
                        <rfc2119>must</rfc2119> not be associated with any other prefix.</p></item><item><p>A namespace node <rfc2119>must not</rfc2119> have the name
                           <code nobreak="false">xmlns</code> or the string value
                           <code nobreak="false">http://www.w3.org/2000/xmlns/</code>.</p></item></ulist><p>
                  <termdef id="dt-namespace-fixup" term="namespace fixup">The rules for the
                     individual XSLT instructions that construct a <termref def="dt-result-tree">result tree</termref> (see <specref ref="creating-new-nodes"/>) prescribe
                     some of the situations in which namespace nodes are written to the tree. These
                     rules, however, are not sufficient to ensure that the prescribed constraints
                     are always satisfied. The XSLT processor <rfc2119>must</rfc2119> therefore add
                     additional namespace nodes to satisfy these constraints. This process is
                     referred to as <term>namespace fixup</term>.</termdef>
               </p><p>The actual namespace nodes that are added to the tree by the namespace fixup
                  process are <termref def="dt-implementation-dependent">implementation-dependent</termref>, provided firstly, that at the end of the
                  process the above constraints <rfc2119>must</rfc2119> all be satisfied, and
                  secondly, that a namespace node <rfc2119>must not</rfc2119> be added to the tree
                  unless the namespace node is necessary either to satisfy these constraints, or to
                  enable the tree to be serialized using the original namespace prefixes from the
                  source document or <termref def="dt-stylesheet">stylesheet</termref>.</p><p>Namespace fixup <rfc2119>must not</rfc2119> result in an element having multiple
                  namespace nodes with the same name.</p><p>Namespace fixup <rfc2119>may</rfc2119>, if necessary to resolve conflicts, change
                  the namespace prefix contained in the QName value that holds the name of an
                  element or attribute node. This includes the option to add or remove a prefix.
                  However, namespace fixup <rfc2119>must not</rfc2119> change the prefix component
                  contained in a value of type <code nobreak="false">xs:QName</code> or <code nobreak="false">xs:NOTATION</code>
                  that forms the typed value of an element or attribute node.</p><note><p>Namespace fixup is not used to create namespace declarations for
                        <code nobreak="false">xs:QName</code> or <code nobreak="false">xs:NOTATION</code> values appearing in the
                     content of an element or attribute.</p><p>Where values acquire such types as the result of validation, namespace fixup
                     does not come into play, because namespace fixup happens before validation: in
                     this situation, it is the user’s responsibility to ensure that the
                     element being validated has the required namespace nodes to enable validation
                     to succeed.</p><p>Where existing elements are copied along with their existing <termref def="dt-type-annotation">type annotations</termref>
                        (<code nobreak="false">validation="preserve"</code>) the rules require that existing
                     namespace nodes are also copied, so that any namespace-sensitive values remain
                     valid.</p><p>Where existing attributes are copied along with their existing type
                     annotations, the rules of the XDM data model require that a parentless
                     attribute node cannot contain a namespace-sensitive typed value; this means
                     that it is an error to copy an attribute using
                        <code nobreak="false">validation="preserve"</code> if it contains namespace-sensitive
                     content.</p></note><p>Namespace fixup is applied to every element that is constructed using a <termref def="dt-literal-result-element">literal result element</termref>, or one of the
                  instructions <elcode>xsl:element</elcode>, <elcode>xsl:copy</elcode>, or
                     <elcode>xsl:copy-of</elcode>. An implementation is not
                     <rfc2119>required</rfc2119> to perform namespace fixup for elements in any
                  source document, that is, for a document in the <termref def="dt-initial-match-selection"/>, documents loaded using the
                     <function>document</function>, <xfunction>doc</xfunction> or
                     <xfunction>collection</xfunction> function, documents supplied as the value of
                  a <termref def="dt-stylesheet-parameter">stylesheet parameter</termref>, or
                  documents returned by an <termref def="dt-extension-function">extension
                     function</termref> or <termref def="dt-extension-instruction">extension
                     instruction</termref>.</p><note><p>A source document (an input document, a document returned by the
                        <function>document</function>, <xfunction>doc</xfunction> or
                        <xfunction>collection</xfunction> functions, a document returned by an
                     extension function or extension instruction, or a document supplied as a
                     stylesheet parameter) is required to satisfy the constraints described in
                        <bibref ref="xpath-datamodel-40"/>, including the constraints imposed by the
                     namespace fixup process. The effect of supplying a pseudo-document that does
                     not meet these constraints is <termref def="dt-implementation-dependent">implementation-dependent</termref>.</p></note><p>In an Infoset (see <bibref ref="xml-infoset"/>) created from a document conforming
                  to <bibref ref="xml-names"/>, it will always be true that if a parent element has
                  an in-scope namespace with a non-empty namespace prefix, then its child elements
                  will also have an in-scope namespace with the same namespace prefix, though
                  possibly with a different namespace URI. This constraint is removed in <bibref ref="xml-names11"/>. XSLT 4.0 supports the
                  creation of result trees that do not satisfy this constraint: the namespace fixup
                  process does not add a namespace node to an element merely because its parent node
                  in the <termref def="dt-result-tree">result tree</termref> has such a namespace
                  node. However, the process of constructing the children of a new element, which is
                  described in <specref ref="constructing-complex-content"/>, does cause the
                  namespaces of a parent element to be inherited by its children unless this is
                  prevented using <code nobreak="false">[xsl:]inherit-namespaces="no"</code> on the instruction that
                  creates the parent element.</p><note><p>This has implications on serialization, defined in <bibref ref="xslt-xquery-serialization-40"/>. It means that it is possible to create
                        <termref def="dt-final-result-tree">final result trees</termref> that cannot
                     be faithfully serialized as XML 1.0 documents. When such a result tree is
                     serialized as XML 1.0, namespace declarations written for the parent element
                     will be inherited by its child elements as if the corresponding namespace nodes
                     were present on the child element, except in the case of the default namespace,
                     which can be undeclared using the construct <code nobreak="false">xmlns=""</code>. When the
                     same result tree is serialized as XML 1.1, however, it is possible to undeclare
                     any namespace on the child element (for example, <code nobreak="false">xmlns:foo=""</code>) to
                     prevent this inheritance taking place.</p></note></div3></div2><div2 id="uri-references"><head>URI References</head><p>
               <termdef id="dt-uri-reference" term="URI Reference">Within this specification, the
                  term <term>URI Reference</term>, unless otherwise stated, refers to a string in
                  the lexical space of the <code nobreak="false">xs:anyURI</code> datatype as defined in <bibref ref="xmlschema-2"/>.</termdef> Note that this is a wider definition than that
               in <bibref ref="RFC3986"/>: in particular, it is designed to accommodate
               Internationalized Resource Identifiers (IRIs) as described in <bibref ref="RFC3987"/>, and thus allows the use of non-ASCII characters without escaping.</p><p>URI References are used in XSLT with three main roles:</p><ulist><item><p>As namespace URIs</p></item><item><p>As collation URIs</p></item><item><p>As identifiers for resources such as stylesheet modules; these resources are
                     typically accessible using a protocol such as HTTP. Examples of such
                     identifiers are the URIs used in the <code nobreak="false">href</code> attributes of
                        <elcode>xsl:import</elcode>, <elcode>xsl:include</elcode>, 
                        <elcode>xsl:result-document</elcode>, and <elcode>xsl:package-location</elcode>.</p></item></ulist><p>The rules for namespace URIs are given in <bibref ref="xml-names"/> and <bibref ref="xml-names11"/>. Those specifications deprecate the use of relative URI
                  references as namespace URIs.</p><p>The rules for collation URIs are given in <xspecref spec="FO40" ref="collations"/>.</p><p>URI references used to identify external resources must conform to the same rules as
               the locator attribute (<code nobreak="false">href</code>) defined in section 5.4 of <bibref ref="xlink"/>. If the URI reference is relative, then it is resolved (unless
               otherwise specified) against the base URI of the containing element node, according
               to the rules of <bibref ref="RFC3986"/>, after first escaping all characters that
               need to be escaped to make it a valid RFC3986 URI reference. (But a relative URI
                  reference in the <code nobreak="false">href</code> attribute of
                  <elcode>xsl:result-document</elcode> is resolved against the <termref def="dt-base-output-uri">Base Output URI</termref>.)</p><p>Other URI references appearing in an XSLT stylesheet document, for example the system
               identifiers of external entities or the value of the <code nobreak="false">xml:base</code> attribute,
               must follow the rules in their respective specifications.</p><p>The base URI of an element node in the stylesheet
               is determined as defined in <xspecref spec="DM40" ref="dm-base-uri"/>. Some
               implementations may allow the output of the static analysis phase of stylesheet
               processing (a “compiled stylesheet”) to be evaluated in a different location from
               that where static analysis took place. Furthermore, stylesheet authors may in such
               cases wish to avoid exposing the location of resources that are private to the
               development environment. If the base URI of an element in the stylesheet is defined
               by an absolute URI appearing in an <code nobreak="false">xml:base</code> attribute within the
               stylesheet, this value <rfc2119>must</rfc2119> be used as the static base URI. In
               other cases where processing depends on the static base URI of a stylesheet module,
               implementations <rfc2119>may</rfc2119> use different values for the static base URI
               during static analysis and during dynamic evaluation (for example, an implementation
                  <rfc2119>may</rfc2119> use different base URIs for resolving
                  <elcode>xsl:import</elcode> module references and for resolving a relative
               reference used as an argument to the <xfunction>doc</xfunction> function). In such
               cases an implementation <rfc2119>must</rfc2119> document how the static base URI is
               computed for each situation in which it is required. </p></div2></div1><div1 id="rules"><head>Template Rules</head><p>Template rules define the processing that can be applied to items that match a particular <termref def="dt-pattern">pattern</termref>.</p><div2 id="defining-templates"><head>Defining Templates</head><e:element-syntax xmlns:e="http://www.w3.org/1999/XSL/Spec/ElementSyntax" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" name="template">
      <e:in-category name="declaration"/>
      <e:attribute name="match">
         <e:data-type name="pattern"/>
      </e:attribute>
      <e:attribute name="name">
         <e:data-type name="eqname"/>
      </e:attribute>
      <e:attribute name="priority">
         <e:data-type name="decimal"/>
      </e:attribute>
      <e:attribute name="mode">
         <e:data-type name="tokens"/>
      </e:attribute>
      <e:attribute name="as" default="'item()*'">
         <e:data-type name="sequence-type"/>
      </e:attribute>
      <e:attribute name="visibility">
         <e:constant value="public"/>
         <e:constant value="private"/>
         <e:constant value="final"/>
         <e:constant value="abstract"/>
      </e:attribute>
      <e:sequence>
         <e:element repeat="zero-or-one" name="context-item"/>
         <e:element repeat="zero-or-more" name="param"/>
         <e:model name="sequence-constructor"/>
      </e:sequence>
      <e:allowed-parents>
         <e:parent name="package"/>
         <e:parent name="stylesheet"/>
         <e:parent name="transform"/>
         <e:parent name="override"/>
      </e:allowed-parents>
   </e:element-syntax><p>
               <termdef id="dt-template" term="template">An <elcode>xsl:template</elcode>
                  declaration defines a <term>template</term>, which contains a <termref def="dt-sequence-constructor">sequence constructor</termref>;
                  this sequence constructor is evaluated to determine
                     the result of the template. A template can serve either as a <termref def="dt-template-rule">template rule</termref>, invoked by matching items against a <termref def="dt-pattern">pattern</termref>, or as a <termref def="dt-named-template">named
                     template</termref>, invoked explicitly by name. It is also possible for the
                  same template to serve in both capacities.</termdef>
            </p><p>
               <error spec="XT" type="static" class="SE" code="0500"><p>An <elcode>xsl:template</elcode> element <rfc2119>must</rfc2119> have either a
                        <code nobreak="false">match</code> attribute or a <code nobreak="false">name</code> attribute, or both. An
                        <elcode>xsl:template</elcode> element that has no <code nobreak="false">match</code>
                     attribute <rfc2119>must</rfc2119> have no <code nobreak="false">mode</code> attribute and no
                        <code nobreak="false">priority</code> attribute. An
                           <elcode>xsl:template</elcode> element that has no <code nobreak="false">name</code>
                        attribute <rfc2119>must</rfc2119> have no <code nobreak="false">visibility</code>
                        attribute.</p></error>
            </p><p>If an <elcode>xsl:template</elcode> element has a <code nobreak="false">match</code> attribute, then
               it is a <termref def="dt-template-rule">template rule</termref>. If it has a
                  <code nobreak="false">name</code> attribute, then it is a <termref def="dt-named-template">named
                  template</termref>.</p><p>A <termref def="dt-template">template</termref> may be invoked in a number of ways,
               depending on whether it is a <termref def="dt-template-rule">template rule</termref>,
               a <termref def="dt-named-template">named template</termref>, or both. The result of
               invoking the template is the result of evaluating the <termref def="dt-sequence-constructor">sequence constructor</termref> contained in the
                  <elcode>xsl:template</elcode> element (see <specref ref="sequence-constructors"/>).</p><p>For details of the optional <elcode>xsl:context-item</elcode> child
               element, see <specref ref="declaring-context-item"/>.</p><p>If an <code nobreak="false">as</code> attribute of the <elcode>xsl:template</elcode> element is
               present, the <code nobreak="false">as</code> attribute defines the required type of the result. The
               result of evaluating the <termref def="dt-sequence-constructor">sequence
                  constructor</termref> is then converted to the required type using the 
               <termref def="dt-coercion-rules"/>. If no
                  <code nobreak="false">as</code> attribute is specified, the default value is <code nobreak="false">item()*</code>,
               which permits any value. No conversion then takes place.</p><p>
               <error spec="XT" type="type" class="TE" code="0505"><p>It is a <termref def="dt-type-error">type error</termref> if the result of
                     evaluating the <termref def="dt-sequence-constructor">sequence
                        constructor</termref> cannot be coerced to the required type.</p></error>
            </p><p>If the <code nobreak="false">visibility</code> attribute is present with the value
                  <code nobreak="false">abstract</code> then (a) the <termref def="dt-sequence-constructor"/>
               defining the template body <rfc2119>must</rfc2119> be empty: that is, the only
               permitted children are <elcode>xsl:context-item</elcode> and
                  <elcode>xsl:param</elcode>, and (b) there <rfc2119>must</rfc2119> be no
                  <code nobreak="false">match</code> attribute.</p><p>If the parent of the <elcode>xsl:template</elcode> element is an
               <elcode>xsl:override</elcode> element, then either or both of the following conditions
               must be true:</p><olist><item><p>There is a <code nobreak="false">name</code> attribute, and the <termref def="dt-package">package</termref> identified by the containing
                  <elcode>xsl:use-package</elcode> element contains among its <termref def="dt-component">components</termref> a <termref def="dt-named-template">named
                        template</termref> whose <termref def="dt-symbolic-identifier">symbolic
                           identifier</termref> is the same as that of this named template, and which has a <termref def="dt-compatible">compatible</termref> signature.</p></item><item><p>Both the following conditions are true:</p><olist><item><p>There is a <code nobreak="false">match</code> attribute.</p></item><item><p>The value of the <code nobreak="false">mode</code> attribute,
                        or in its absence the string <code nobreak="false">#default</code>,
                        is a whitespace-separated sequence of tokens in which each token satisfies
                        one of the following conditions:</p><olist><item><p>The token is an EQName representing the name of a mode that is exposed,
                           with visibility equal to <code nobreak="false">public</code>, by the package identified by the containing
                           <elcode>xsl:use-package</elcode> element.</p></item><item><p>The token is <code nobreak="false">#default</code>, and there is an ancestor-or-self element with
                              a <code nobreak="false">default-mode</code> attribute whose value is an EQName representing the name of a mode that is exposed,
                              with visibility equal to <code nobreak="false">public</code>, by the package identified by the containing
                              <elcode>xsl:use-package</elcode> element.</p></item></olist></item></olist><note><p>The token <code nobreak="false">#unnamed</code> is not allowed because the unnamed mode never has public visibility. 
                     The token <code nobreak="false">#all</code> is not allowed because its intended meaning would not be obvious.
                  </p></note></item></olist></div2><div2 id="defining-template-rules"><head>Defining Template Rules</head><p>This section describes <termref def="dt-template-rule">template rules</termref>.
                  <termref def="dt-named-template">Named templates</termref> are described in
                  <specref ref="named-templates"/>.</p><p>A <termref def="dt-template-rule">template rule</termref> is specified using the
                  <elcode>xsl:template</elcode> element with a <code nobreak="false">match</code> attribute. The
                  <code nobreak="false">match</code> attribute is a <nt xmlns:xlink="http://www.w3.org/1999/xlink" def="doc-xslt40-Pattern" xlink:type="simple">Pattern</nt> that identifies
               the items to which the rule applies. The result of
               applying the template rule is the result of evaluating the sequence constructor
               contained in the <elcode>xsl:template</elcode> element, with the matching item used as the <termref def="dt-context-item">context item</termref>.</p><example><head>A Simple Template Rule</head><p>For example, an XML document might contain:</p><eg xml:space="preserve" role="xml">This is an &lt;emph&gt;important&lt;/emph&gt; point.</eg><p>The following <termref def="dt-template-rule">template rule</termref> matches
                     <code nobreak="false">emph</code> elements and produces a <code nobreak="false">fo:wrapper</code> element with
                  a <code nobreak="false">font-weight</code> property of <code nobreak="false">bold</code>.</p><eg xml:space="preserve" role="xslt-declaration">&lt;xsl:template match="emph"&gt;
  &lt;fo:wrapper font-weight="bold" 
              xmlns:fo="http://www.w3.org/1999/XSL/Format"&gt;
    &lt;xsl:apply-templates/&gt;
  &lt;/fo:wrapper&gt;
&lt;/xsl:template&gt;
</eg></example><p>A <termref def="dt-template-rule">template rule</termref> is evaluated when an
                  <elcode>xsl:apply-templates</elcode> instruction selects an item that matches the pattern specified in the <code nobreak="false">match</code>
               attribute. The <elcode>xsl:apply-templates</elcode> instruction is described in the
               next section. If several template rules match a selected item, only one of them is evaluated, as described in <specref ref="conflict"/>.</p></div2><div2 id="patterns"><head>Patterns</head><p>In XSLT 4.0, patterns can match any kind of item: atomic items and
               function items as well as nodes.</p><p>A <termref def="dt-template-rule">template rule</termref> identifies the items to which it applies by means of a pattern. As
               well as being used in template rules, patterns are used for numbering (see <specref ref="number"/>), for grouping (see <specref ref="grouping"/>), and for declaring
                  <termref def="dt-key">keys</termref> (see <specref ref="key"/>).</p><p><termdef id="dt-pattern" term="pattern">A <term>pattern</term> specifies a set of
                  conditions on an item. An item that satisfies the conditions matches the pattern; an
                     item that does not satisfy the conditions
                  does not match the pattern.</termdef></p><p>There are several kinds of pattern:</p><ulist diff="chg" at="2022-01-01"><item><p><termdef id="dt-predicate-pattern" term="predicate pattern">A <term>predicate pattern</term> is written as
                           <code nobreak="false">.</code> (dot) followed by zero or more predicates in square
                        brackets, and it matches any item for which each of the predicates evaluates
                        to <code nobreak="false">true</code>.</termdef></p><p>The detailed semantics are given in <specref ref="predicate-patterns"/>. This construct can be used to match items of any
                     kind (nodes, atomic items, and function items). For example, the pattern
                     <code nobreak="false">.[starts-with(., '$')]</code> matches any string that starts with the
                     character <code nobreak="false">$</code>, or a node whose atomized value starts with 
                     <code nobreak="false">$</code>. This example shows a predicate pattern with a single
                     predicate, but the grammar allows any number of predicates (zero or more).</p></item><item><p><termdef id="dt-type-pattern" term="type pattern">A <term>type pattern</term> is written as
                     <code nobreak="false">~T</code> (where <var>T</var> is an <xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="XP40" ref="prod-xpath40-ItemType" xlink:type="simple">ItemType</xnt>)
                     followed by zero or more predicates in square
                     brackets, and it matches any item that is coercible to type <var>T</var> for which each of the predicates evaluates
                     to <code nobreak="false">true</code>.</termdef></p><p>The parameter <var>T</var> can also be a <xtermref spec="XP40" ref="dt-choice-item-type"/>, 
                     consisting of a parenthesized sequence of item types separated by <code nobreak="false">"|"</code>.
                  For example, <code nobreak="false">~(array(*) | map(*))</code> matches arrays and maps, while 
                  <code nobreak="false">~(text() | comment())</code> matches text nodes and comment nodes.</p><p>The type pattern <code nobreak="false">match="~(text() | comment())"</code> has almost the same effect as
                  the <termref def="dt-gnode-pattern"/> <code nobreak="false">match="text() | comment()"</code>, 
                     but the rules for calculating a default priority
                  are different: see <specref ref="default-priority"/>.</p></item><item><p><termdef id="dt-gnode-pattern" term="GNode pattern">An <term>GNode pattern</term> uses a subset of
                        the syntax for path expressions, and is defined to match a GNode if the
                        corresponding path expression would select the GNode.</termdef></p><p>The syntax for GNode patterns
                        (<nt xmlns:xlink="http://www.w3.org/1999/xlink" def="doc-xslt40-GNodePattern" xlink:type="simple">GNodePattern</nt> in the grammar:
                        see <specref ref="pattern-syntax"/>) is a subset of the syntax for
                        <termref def="dt-expression">expressions</termref>. GNode patterns
                        are used only for matching nodes, and the same syntax may match either
                        an XNode or a JNode.
                     As explained in detail below, a GNode matches a GNode pattern if the
                     equivalent XPath expression selects the GNode when evaluated with respect
                     to some appropriate context.</p></item></ulist><note><p>The specification uses the phrases <emph>an item matches a pattern</emph> and
                     <emph>a pattern matches an item</emph> interchangeably. They are equivalent: an
                  item matches a pattern if and only if the pattern matches the item.</p></note><div3 id="pattern-examples"><head>Examples of Patterns</head><example id="pattern-examples-1"><head>Patterns</head><p>Here are some examples of patterns:</p><ulist><item><p><emph>Predicate Patterns:</emph></p><olist><item><p><code nobreak="false">.</code> matches any item.</p></item><item><p><code nobreak="false">.[. castable as xs:date]</code> matches any item
                                 that can be successfully cast to <code nobreak="false">xs:date</code>: for example,
                              an <code nobreak="false">xs:date</code> or <code nobreak="false">xs:dateTime</code> value, or a string
                              in the lexical form of a date, or a node whose typed value is an <code nobreak="false">xs:date</code>
                              or a string in the form of a date.</p></item><item><p><code nobreak="false">.[string() =&gt; matches('^[0-9]$')]</code> matches any
                                 item whose string value is a sequence of digits.</p></item><item><p><code nobreak="false">.[. castable as xs:date][xs:date(.) le current-date()]</code> matches any
                                 item that is castable to <code nobreak="false">xs:date</code> provided that the result of casting
                                 the value to <code nobreak="false">xs:date</code> is a date in the past.</p></item></olist></item><item diff="add" at="2022-01-01"><p><emph>Type Patterns</emph></p><olist><item><p><code nobreak="false">~item()</code> matches any item.</p></item><item><p><code nobreak="false">~node()</code> matches any XNode.
                                 (Note the distinction from the pattern <code nobreak="false">node()</code>.)</p></item><item><p><code nobreak="false">~xs:date</code> matches any
                                 atomic item of type <code nobreak="false">xs:date</code> (or a type derived by
                                 restriction from <code nobreak="false">xs:date</code>).</p></item><item><p><code nobreak="false">~xs:date[. gt current-date()]</code> matches any date in
                                 the future.</p></item><item><p><code nobreak="false">~xs:string[starts-with(., 'e')]</code> matches any <code nobreak="false">xs:string</code>
                                 value that starts with the letter <code nobreak="false">e</code>. Note there is no type conversion; the pattern
                              will not match an <code nobreak="false">xs:untypedAtomic</code> or <code nobreak="false">xs:anyURI</code> value,
                              nor will it match a node.</p></item><item><p><code nobreak="false">~fn(*)</code> matches any
                                 function item.</p></item><item><p><code nobreak="false">~(fn($x as xs:integer) as xs:boolean)[.(42)]</code> matches any function that
                                 accepts an <code nobreak="false">xs:integer</code> argument and returns a boolean result, provided
                                 that the result of calling the function with the argument value <code nobreak="false">42</code> is <code nobreak="false">true</code>.</p></item><item><p><code nobreak="false">~(xs:date | xs:dateTime | xs:time)</code> matches any atomic item
                                 that is an instance of <code nobreak="false">xs:date</code>, <code nobreak="false">xs:dateTime</code>, or <code nobreak="false">xs:time</code>.</p></item><item><p><code nobreak="false">~(array(xs:date) | array(xs:dateTime) | array(xs:time))</code> matches any array whose
                                 members are all of type <code nobreak="false">xs:date</code>, any array whose
                                 members are all of type <code nobreak="false">xs:dateTime</code>, or any array whose
                                 members are all of type <code nobreak="false">xs:time</code>. Contrast 
                              <code nobreak="false">~array(xs:date | xs:dateTime | xs:time)</code> which allows
                              the three types to be mixed within a single array.</p></item><item><p><code nobreak="false">~map((xs:string | xs:untypedAtomic), *)</code> matches any map
                                 whose keys are all instances of <code nobreak="false">xs:string</code> or <code nobreak="false">xs:untypedAtomic</code>.</p></item><item><p><code nobreak="false">~enum("red", "green", "blue")</code> matches any one of the three strings
                                 <code nobreak="false">"red"</code>, <code nobreak="false">"green"</code>, or <code nobreak="false">"blue"</code>.</p></item><item><p><code nobreak="false">~record(first, last)[?location = 'UK']</code> matches any map whose keys include the strings <code nobreak="false">"first"</code>
                                 and <code nobreak="false">"last"</code>, and that also has an entry with key <code nobreak="false">"location"</code> whose
                              value is <code nobreak="false">"UK"</code>.</p><p>This can also be written <code nobreak="false">~record(first, last, location as enum('UK'))</code>.</p></item><item><p><code nobreak="false">~record(longitude, latitude)</code> matches any map with exactly two entries,
                                 whose keys are the strings <code nobreak="false">"longitude"</code>
                                 and <code nobreak="false">"latitude"</code>.</p></item><item><p><code nobreak="false">~record(title, author as enum("Dickens"))</code> matches having an entry whose keys is the string <code nobreak="false">"title"</code>,
                                 plus an entry whose key is the string <code nobreak="false">"author"</code> and whose associated value
                                 is the string <code nobreak="false">"Dickens"</code>.</p></item><item><p><code nobreak="false">~array(xs:integer)[array:size(.) eq 4]</code> matches any array of four integers.</p></item><item><p><code nobreak="false">~array(record(first, last))</code> matches any array of maps where each map
                                 contains entries with keys <code nobreak="false">"first"</code> and <code nobreak="false">"last"</code>. Note that
                              this includes the empty array.</p></item><item><p><code nobreak="false">~array(record(first, last))[array:size(.) gt 0]</code> matches any non-empty array of maps where each map
                                 contains entries with keys <code nobreak="false">"first"</code> and <code nobreak="false">"last"</code>. </p></item><item><p><code nobreak="false">~complex</code> matches any value that is an instance of the item type 
                                 declared in an <elcode>xsl:item-type</elcode> or <elcode>xsl:record-type</elcode>
                                 declaration with name <code nobreak="false">"complex"</code></p></item><item><p><code nobreak="false">~complex[?i eq 0]</code> matches any value that is an instance of the 
                                 item type declared in an <elcode>xsl:item-type</elcode> or <elcode>xsl:record-type</elcode>
                                 declaration with name <code nobreak="false">"complex"</code> and that is a map with an entry having key <code nobreak="false">i</code> and value zero.</p></item><item><p><code nobreak="false">~jnode("date of birth", xs:date)</code> matches a JNode that encapsulates a map entry
                              whose key is the string <code nobreak="false">"date of birth"</code> and whose associated value is an atomic item
                              of type <code nobreak="false">xs:date</code>.</p></item></olist></item><item><p><emph>Patterns Matching XNodes</emph></p><olist><item><p><code nobreak="false">*</code> matches any element node.</p></item><item><p><code nobreak="false">para</code> matches any <code nobreak="false">para</code> element.</p></item><item><p><code nobreak="false">chapter|appendix</code> matches any <code nobreak="false">chapter</code> element
                              and any <code nobreak="false">appendix</code> element.</p></item><item diff="add" at="2022-12-13"><p><code nobreak="false">child::(chapter|appendix)</code> matches any <code nobreak="false">chapter</code> element
                                 and any <code nobreak="false">appendix</code> element. Note that although the <code nobreak="false">child</code> axis
                              is explicitly written, an element can match even though it has no parent.</p></item><item><p><code nobreak="false">olist/entry</code> matches any <code nobreak="false">entry</code> element with an
                              <code nobreak="false">olist</code> parent.</p></item><item><p><code nobreak="false">appendix//para</code> matches any <code nobreak="false">para</code> element with an
                              <code nobreak="false">appendix</code> ancestor element.</p></item><item diff="add" at="2022-12-13"><p><code nobreak="false">appendix/descendant::(para|table)</code> matches any <code nobreak="false">para</code> 
                                 or <code nobreak="false">table</code>element with an
                                 <code nobreak="false">appendix</code> ancestor element.</p></item><item><p><code nobreak="false">schema-element(us:address)</code> matches any element that is
                              annotated as an instance of the type defined by the schema element
                              declaration <code nobreak="false">us:address</code>, and whose name is either
                              <code nobreak="false">us:address</code> or the name of another element in its
                              substitution group. </p></item><item><p><code nobreak="false">attribute(*, xs:date)</code> matches any attribute annotated as
                              being of type <code nobreak="false">xs:date</code>.</p></item><item><p><code nobreak="false">/</code> matches a document node.</p></item><item><p><code nobreak="false">document-node()</code> matches a document node.</p></item><item><p><code nobreak="false">document-node(schema-element(my:invoice))</code> matches the
                              document node of a document whose document element is named
                              <code nobreak="false">my:invoice</code> and matches the type defined by the global
                              element declaration <code nobreak="false">my:invoice</code>.</p></item><item><p><code nobreak="false">text()</code> matches any text node.</p></item><item><p><code nobreak="false">namespace-node()</code> matches any namespace
                              node.</p></item><item><p><code nobreak="false">node()</code> matches any node other than an attribute node,
                              namespace node, or document node.</p></item><item><p><code nobreak="false">id("W33")</code> matches the element with unique ID
                              <code nobreak="false">W33</code>. </p></item><item><p><code nobreak="false">para[1]</code> matches any <code nobreak="false">para</code> element that is the
                              first <code nobreak="false">para</code> child element of its parent. It also matches a
                              parentless <code nobreak="false">para</code> element.</p></item><item><p><code nobreak="false">//para</code> matches any <code nobreak="false">para</code> element in a tree that is rooted at a document node.</p></item><item><p><code nobreak="false">bullet[position() mod 2 = 0]</code> matches any <code nobreak="false">bullet</code>
                              element that is an even-numbered <code nobreak="false">bullet</code> child of its
                              parent.</p></item><item><p><code nobreak="false">div[@class="appendix"]//p</code> matches any <code nobreak="false">p</code> element
                              with a <code nobreak="false">div</code> ancestor element that has a <code nobreak="false">class</code>
                              attribute with value <code nobreak="false">appendix</code>. </p></item><item><p><code nobreak="false">@class</code> matches any <code nobreak="false">class</code> attribute
                              (<emph>not</emph> any element that has a <code nobreak="false">class</code>
                              attribute).</p></item><item><p><code nobreak="false">@(class|type|kind)</code> matches any attribute named <code nobreak="false">class</code> 
                              or <code nobreak="false">type</code> or <code nobreak="false">kind</code>.</p></item><item><p><code nobreak="false">@*</code> matches any attribute node.</p></item><item><p><code nobreak="false">$xyz</code> matches any GNode that is present in
                              the value of the variable <code nobreak="false">$xyz</code>. Note that it will not
                              match any other item that is present in the value of the variable.</p></item><item><p><code nobreak="false">$xyz//*</code> matches any element that is a
                              descendant of a node that is present in the value of the variable
                              <code nobreak="false">$xyz</code>. It will also match certain JNodes if the
                              variable <code nobreak="false">$xyz</code> includes JNodes.</p></item><item><p><code nobreak="false">doc('product.xml')//*</code> matches any element
                              within the document whose document URI is <code nobreak="false">product.xml</code>.</p></item></olist></item><item><p><emph>Patterns matching JNodes</emph></p><olist><item><p>The patterns <code nobreak="false">jnode()</code>, <code nobreak="false">jnode(*)</code>, and <code nobreak="false">jnode(*, item()*)</code> 
                                 are equivalent, and match any JNode.</p></item><item><p><code nobreak="false">jnode("date of birth")</code> matches any JNode representing a map
                                 entry with key <code nobreak="false">"date of birth"</code>.</p></item><item><p><code nobreak="false">jnode(*, array(xs:integer))</code> matches any JNode representing a map
                                 entry or array item whose value is an array of integers.</p></item><item><p><code nobreak="false">jnode(books, array(record(Author, Title)))</code> 
                                 matches any JNode representing a map
                                 entry whose key is <code nobreak="false">"books"</code> and whose content is an array of records,
                                 each record having entries named <code nobreak="false">"Author"</code> and <code nobreak="false">"Title"</code> (with other
                                 entries also allowed).</p></item><item><p><code nobreak="false">jnode(*, record(Author as enum("Dickens"), Title))</code> 
                                 matches any JNode whose content is a map
                                 having an entry with key <code nobreak="false">"Author"</code> and value <code nobreak="false">"Dickens"</code>,
                                 plus an entry with key <code nobreak="false">"Title"</code> (with other
                                 entries also allowed).</p></item><item><p><code nobreak="false">jnode(())</code> matches any root JNode (that is, a JNode whose <term>·jkey·</term> property
                              is absent).</p></item><item><p><code nobreak="false">jnode((), array(map(*)))</code> matches any root JNode whose <term>·jvalue·</term> property
                                 is an array of maps.</p></item></olist></item></ulist></example></div3><div3 id="pattern-syntax"><head>Syntax of Patterns</head><p>
                  <error spec="XT" type="static" class="SE" code="0340"><p>Where an attribute is defined to contain a <termref def="dt-pattern">pattern</termref>, it is a <termref def="dt-static-error">static
                           error</termref> if the pattern does not match the production <nt xmlns:xlink="http://www.w3.org/1999/xlink" def="doc-xslt40-Pattern" xlink:type="simple">Pattern</nt>.</p></error></p><p>The complete grammar for patterns is listed in <specref ref="pattern-syntax-summary"/>. 
                  It uses the notation defined in <xspecref spec="XP40" ref="EBNFNotation">Notation</xspecref>. </p><p>The lexical rules for patterns are the same as the lexical rules
                  for XPath expressions, as defined in <xspecref spec="XP40" ref="lexical-structure">Lexical structure</xspecref>. Comments are permitted between tokens, using the
                  syntax <code nobreak="false">(: ... :)</code>. All other provisions of the XPath grammar apply
                  where relevant, for example the rules for whitespace handling and
                  extra-grammatical constraints.</p><scrap headstyle="show" id="Patterns-scrap"><prod id="doc-xslt40-Pattern"><lhs>Pattern</lhs><rhs><nt xmlns:xlink="http://www.w3.org/1999/xlink" def="prod-xslt40-PredicatePattern" xlink:type="simple">PredicatePattern</nt>  |  <nt xmlns:xlink="http://www.w3.org/1999/xlink" def="prod-xslt40-TypePattern" xlink:type="simple">TypePattern</nt>  |  <nt xmlns:xlink="http://www.w3.org/1999/xlink" def="prod-xslt40-GNodePattern" xlink:type="simple">GNodePattern</nt></rhs></prod><prod id="doc-xslt40-Pattern-PredicatePattern"><lhs>PredicatePattern</lhs><rhs>"."  <xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="XP40" ref="prod-xpath40-Predicate" xlink:type="simple">Predicate</xnt>*</rhs></prod><prod id="doc-xslt40-Pattern-TypePattern"><lhs>TypePattern</lhs><rhs>"~"  <xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="XP40" ref="prod-xpath40-ItemType" xlink:type="simple">ItemType</xnt>  <xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="XP40" ref="prod-xpath40-Predicate" xlink:type="simple">Predicate</xnt>*</rhs></prod><prod id="doc-xslt40-Pattern-GNodePattern"><lhs>GNodePattern</lhs><rhs><nt xmlns:xlink="http://www.w3.org/1999/xlink" def="prod-xslt40-UnionExprP" xlink:type="simple">UnionExprP</nt></rhs></prod></scrap><p>Patterns fall into three groups:</p><ulist diff="add" at="2022-01-01"><item><p>A <code nobreak="false">PredicatePattern</code> matches items according to conditions that the item must
                  satisfy: for example <code nobreak="false">.[. castable as xs:integer]</code> matches any value (it might
                  be an atomic item, a node, or an array) that is castable as an integer.</p></item><item><p>A <code nobreak="false">TypePattern</code> matches items according to their type. For example
                  <code nobreak="false">~xs:integer</code> matches an atomic item that is an instance of <code nobreak="false">xs:integer</code>,
                  while <code nobreak="false">~record(longitude, latitude)</code> matches a map that has exactly two entries, with
                  keys <code nobreak="false">"longitude"</code> and <code nobreak="false">"latitude"</code></p></item><item><p>An <code nobreak="false">GNodePattern</code> matches GNodes in a GTree (for example, a tree
                     representing the contents of an XML or JSON document), by specifying a path that
                  can be used to locate the nodes: for example <code nobreak="false">order</code> matches an element node
                  named <code nobreak="false">order</code> within an XTree, or a JNode with ·jkey· <code nobreak="false">"order"</code>
                        within a JTree; similarly, <code nobreak="false">billing-address/city</code> matches an element node named <code nobreak="false">city</code>
                  whose parent node is an element named <code nobreak="false">billing-address</code>, or a JNode with ·jkey· <code nobreak="false">"city"</code>
                  whose parent is a JNode with ·jkey· <code nobreak="false">"billing-address"</code>.</p></item></ulist><p>The following sections define the rules for each of these groups.</p><div4 id="predicate-patterns"><head>Predicate Patterns</head><scrap headstyle="show" id="PredicatePatterns-scrap"><prod id="doc-xslt40-PredicatePattern"><lhs>PredicatePattern</lhs><rhs>"."  <xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="XP40" ref="prod-xpath40-Predicate" xlink:type="simple">Predicate</xnt>*</rhs></prod><prod id="doc-xslt40-PredicatePattern-Predicate"><lhs>Predicate</lhs><rhs>"["  <xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="XP40" ref="prod-xpath40-Expr" xlink:type="simple">Expr</xnt>  "]"</rhs></prod><prod id="doc-xslt40-PredicatePattern-Expr"><lhs>Expr</lhs><rhs>(<xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="XP40" ref="prod-xpath40-ExprSingle" xlink:type="simple">ExprSingle</xnt> ++ ",")</rhs></prod><prod id="doc-xslt40-PredicatePattern-ExprSingle"><lhs>ExprSingle</lhs><rhs><xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="XP40" ref="prod-xpath40-ForExpr" xlink:type="simple">ForExpr</xnt><br/>|  <xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="XP40" ref="prod-xpath40-LetExpr" xlink:type="simple">LetExpr</xnt><br/>|  <xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="XP40" ref="prod-xpath40-QuantifiedExpr" xlink:type="simple">QuantifiedExpr</xnt><br/>|  <xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="XP40" ref="prod-xpath40-IfExpr" xlink:type="simple">IfExpr</xnt></rhs></prod><prod id="doc-xslt40-PredicatePattern-ForExpr"><lhs>ForExpr</lhs><rhs><xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="XP40" ref="prod-xpath40-ForClause" xlink:type="simple">ForClause</xnt>  <xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="XP40" ref="prod-xpath40-ForLetReturn" xlink:type="simple">ForLetReturn</xnt></rhs></prod><prod id="doc-xslt40-PredicatePattern-ForClause"><lhs>ForClause</lhs><rhs>"for"  (<xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="XP40" ref="prod-xpath40-ForBinding" xlink:type="simple">ForBinding</xnt> ++ ",")</rhs></prod><prod id="doc-xslt40-PredicatePattern-ForLetReturn"><lhs>ForLetReturn</lhs><rhs><xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="XP40" ref="prod-xpath40-ForExpr" xlink:type="simple">ForExpr</xnt>  |  <xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="XP40" ref="prod-xpath40-LetExpr" xlink:type="simple">LetExpr</xnt>  |  ("return"  <xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="XP40" ref="prod-xpath40-ExprSingle" xlink:type="simple">ExprSingle</xnt>)</rhs></prod><prod id="doc-xslt40-PredicatePattern-LetExpr"><lhs>LetExpr</lhs><rhs><xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="XP40" ref="prod-xpath40-LetClause" xlink:type="simple">LetClause</xnt>  <xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="XP40" ref="prod-xpath40-ForLetReturn" xlink:type="simple">ForLetReturn</xnt></rhs></prod><prod id="doc-xslt40-PredicatePattern-LetClause"><lhs>LetClause</lhs><rhs>"let"  (<xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="XP40" ref="prod-xpath40-LetBinding" xlink:type="simple">LetBinding</xnt> ++ ",")</rhs></prod><prod id="doc-xslt40-PredicatePattern-QuantifiedExpr"><lhs>QuantifiedExpr</lhs><rhs>("some"  |  "every")  (<xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="XP40" ref="prod-xpath40-QuantifierBinding" xlink:type="simple">QuantifierBinding</xnt> ++ ",")  "satisfies"  <xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="XP40" ref="prod-xpath40-ExprSingle" xlink:type="simple">ExprSingle</xnt></rhs></prod><prod id="doc-xslt40-PredicatePattern-QuantifierBinding"><lhs>QuantifierBinding</lhs><rhs><xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="XP40" ref="prod-xpath40-VarNameAndType" xlink:type="simple">VarNameAndType</xnt>  "in"  <xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="XP40" ref="prod-xpath40-ExprSingle" xlink:type="simple">ExprSingle</xnt></rhs></prod><prod id="doc-xslt40-PredicatePattern-IfExpr"><lhs>IfExpr</lhs><rhs>"if"  "("  <xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="XP40" ref="prod-xpath40-Expr" xlink:type="simple">Expr</xnt>  ")"  (<xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="XP40" ref="prod-xpath40-UnbracedActions" xlink:type="simple">UnbracedActions</xnt>  |  <xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="XP40" ref="prod-xpath40-BracedAction" xlink:type="simple">BracedAction</xnt>)</rhs></prod><prod id="doc-xslt40-PredicatePattern-UnbracedActions"><lhs>UnbracedActions</lhs><rhs>"then"  <xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="XP40" ref="prod-xpath40-ExprSingle" xlink:type="simple">ExprSingle</xnt>  "else"  <xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="XP40" ref="prod-xpath40-ExprSingle" xlink:type="simple">ExprSingle</xnt></rhs></prod><prod id="doc-xslt40-PredicatePattern-BracedAction"><lhs>BracedAction</lhs><rhs><xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="XP40" ref="prod-xpath40-EnclosedExpr" xlink:type="simple">EnclosedExpr</xnt></rhs></prod></scrap><p>A <nt xmlns:xlink="http://www.w3.org/1999/xlink" def="doc-xslt40-PredicatePattern" xlink:type="simple">PredicatePattern</nt>
                     <var>PP</var> matches an item <var>J</var> if and only if the XPath expression taking
                     the same form as <var>PP</var> returns a non-empty sequence when evaluated with a
                     <termref def="dt-singleton-focus"/> based on <var>J</var>.</p><note><p>The pattern <code nobreak="false">.</code>, which is a <code nobreak="false">PredicatePattern</code> with no predicates,
                        matches every item.</p><p>A predicate with the numeric value 1 (one) always matches, and a predicate with
                        any other numeric value never matches. Numeric predicates in a
                        <code nobreak="false">PredicatePattern</code> are therefore not useful, but are defined this
                        way in the interests of consistency with XPath.</p><p>The predicate pattern <code nobreak="false">.[<var>P1</var>][<var>P2</var>][<var>P3</var>]</code>
                     is equivalent to the type pattern <code nobreak="false">~item()[<var>P1</var>][<var>P2</var>][<var>P3</var>]</code>.</p></note><p>For example, the pattern <code nobreak="false">.[contains(., "XSLT")]</code>
                  matches any item whose atomized value contains <code nobreak="false">"XSLT"</code> as a substring. 
                  It matches values such as the string <code nobreak="false">"XSLT Transformations"</code>, the
                     <code nobreak="false">xs:anyURI</code> value
                     <code nobreak="false">http://www.w3.org/TR/XSLT</code>, the attribute node 
                     <code nobreak="false">class="XSD XSLT XPath"</code>, and the singleton array <code nobreak="false">[ "XSLT 4.0" ]</code>.</p><note><p>
                     Evaluation of this example pattern may fail with a dynamic error if the item in question
                     has an atomized value that is not a string, or that is a sequence of strings: an example might
                     be the array <code nobreak="false">[ "XSLT", 1999 ]</code>. It will also fail if the item cannot be atomized,
                     for example if it is a map. The rules in <specref ref="pattern-errors"/> cause these errors
                     to be masked: they simply result in the pattern being treated as non-matching.
                  </p></note></div4><div4 id="type-patterns"><head>Type Patterns</head><changes><change issue="400" PR="401" date="2023-03-21">
                        Patterns (especially those used in template rules) can now be defined
                        by reference to item types, so any item type can be used as a match
                        pattern. For example <code nobreak="false">match="~record(longitude, latitude)"</code>
                        matches any map that includes the key values <code nobreak="false">"longitude"</code>
                        and <code nobreak="false">"latitude"</code>.
                     </change><change issue="2365" PR="2413" date="2026-01-28">
                        Extensible map types are dropped; instead, the coercion rules cause undefined
                        map entries to be discarded.
                     </change></changes><scrap headstyle="show" id="TypePatterns-scrap"><prod id="doc-xslt40-TypePattern"><lhs>TypePattern</lhs><rhs>"~"  <xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="XP40" ref="prod-xpath40-ItemType" xlink:type="simple">ItemType</xnt>  <xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="XP40" ref="prod-xpath40-Predicate" xlink:type="simple">Predicate</xnt>*</rhs></prod><prod id="doc-xslt40-TypePattern-ItemType"><lhs>ItemType</lhs><rhs><xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="XP40" ref="prod-xpath40-RegularItemType" xlink:type="simple">RegularItemType</xnt>  |  <xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="XP40" ref="prod-xpath40-FunctionType" xlink:type="simple">FunctionType</xnt>  |  <xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="XP40" ref="prod-xpath40-TypeName" xlink:type="simple">TypeName</xnt>  |  <xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="XP40" ref="prod-xpath40-ChoiceItemType" xlink:type="simple">ChoiceItemType</xnt></rhs></prod><prod id="doc-xslt40-TypePattern-RegularItemType"><lhs>RegularItemType</lhs><rhs><xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="XP40" ref="prod-xpath40-AnyItemType" xlink:type="simple">AnyItemType</xnt>  |  <xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="XP40" ref="prod-xpath40-XNodeType" xlink:type="simple">XNodeType</xnt>  |  <xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="XP40" ref="prod-xpath40-GNodeType" xlink:type="simple">GNodeType</xnt>  |  <xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="XP40" ref="prod-xpath40-JNodeType" xlink:type="simple">JNodeType</xnt>  |  <xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="XP40" ref="prod-xpath40-MapType" xlink:type="simple">MapType</xnt>  |  <xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="XP40" ref="prod-xpath40-ArrayType" xlink:type="simple">ArrayType</xnt>  |  <xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="XP40" ref="prod-xpath40-RecordType" xlink:type="simple">RecordType</xnt>  |  <xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="XP40" ref="prod-xpath40-EnumerationType" xlink:type="simple">EnumerationType</xnt></rhs></prod><prod id="doc-xslt40-TypePattern-AnyItemType"><lhs>AnyItemType</lhs><rhs>"item"  "("  ")"</rhs></prod><prod id="doc-xslt40-TypePattern-XNodeType"><lhs>XNodeType</lhs><rhs><xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="XP40" ref="prod-xpath40-DocumentNodeType" xlink:type="simple">DocumentNodeType</xnt><br/>|  <xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="XP40" ref="prod-xpath40-ElementNodeType" xlink:type="simple">ElementNodeType</xnt><br/>|  <xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="XP40" ref="prod-xpath40-AttributeNodeType" xlink:type="simple">AttributeNodeType</xnt><br/>|  <xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="XP40" ref="prod-xpath40-SchemaElementNodeType" xlink:type="simple">SchemaElementNodeType</xnt><br/>|  <xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="XP40" ref="prod-xpath40-SchemaAttributeNodeType" xlink:type="simple">SchemaAttributeNodeType</xnt><br/>|  <xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="XP40" ref="prod-xpath40-ProcessingInstructionNodeType" xlink:type="simple">ProcessingInstructionNodeType</xnt><br/>|  <xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="XP40" ref="prod-xpath40-CommentNodeType" xlink:type="simple">CommentNodeType</xnt><br/>|  <xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="XP40" ref="prod-xpath40-TextNodeType" xlink:type="simple">TextNodeType</xnt><br/>|  <xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="XP40" ref="prod-xpath40-NamespaceNodeType" xlink:type="simple">NamespaceNodeType</xnt><br/>|  <xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="XP40" ref="prod-xpath40-AnyXNodeType" xlink:type="simple">AnyXNodeType</xnt></rhs></prod><prod id="doc-xslt40-TypePattern-DocumentNodeType"><lhs>DocumentNodeType</lhs><rhs>"document-node"  "("  (<xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="XP40" ref="prod-xpath40-ElementNodeType" xlink:type="simple">ElementNodeType</xnt>  |  <xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="XP40" ref="prod-xpath40-SchemaElementNodeType" xlink:type="simple">SchemaElementNodeType</xnt>  |  <xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="XP40" ref="prod-xpath40-NameTestUnion" xlink:type="simple">NameTestUnion</xnt>)?  ")"</rhs></prod><prod id="doc-xslt40-TypePattern-ElementNodeType"><lhs>ElementNodeType</lhs><rhs>"element"  "("  (<xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="XP40" ref="prod-xpath40-NameTestUnion" xlink:type="simple">NameTestUnion</xnt>  (","  <xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="XP40" ref="prod-xpath40-TypeName" xlink:type="simple">TypeName</xnt>  "?"?)?)?  ")"</rhs></prod><prod id="doc-xslt40-TypePattern-SchemaElementNodeType"><lhs>SchemaElementNodeType</lhs><rhs>"schema-element"  "("  <xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="XP40" ref="prod-xpath40-ElementName" xlink:type="simple">ElementName</xnt>  ")"</rhs></prod><prod id="doc-xslt40-TypePattern-NameTestUnion"><lhs>NameTestUnion</lhs><rhs>(<xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="XP40" ref="prod-xpath40-NameTest" xlink:type="simple">NameTest</xnt> ++ "|")</rhs></prod><prod id="doc-xslt40-TypePattern-TypeName"><lhs>TypeName</lhs><rhs><xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="XP40" ref="prod-xpath40-EQName" xlink:type="simple">EQName</xnt></rhs></prod><prod id="doc-xslt40-TypePattern-AttributeNodeType"><lhs>AttributeNodeType</lhs><rhs>"attribute"  "("  (<xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="XP40" ref="prod-xpath40-NameTestUnion" xlink:type="simple">NameTestUnion</xnt>  (","  <xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="XP40" ref="prod-xpath40-TypeName" xlink:type="simple">TypeName</xnt>)?)?  ")"</rhs></prod><prod id="doc-xslt40-TypePattern-ElementName"><lhs>ElementName</lhs><rhs><xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="XP40" ref="prod-xpath40-EQName" xlink:type="simple">EQName</xnt></rhs></prod><prod id="doc-xslt40-TypePattern-SchemaAttributeNodeType"><lhs>SchemaAttributeNodeType</lhs><rhs>"schema-attribute"  "("  <xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="XP40" ref="prod-xpath40-AttributeName" xlink:type="simple">AttributeName</xnt>  ")"</rhs></prod><prod id="doc-xslt40-TypePattern-AttributeName"><lhs>AttributeName</lhs><rhs><xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="XP40" ref="prod-xpath40-EQName" xlink:type="simple">EQName</xnt></rhs></prod><prod id="doc-xslt40-TypePattern-ProcessingInstructionNodeType"><lhs>ProcessingInstructionNodeType</lhs><rhs>"processing-instruction"  "("  (<xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="XP40" ref="prod-xpath40-NCName" xlink:type="simple">NCName</xnt>  |  <xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="XP40" ref="prod-xpath40-StringLiteral" xlink:type="simple">StringLiteral</xnt>)?  ")"</rhs></prod><prod id="doc-xslt40-TypePattern-StringLiteral"><lhs>StringLiteral</lhs><rhs><nt xmlns:xlink="http://www.w3.org/1999/xlink" def="prod-xslt40-AposStringLiteral" xlink:type="simple">AposStringLiteral</nt>  |  <nt xmlns:xlink="http://www.w3.org/1999/xlink" def="prod-xslt40-QuotStringLiteral" xlink:type="simple">QuotStringLiteral</nt></rhs><com><loc xmlns:xlink="http://www.w3.org/1999/xlink" href="#ws-explicit" xlink:type="simple" xlink:show="replace" xlink:actuate="onRequest">ws: explicit</loc></com></prod><prod id="doc-xslt40-TypePattern-CommentNodeType"><lhs>CommentNodeType</lhs><rhs>"comment"  "("  ")"</rhs></prod><prod id="doc-xslt40-TypePattern-TextNodeType"><lhs>TextNodeType</lhs><rhs>"text"  "("  ")"</rhs></prod><prod id="doc-xslt40-TypePattern-NamespaceNodeType"><lhs>NamespaceNodeType</lhs><rhs>"namespace-node"  "("  ")"</rhs></prod><prod id="doc-xslt40-TypePattern-AnyXNodeType"><lhs>AnyXNodeType</lhs><rhs>"node"  "("  ")"</rhs></prod><prod id="doc-xslt40-TypePattern-GNodeType"><lhs>GNodeType</lhs><rhs>"gnode"  "("  ")"</rhs></prod><prod id="doc-xslt40-TypePattern-JNodeType"><lhs>JNodeType</lhs><rhs>"jnode"  "("  (("*"  |  <xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="XP40" ref="prod-xpath40-JRootSelector" xlink:type="simple">JRootSelector</xnt>  |  <xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="XP40" ref="prod-xpath40-NCName" xlink:type="simple">NCName</xnt>  |  <xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="XP40" ref="prod-xpath40-Constant" xlink:type="simple">Constant</xnt>)  (","  <xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="XP40" ref="prod-xpath40-SequenceType" xlink:type="simple">SequenceType</xnt>)?)?  ")"</rhs></prod><prod id="doc-xslt40-TypePattern-JRootSelector"><lhs>JRootSelector</lhs><rhs>"("  ")"</rhs></prod><prod id="doc-xslt40-TypePattern-Constant"><lhs>Constant</lhs><rhs><xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="XP40" ref="prod-xpath40-StringLiteral" xlink:type="simple">StringLiteral</xnt>  |  ("-"?  <xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="XP40" ref="prod-xpath40-NumericLiteral" xlink:type="simple">NumericLiteral</xnt>)  |  <xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="XP40" ref="prod-xpath40-QNameLiteral" xlink:type="simple">QNameLiteral</xnt>  |  ("true"  "("  ")")  |  ("false"  "("  ")")</rhs></prod><prod id="doc-xslt40-TypePattern-NumericLiteral"><lhs>NumericLiteral</lhs><rhs><nt xmlns:xlink="http://www.w3.org/1999/xlink" def="prod-xslt40-IntegerLiteral" xlink:type="simple">IntegerLiteral</nt>  |  <nt xmlns:xlink="http://www.w3.org/1999/xlink" def="prod-xslt40-HexIntegerLiteral" xlink:type="simple">HexIntegerLiteral</nt>  |  <nt xmlns:xlink="http://www.w3.org/1999/xlink" def="prod-xslt40-BinaryIntegerLiteral" xlink:type="simple">BinaryIntegerLiteral</nt>  |  <nt xmlns:xlink="http://www.w3.org/1999/xlink" def="prod-xslt40-DecimalLiteral" xlink:type="simple">DecimalLiteral</nt>  |  <nt xmlns:xlink="http://www.w3.org/1999/xlink" def="prod-xslt40-DoubleLiteral" xlink:type="simple">DoubleLiteral</nt></rhs></prod><prod id="doc-xslt40-TypePattern-QNameLiteral"><lhs>QNameLiteral</lhs><rhs>"#"  <xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="XP40" ref="prod-xpath40-EQName" xlink:type="simple">EQName</xnt></rhs></prod><prod id="doc-xslt40-TypePattern-SequenceType"><lhs>SequenceType</lhs><rhs>("empty-sequence"  "("  ")")<br/>|  (<xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="XP40" ref="prod-xpath40-ItemType" xlink:type="simple">ItemType</xnt>  <xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="XP40" ref="prod-xpath40-OccurrenceIndicator" xlink:type="simple">OccurrenceIndicator</xnt>?)</rhs></prod><prod id="doc-xslt40-TypePattern-OccurrenceIndicator"><lhs>OccurrenceIndicator</lhs><rhs>"?"  |  "*"  |  "+"</rhs><com><loc xmlns:xlink="http://www.w3.org/1999/xlink" href="#parse-note-occurrence-indicators" xlink:type="simple" xlink:show="replace" xlink:actuate="onRequest">xgs: occurrence-indicators</loc></com></prod><prod id="doc-xslt40-TypePattern-MapType"><lhs>MapType</lhs><rhs><xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="XP40" ref="prod-xpath40-AnyMapType" xlink:type="simple">AnyMapType</xnt>  |  <xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="XP40" ref="prod-xpath40-TypedMapType" xlink:type="simple">TypedMapType</xnt></rhs></prod><prod id="doc-xslt40-TypePattern-AnyMapType"><lhs>AnyMapType</lhs><rhs>"map"  "("  "*"  ")"</rhs></prod><prod id="doc-xslt40-TypePattern-TypedMapType"><lhs>TypedMapType</lhs><rhs>"map"  "("  <xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="XP40" ref="prod-xpath40-ItemType" xlink:type="simple">ItemType</xnt>  ","  <xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="XP40" ref="prod-xpath40-SequenceType" xlink:type="simple">SequenceType</xnt>  ")"</rhs></prod><prod id="doc-xslt40-TypePattern-ArrayType"><lhs>ArrayType</lhs><rhs><xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="XP40" ref="prod-xpath40-AnyArrayType" xlink:type="simple">AnyArrayType</xnt>  |  <xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="XP40" ref="prod-xpath40-TypedArrayType" xlink:type="simple">TypedArrayType</xnt></rhs></prod><prod id="doc-xslt40-TypePattern-AnyArrayType"><lhs>AnyArrayType</lhs><rhs>"array"  "("  "*"  ")"</rhs></prod><prod id="doc-xslt40-TypePattern-TypedArrayType"><lhs>TypedArrayType</lhs><rhs>"array"  "("  <xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="XP40" ref="prod-xpath40-SequenceType" xlink:type="simple">SequenceType</xnt>  ")"</rhs></prod><prod id="doc-xslt40-TypePattern-RecordType"><lhs>RecordType</lhs><rhs>"record"  "("  (<xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="XP40" ref="prod-xpath40-FieldDeclaration" xlink:type="simple">FieldDeclaration</xnt> ** ",")  ")"</rhs></prod><prod id="doc-xslt40-TypePattern-FieldDeclaration"><lhs>FieldDeclaration</lhs><rhs><xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="XP40" ref="prod-xpath40-FieldName" xlink:type="simple">FieldName</xnt>  "?"?  ("as"  <xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="XP40" ref="prod-xpath40-SequenceType" xlink:type="simple">SequenceType</xnt>)?</rhs></prod><prod id="doc-xslt40-TypePattern-FieldName"><lhs>FieldName</lhs><rhs><xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="XP40" ref="prod-xpath40-NCName" xlink:type="simple">NCName</xnt>  |  <xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="XP40" ref="prod-xpath40-StringLiteral" xlink:type="simple">StringLiteral</xnt></rhs></prod><prod id="doc-xslt40-TypePattern-EnumerationType"><lhs>EnumerationType</lhs><rhs>"enum"  "("  (<xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="XP40" ref="prod-xpath40-StringLiteral" xlink:type="simple">StringLiteral</xnt> ++ ",")  ")"</rhs></prod><prod id="doc-xslt40-TypePattern-AposStringLiteral"><lhs>AposStringLiteral</lhs><rhs>"'"  (<nt xmlns:xlink="http://www.w3.org/1999/xlink" def="prod-xslt40-EscapeApos" xlink:type="simple">EscapeApos</nt>  |  [^'])*  "'"</rhs><com><loc xmlns:xlink="http://www.w3.org/1999/xlink" href="#ws-explicit" xlink:type="simple" xlink:show="replace" xlink:actuate="onRequest">ws: explicit</loc></com></prod><prod id="doc-xslt40-TypePattern-QuotStringLiteral"><lhs>QuotStringLiteral</lhs><rhs>'"'  (<nt xmlns:xlink="http://www.w3.org/1999/xlink" def="prod-xslt40-EscapeQuot" xlink:type="simple">EscapeQuot</nt>  |  [^"])*  '"'</rhs><com><loc xmlns:xlink="http://www.w3.org/1999/xlink" href="#ws-explicit" xlink:type="simple" xlink:show="replace" xlink:actuate="onRequest">ws: explicit</loc></com></prod><prod id="doc-xslt40-TypePattern-FunctionType"><lhs>FunctionType</lhs><rhs><xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="XP40" ref="prod-xpath40-AnyFunctionType" xlink:type="simple">AnyFunctionType</xnt><br/>|  <xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="XP40" ref="prod-xpath40-TypedFunctionType" xlink:type="simple">TypedFunctionType</xnt></rhs></prod><prod id="doc-xslt40-TypePattern-AnyFunctionType"><lhs>AnyFunctionType</lhs><rhs>("function"  |  "fn")  "("  "*"  ")"</rhs></prod><prod id="doc-xslt40-TypePattern-TypedFunctionType"><lhs>TypedFunctionType</lhs><rhs>("function"  |  "fn")  "("  (<xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="XP40" ref="prod-xpath40-TypedFunctionParam" xlink:type="simple">TypedFunctionParam</xnt> ** ",")  ")"  "as"  <xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="XP40" ref="prod-xpath40-SequenceType" xlink:type="simple">SequenceType</xnt></rhs></prod><prod id="doc-xslt40-TypePattern-TypedFunctionParam"><lhs>TypedFunctionParam</lhs><rhs>("$"  <xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="XP40" ref="prod-xpath40-EQName" xlink:type="simple">EQName</xnt>  "as")?  <xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="XP40" ref="prod-xpath40-SequenceType" xlink:type="simple">SequenceType</xnt></rhs></prod><prod id="doc-xslt40-TypePattern-EQName"><lhs>EQName</lhs><rhs><nt xmlns:xlink="http://www.w3.org/1999/xlink" def="prod-xslt40-QName" xlink:type="simple">QName</nt>  |  <xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="XP40" ref="prod-xpath40-URIQualifiedName" xlink:type="simple">URIQualifiedName</xnt></rhs></prod><prod id="doc-xslt40-TypePattern-URIQualifiedName"><lhs>URIQualifiedName</lhs><rhs><nt xmlns:xlink="http://www.w3.org/1999/xlink" def="prod-xslt40-BracedURILiteral" xlink:type="simple">BracedURILiteral</nt>  (<nt xmlns:xlink="http://www.w3.org/1999/xlink" def="prod-xslt40-NCName" xlink:type="simple">NCName</nt>  ":")?  <nt xmlns:xlink="http://www.w3.org/1999/xlink" def="prod-xslt40-NCName" xlink:type="simple">NCName</nt></rhs><com><loc xmlns:xlink="http://www.w3.org/1999/xlink" href="#ws-explicit" xlink:type="simple" xlink:show="replace" xlink:actuate="onRequest">ws: explicit</loc></com></prod><prod id="doc-xslt40-TypePattern-ChoiceItemType"><lhs>ChoiceItemType</lhs><rhs>"("  (<xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="XP40" ref="prod-xpath40-ItemType" xlink:type="simple">ItemType</xnt> ++ "|")  ")"</rhs></prod><prod id="doc-xslt40-TypePattern-Predicate"><lhs>Predicate</lhs><rhs>"["  <xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="XP40" ref="prod-xpath40-Expr" xlink:type="simple">Expr</xnt>  "]"</rhs></prod><prod id="doc-xslt40-TypePattern-Expr"><lhs>Expr</lhs><rhs>(<xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="XP40" ref="prod-xpath40-ExprSingle" xlink:type="simple">ExprSingle</xnt> ++ ",")</rhs></prod><prod id="doc-xslt40-TypePattern-ExprSingle"><lhs>ExprSingle</lhs><rhs><xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="XP40" ref="prod-xpath40-ForExpr" xlink:type="simple">ForExpr</xnt><br/>|  <xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="XP40" ref="prod-xpath40-LetExpr" xlink:type="simple">LetExpr</xnt><br/>|  <xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="XP40" ref="prod-xpath40-QuantifiedExpr" xlink:type="simple">QuantifiedExpr</xnt><br/>|  <xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="XP40" ref="prod-xpath40-IfExpr" xlink:type="simple">IfExpr</xnt></rhs></prod><prod id="doc-xslt40-TypePattern-ForExpr"><lhs>ForExpr</lhs><rhs><xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="XP40" ref="prod-xpath40-ForClause" xlink:type="simple">ForClause</xnt>  <xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="XP40" ref="prod-xpath40-ForLetReturn" xlink:type="simple">ForLetReturn</xnt></rhs></prod><prod id="doc-xslt40-TypePattern-ForClause"><lhs>ForClause</lhs><rhs>"for"  (<xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="XP40" ref="prod-xpath40-ForBinding" xlink:type="simple">ForBinding</xnt> ++ ",")</rhs></prod><prod id="doc-xslt40-TypePattern-ForLetReturn"><lhs>ForLetReturn</lhs><rhs><xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="XP40" ref="prod-xpath40-ForExpr" xlink:type="simple">ForExpr</xnt>  |  <xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="XP40" ref="prod-xpath40-LetExpr" xlink:type="simple">LetExpr</xnt>  |  ("return"  <xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="XP40" ref="prod-xpath40-ExprSingle" xlink:type="simple">ExprSingle</xnt>)</rhs></prod><prod id="doc-xslt40-TypePattern-LetExpr"><lhs>LetExpr</lhs><rhs><xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="XP40" ref="prod-xpath40-LetClause" xlink:type="simple">LetClause</xnt>  <xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="XP40" ref="prod-xpath40-ForLetReturn" xlink:type="simple">ForLetReturn</xnt></rhs></prod><prod id="doc-xslt40-TypePattern-LetClause"><lhs>LetClause</lhs><rhs>"let"  (<xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="XP40" ref="prod-xpath40-LetBinding" xlink:type="simple">LetBinding</xnt> ++ ",")</rhs></prod><prod id="doc-xslt40-TypePattern-QuantifiedExpr"><lhs>QuantifiedExpr</lhs><rhs>("some"  |  "every")  (<xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="XP40" ref="prod-xpath40-QuantifierBinding" xlink:type="simple">QuantifierBinding</xnt> ++ ",")  "satisfies"  <xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="XP40" ref="prod-xpath40-ExprSingle" xlink:type="simple">ExprSingle</xnt></rhs></prod><prod id="doc-xslt40-TypePattern-QuantifierBinding"><lhs>QuantifierBinding</lhs><rhs><xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="XP40" ref="prod-xpath40-VarNameAndType" xlink:type="simple">VarNameAndType</xnt>  "in"  <xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="XP40" ref="prod-xpath40-ExprSingle" xlink:type="simple">ExprSingle</xnt></rhs></prod><prod id="doc-xslt40-TypePattern-IfExpr"><lhs>IfExpr</lhs><rhs>"if"  "("  <xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="XP40" ref="prod-xpath40-Expr" xlink:type="simple">Expr</xnt>  ")"  (<xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="XP40" ref="prod-xpath40-UnbracedActions" xlink:type="simple">UnbracedActions</xnt>  |  <xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="XP40" ref="prod-xpath40-BracedAction" xlink:type="simple">BracedAction</xnt>)</rhs></prod><prod id="doc-xslt40-TypePattern-UnbracedActions"><lhs>UnbracedActions</lhs><rhs>"then"  <xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="XP40" ref="prod-xpath40-ExprSingle" xlink:type="simple">ExprSingle</xnt>  "else"  <xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="XP40" ref="prod-xpath40-ExprSingle" xlink:type="simple">ExprSingle</xnt></rhs></prod><prod id="doc-xslt40-TypePattern-BracedAction"><lhs>BracedAction</lhs><rhs><xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="XP40" ref="prod-xpath40-EnclosedExpr" xlink:type="simple">EnclosedExpr</xnt></rhs></prod></scrap><p>A type pattern matches an item if both the following conditions are true:</p><ulist><item><p>The item can be successfully coerced to the given item type, by applying the
                     <termref def="dt-coercion-rules"/>.</p></item><item><p>The item (after such coercion) satisfies each of the predicates.</p></item></ulist><p>For example:</p><ulist><item><p><code nobreak="false">~xs:integer</code> matches any instance of
                        <code nobreak="false">xs:integer</code></p></item><item><p><code nobreak="false">~xs:integer[. gt 0]</code> matches
                        any positive integer.</p></item><item><p><code nobreak="false">~(xs:string | xs:untypedAtomic)[matches(., '[0-9]+')]</code> matches
                        any instance of <code nobreak="false">xs:string</code> or <code nobreak="false">xs:untypedAtomic</code> that
                        contains a sequence of decimal digits.</p></item><item><p><code nobreak="false">~node()</code> matches any XNode. (This is not the same as the pattern
                        <code nobreak="false">node()</code>, which for historical reasons only matches  element, text, comment, 
                        and processing instruction nodes).</p></item><item><p><code nobreak="false">~record(first as enum("Sharon"), last)</code>
                        matches any map having entries with the string-valued keys <code nobreak="false">"first"</code> and <code nobreak="false">"last"</code>,
                        where the entry for the key <code nobreak="false">"first"</code> is equal to the string <code nobreak="false">"Sharon"</code></p></item><item><p><code nobreak="false">~jnode(address, record(address-line-1, address-line-2))</code> matches a JNode whose
                     ·jkey· property is the string <code nobreak="false">"address"</code>, and whose content matches the given record type.</p></item></ulist><p>More formally, an item <var>$J</var> matches a pattern <code nobreak="false">~<var>T</var>[<var>P1</var>][<var>P2</var>][<var>P3</var>]</code> if
                  the XPath expression <code nobreak="false">let $JJ as <var>T</var> := J return exists($JJ[<var>P1</var>][<var>P2</var>][<var>P3</var>])</code> is true.</p><note><p>As with predicate patterns, numeric predicates are allowed, but serve no useful purpose.</p></note><note><p>An error in evaluating the equivalent expression (for example, when the item
                        cannot be coerced to the required type) means that the item is treated as not matching the pattern.</p></note><note><p>The item type in a pattern can be any <code nobreak="false">ItemType</code>, but patterns that match
                        XNodes or JNodes can usually be expressed more concisely
                        as a <code nobreak="false">NodePattern</code> (see <specref ref="node-patterns"/>): 
                        for example <code nobreak="false">match="~element(PERSON)"</code> has the same meaning as
                        <code nobreak="false">match="element(PERSON)"</code>, which in turn is usually abbreviated to 
                        <code nobreak="false">match="PERSON"</code> (although <code nobreak="false">match="PERSON"</code> will also match JNodes).</p></note></div4><div4 id="node-patterns"><head>GNode Patterns</head><changes><change issue="1375 1522" PR="1378" date="2024-10-15">
                        A function call at the outermost level can now be named using any valid <code nobreak="false">EQName</code>
                        (for example <xfunction>fn:doc</xfunction>) provided it binds to one of the permitted functions
                        <xfunction>fn:doc</xfunction>, <xfunction>fn:id</xfunction>, <xfunction>fn:element-with-id</xfunction>, 
                        <function>fn:key</function>, or <xfunction>fn:root</xfunction>. 
                        If two functions are called, for example <code nobreak="false">doc('a.xml')/id('abc')</code>,
                        it is no longer necessary to put the second call in parentheses.
                     </change></changes><scrap id="NodePatterns-scrap" headstyle="show"><prod id="doc-xslt40-GNodePattern"><lhs>GNodePattern</lhs><rhs><nt xmlns:xlink="http://www.w3.org/1999/xlink" def="prod-xslt40-UnionExprP" xlink:type="simple">UnionExprP</nt></rhs></prod><prod id="doc-xslt40-GNodePattern-UnionExprP"><lhs>UnionExprP</lhs><rhs><nt xmlns:xlink="http://www.w3.org/1999/xlink" def="prod-xslt40-IntersectExceptExprP" xlink:type="simple">IntersectExceptExprP</nt>  (("union"  |  "|")  <nt xmlns:xlink="http://www.w3.org/1999/xlink" def="prod-xslt40-IntersectExceptExprP" xlink:type="simple">IntersectExceptExprP</nt>)*</rhs></prod><prod id="doc-xslt40-GNodePattern-IntersectExceptExprP"><lhs>IntersectExceptExprP</lhs><rhs><nt xmlns:xlink="http://www.w3.org/1999/xlink" def="prod-xslt40-PathExprP" xlink:type="simple">PathExprP</nt>  (("intersect"  |  "except")  <nt xmlns:xlink="http://www.w3.org/1999/xlink" def="prod-xslt40-PathExprP" xlink:type="simple">PathExprP</nt>)*</rhs></prod><prod id="doc-xslt40-GNodePattern-PathExprP"><lhs>PathExprP</lhs><rhs><nt xmlns:xlink="http://www.w3.org/1999/xlink" def="prod-xslt40-RootedPath" xlink:type="simple">RootedPath</nt><br/>|  ("/"  <nt xmlns:xlink="http://www.w3.org/1999/xlink" def="prod-xslt40-RelativePathExprP" xlink:type="simple">RelativePathExprP</nt>?)<br/>|  ("//"  <nt xmlns:xlink="http://www.w3.org/1999/xlink" def="prod-xslt40-RelativePathExprP" xlink:type="simple">RelativePathExprP</nt>)<br/>|  <nt xmlns:xlink="http://www.w3.org/1999/xlink" def="prod-xslt40-RelativePathExprP" xlink:type="simple">RelativePathExprP</nt></rhs><com><loc xmlns:xlink="http://www.w3.org/1999/xlink" href="#parse-note-leading-lone-slash" xlink:type="simple" xlink:show="replace" xlink:actuate="onRequest">xgs: leading-lone-slash</loc></com></prod><prod id="doc-xslt40-GNodePattern-RootedPath"><lhs>RootedPath</lhs><rhs><xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="XP40" ref="prod-xpath40-VarRef" xlink:type="simple">VarRef</xnt>  <xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="XP40" ref="prod-xpath40-Predicate" xlink:type="simple">Predicate</xnt>*  (("/"  |  "//")  <nt xmlns:xlink="http://www.w3.org/1999/xlink" def="prod-xslt40-RelativePathExprP" xlink:type="simple">RelativePathExprP</nt>)?</rhs></prod><prod id="doc-xslt40-GNodePattern-VarRef"><lhs>VarRef</lhs><rhs>"$"  <xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="XP40" ref="prod-xpath40-EQName" xlink:type="simple">EQName</xnt></rhs></prod><prod id="doc-xslt40-GNodePattern-Predicate"><lhs>Predicate</lhs><rhs>"["  <xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="XP40" ref="prod-xpath40-Expr" xlink:type="simple">Expr</xnt>  "]"</rhs></prod><prod id="doc-xslt40-GNodePattern-RelativePathExprP"><lhs>RelativePathExprP</lhs><rhs><nt xmlns:xlink="http://www.w3.org/1999/xlink" def="prod-xslt40-StepExprP" xlink:type="simple">StepExprP</nt>  (("/"  |  "//")  <nt xmlns:xlink="http://www.w3.org/1999/xlink" def="prod-xslt40-StepExprP" xlink:type="simple">StepExprP</nt>)*</rhs></prod><prod id="doc-xslt40-GNodePattern-StepExprP"><lhs>StepExprP</lhs><rhs><nt xmlns:xlink="http://www.w3.org/1999/xlink" def="prod-xslt40-PostfixExprP" xlink:type="simple">PostfixExprP</nt>  |  <nt xmlns:xlink="http://www.w3.org/1999/xlink" def="prod-xslt40-AxisStepP" xlink:type="simple">AxisStepP</nt></rhs></prod></scrap><p>GNode patterns are used to match GNodes: that is, XNodes or JNodes.</p><p>Many of the constructs within a GNode pattern have names that are chosen to align 
                  with the XPath 4.0 grammar.
                  Constructs whose names are suffixed with <code nobreak="false">P</code> are restricted forms of
                  the corresponding XPath 4.0 construct without the suffix: for example,
                  <code nobreak="false">StepExprP</code> is a restricted form of <code nobreak="false">StepExpr</code>. Constructs labeled with
                  the subpercript “XP” are defined in <bibref ref="xpath-40"/>.</p><p>The syntax of a <nt xmlns:xlink="http://www.w3.org/1999/xlink" def="doc-xslt40-GNodePattern" xlink:type="simple">GNodePattern</nt> is a subset of the syntax
               of an XPath path expression, and the semantics are defined by reference to the semantics
               of XPath expressions.</p><p>In a <nt xmlns:xlink="http://www.w3.org/1999/xlink" def="prod-xslt40-FunctionCallP" xlink:type="simple">FunctionCallP</nt>, the
                     <code nobreak="false">EQName</code> used for the function name must bind to
                  one of the functions <xfunction>fn:doc#1</xfunction>, <xfunction>fn:id#1</xfunction>, 
                  <xfunction>fn:id#2</xfunction>, <xfunction>fn:element-with-id#1</xfunction>,
                  <xfunction>fn:element-with-id#2</xfunction>
                  <function>fn:key#2</function>, <function>fn:key#3</function>
                  or <xfunction>fn:root#0</xfunction>, and the arguments (if any) must
                  either be variable references or constants.</p><note><p>In the case of a call to the
                     <xfunction>fn:root</xfunction> function, the argument list must be empty: that is,
                  only the zero-arity form of the function is allowed.</p></note><note><p>As with XPath expressions, the pattern <code nobreak="false">/ union /*</code> can be parsed in
                     two different ways, and the chosen interpretation is to treat
                        <code nobreak="false">union</code> as an element name rather than as an operator. The other
                     interpretation can be achieved by writing <code nobreak="false">(/) union (/*)</code></p></note><div5 id="pattern-semantics"><head>The Meaning of a GNode Pattern</head><p>This section defines the formal meaning of a <nt xmlns:xlink="http://www.w3.org/1999/xlink" def="doc-xslt40-GNodePattern" xlink:type="simple">GNodePattern</nt>.</p><p>The process for determining whether a GNode matches a 
            <nt xmlns:xlink="http://www.w3.org/1999/xlink" def="doc-xslt40-GNodePattern" xlink:type="simple"/> is as follows:</p><olist><item><p>The <nt xmlns:xlink="http://www.w3.org/1999/xlink" def="doc-xslt40-GNodePattern" xlink:type="simple"/> is converted to an 
               <termref def="dt-expression">expression</termref>, 
               called the <term>equivalent expression</term>. The
               equivalent expression to a <nt xmlns:xlink="http://www.w3.org/1999/xlink" def="doc-xslt40-GNodePattern" xlink:type="simple"/> is the XPath
               expression that takes the same lexical form as the <nt xmlns:xlink="http://www.w3.org/1999/xlink" def="doc-xslt40-GNodePattern" xlink:type="simple"/> as
               written, except that two adjustments are made to any
               <nt xmlns:xlink="http://www.w3.org/1999/xlink" def="prod-xslt40-AxisStepP" xlink:type="simple"/> that is a <termref def="dt-leading-step"/>.</p><p><termdef id="dt-leading-step" term="leading step">An <nt xmlns:xlink="http://www.w3.org/1999/xlink" def="prod-xslt40-AxisStepP" xlink:type="simple"/>
               within a <termref def="dt-pattern"/> is a <term>leading step</term> if
               (a) it is not the right-hand operand of a <code nobreak="false">/</code> or <code nobreak="false">//</code>
               operator, and (b) it is not contained (directly or indirectly) within a
               <nt xmlns:xlink="http://www.w3.org/1999/xlink" def="prod-xslt40-ParenthesizedPattern" xlink:type="simple"/> that is the right-hand operand of a 
               <code nobreak="false">/</code> or <code nobreak="false">//</code> operator</termdef>.</p><note><p>An <xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="XP40" ref="AxisStep" xlink:type="simple">AxisStep</xnt>
               within a predicate is unaffected, since it is not an <nt xmlns:xlink="http://www.w3.org/1999/xlink" def="prod-xslt40-AxisStepP" xlink:type="simple"/>.</p></note><p>The adjustments that are made to a <termref def="dt-leading-step"/> are:</p><olist><item><p>The <code nobreak="false">NodeTest</code> is adjusted to ensure that the pattern will (in most cases) match
                           XNodes or JNodes but not both. Specifically, if the principal node kind of the
                           axis is <code nobreak="false">element</code>, then any <code nobreak="false">Selector</code> within the <code nobreak="false">NodeTest</code>
                           that takes the form of an <code nobreak="false">EQName</code> or <code nobreak="false">Wildcard</code> is wrapped in an <nt xmlns:xlink="http://www.w3.org/1999/xlink" def="prod-xslt40-ElementNodeType" xlink:type="simple"/> 
                           so it only selects element nodes. For example, <code nobreak="false">match="*"</code> is interpreted as
                           <code nobreak="false">match="element(*)"</code>, and <code nobreak="false">match="employee"</code> is interpreted
                           as <code nobreak="false">match="element(employee)"</code>.</p><note><p>The rationale for this is firstly, that it improves the clarity of the code
                           if it is clear whether patterns are intended to match XNodes or JNodes; and secondly,
                           that it enables pattern matching to be optimized and simplifies streamability analysis.</p></note></item><item><p>In addition, the axis is adjusted to allow the step to match a parentless GNode. The
                        adjustment depends on the axis used in this step, whether it appears
                        explicitly or implicitly (according to the rules of <xspecref spec="XP40" ref="abbrev"/>), 
                        and is made as follows:</p><olist><item><p>If the <code nobreak="false">NodeTest</code> in <var>PS</var> is
                                 <code nobreak="false">document-node()</code> (optionally with arguments), and if no
                              explicit axis is specified, then the axis in step <var>PS</var> is
                              taken as <code nobreak="false">self</code> rather than <code nobreak="false">child</code>.</p></item><item><p>If <var>PS</var> uses the child axis (explicitly or implicitly), and
                              if the <code nobreak="false">NodeTest</code> in <var>PS</var> is not
                                 <code nobreak="false">document-node()</code> (optionally with arguments), then the
                              axis in step <var>PS</var> is replaced by <code nobreak="false">child-or-top</code>,
                              which is defined as follows. If the context node is a parentless
                              element, comment, processing instruction, or text node then the
                                 <code nobreak="false">child-or-top</code> axis selects the context node; otherwise
                              it selects the children of the context node. It is a forwards axis
                              whose principal node kind is element.</p></item><item><p>If <var>PS</var> uses the attribute axis (explicitly or implicitly),
                              then the axis in step <var>PS</var> is replaced by
                                 <code nobreak="false">attribute-or-top</code>, which is defined as follows. If the
                              context node is an attribute node with no parent, then the
                                 <code nobreak="false">attribute-or-top</code> axis selects the context node;
                              otherwise it selects the attributes of the context node. It is a
                              forwards axis whose principal node kind is attribute.</p></item><item><p>If <var>PS</var> uses the namespace axis (explicitly or implicitly), then the axis in step
                                 <var>PS</var> is replaced by <code nobreak="false">namespace-or-top</code>, which
                              is defined as follows. If the context node is a namespace node with no
                              parent, then the <code nobreak="false">namespace-or-top</code> axis selects the
                              context node; otherwise it selects the namespace nodes of the context
                              node. It is a forwards axis whose principal node kind is
                              namespace.</p></item></olist><p>The axes <code nobreak="false">child-or-top</code>, <code nobreak="false">attribute-or-top</code>, and
                           <code nobreak="false">namespace-or-top</code> are introduced only for definitional
                        purposes. They cannot be used explicitly in a user-written pattern or
                        expression.</p><note><p>The purpose of this adjustment is to ensure that a pattern such as
                              <code nobreak="false">person</code> matches any element named <code nobreak="false">person</code>,
                           even if it has no parent; and similarly, that the pattern
                              <code nobreak="false">@width</code> matches any attribute named <code nobreak="false">width</code>,
                           even a parentless attribute. The rule also ensures that a pattern using a
                              <code nobreak="false">NodeTest</code> of the form <code nobreak="false">document-node(...)</code>
                           matches a document node. The pattern <code nobreak="false">node()</code> will match any
                           element, text node, comment, or processing instruction, whether or not it
                           has a parent. For backwards compatibility reasons, the pattern
                              <code nobreak="false">node()</code>, when used without an explicit axis, does not
                           match document nodes, attribute nodes, or namespace nodes. The rules are
                           also phrased to ensure that positional patterns of the form
                              <code nobreak="false">para[1]</code> continue to count nodes relative to their parent,
                           if they have one. To match any XNode at all,
                              XSLT 4.0 allows the pattern <code nobreak="false">~node()</code> to be
                              used.</p><p>The adjustment is not necessary in the case of JNodes, because a JNode
                        with ·jkey· value <code nobreak="false">"person"</code> will necessarily have a parent JNode.</p></note></item></olist></item><item><p>The meaning of the pattern is then defined in terms of the semantics of the
                     equivalent expression, denoted below as <code nobreak="false">EE</code>.</p><p>Specifically, an item <var>N</var> matches a <nt xmlns:xlink="http://www.w3.org/1999/xlink" def="doc-xslt40-GNodePattern" xlink:type="simple">GNodePattern</nt>
                      <var>P</var> if and only if the following applies, where
                        <code nobreak="false">EE</code> is the <term>equivalent expression</term> to <var>P</var>:</p><ulist><item><p><var>N</var> is a GNode, and the result of evaluating the expression
                              <code nobreak="false">root(.)//(EE)</code> with a <termref def="dt-singleton-focus">singleton focus</termref> 
                           based on <var>N</var> is a sequence that includes the GNode <var>N</var>.
                        </p></item></ulist><p>If a pattern appears in an attribute of an XSLT element that
                        is processed with <termref def="dt-xslt-10-behavior">XSLT 1.0
                           behavior</termref> (see <specref ref="backwards"/>), then the
                     semantics of the pattern are defined on the basis that the equivalent XPath
                     expression is evaluated with <termref def="dt-xpath-compat-mode">XPath 1.0
                        compatibility mode</termref> set to <code nobreak="false">true</code>.</p></item></olist><example><head>Matching XNodes</head><p>The <termref def="dt-gnode-pattern"/>
                     <code nobreak="false">p</code> matches any <code nobreak="false">p</code> element. The equivalent expression,
                     after adjustment, is <code nobreak="false">child-or-top::element(p)</code>, and the pattern matches because a <code nobreak="false">p</code>
                     element will always be present in the result of evaluating the 
                     equivalent <termref def="dt-expression">expression</termref>
                     <code nobreak="false">root(.)//(child-or-top::element(p))</code>.</p><p>Similarly, <code nobreak="false">/</code> matches a
                     document node, and only a document node. The equivalent expression, after adjustment,
                     is <code nobreak="false">self::document-node()</code>, and the pattern matches because the result 
                     of the equivalent <termref def="dt-expression">expression</termref>
                     <code nobreak="false">root(.)//(self::document-node())</code> returns the root node of the tree containing the
                     context node if and only if it is a document node.</p><p>The <termref def="dt-gnode-pattern"/>
                     <code nobreak="false">node()</code> matches all XNodes selected by the expression
                        <code nobreak="false">root(.)//(child-or-top::node())</code>, that is, all element, text,
                     comment, and processing instruction nodes, whether or not they have a parent.
                     It does not match attribute or namespace nodes because the expression does not
                     select nodes using the attribute or namespace axes. It does not match document
                     nodes because for backwards compatibility reasons the <code nobreak="false">child-or-top</code>
                     axis does not match a document node.</p><note><p>The pattern <code nobreak="false">~node()</code> matches all XNodes.</p></note><p>The <termref def="dt-gnode-pattern"/>
                     <code nobreak="false">$V</code> matches all XNodes selected by the expression
                        <code nobreak="false">root(.)//($V)</code>, that is, all XNodes in the value of $V (which
                     will typically be a global variable, though when the pattern is used in
                     contexts such as the <elcode>xsl:number</elcode> or
                        <elcode>xsl:for-each-group</elcode> instructions, it can also be a local
                     variable).</p><p>The <termref def="dt-gnode-pattern"/>
                     <code nobreak="false">doc('product.xml')//product</code> matches all XNodes selected by the
                     expression <code nobreak="false">root(.)//(doc('product.xml')//product)</code>, that is, all
                        <code nobreak="false">product</code> elements in the document whose URI is
                        <code nobreak="false">product.xml</code>.</p><p>The <termref def="dt-gnode-pattern"/>
                     <code nobreak="false">root(.)/self::E</code> matches an <code nobreak="false">E</code> element that is the root
                     of a tree (that is, an <code nobreak="false">E</code> element with no parent node).</p></example><p>Although the semantics of <termref def="dt-gnode-pattern">GNode patterns</termref> are
                  specified formally in terms of expression evaluation, it is possible to understand
                  pattern matching using a different model. A <termref def="dt-gnode-pattern"/> such as
                     <code nobreak="false">book/chapter/section</code> can be examined from right to left. A node
                  will only match this pattern if it is a <code nobreak="false">section</code> element; and then,
                  only if its parent is a <code nobreak="false">chapter</code>; and then, only if the parent of that
                     <code nobreak="false">chapter</code> is a <code nobreak="false">book</code>. When the pattern uses the
                     <code nobreak="false">//</code> operator, one can still read it from right to left, but this
                  time testing the ancestors of a node rather than its parent. For example
                     <code nobreak="false">appendix//section</code> matches every <code nobreak="false">section</code> element that
                  has an ancestor <code nobreak="false">appendix</code> element.</p><p>The formal definition, however, is useful for understanding the meaning of a
                  pattern such as <code nobreak="false">para[1]</code>. This matches any node selected by the
                  expression <code nobreak="false">root(.)//(child-or-top::para[1])</code>: that is, any
                     <code nobreak="false">para</code> element that is the first <code nobreak="false">para</code> child of its
                  parent, or a <code nobreak="false">para</code> element that has no parent.</p><example><head>Matching JNodes</head><ulist><item><p>The pattern <code nobreak="false">jnode(code, xs:string)</code> matches any
                     JNode whose ·jkey· is the string <code nobreak="false">"code"</code> and whose ·jvalue·
                     is an instance of <code nobreak="false">xs:string</code>.</p></item><item><p>The pattern <code nobreak="false">jnode("date of birth", xs:date)</code> matches any
                     JNode whose ·jkey· is the string <code nobreak="false">"date of birth"</code> and whose ·jvalue·
                     is an instance of <code nobreak="false">xs:date</code>.</p></item><item><p>The pattern <code nobreak="false">jnode(*, array(*))</code> matches any
                     JNode whose ·jvalue· is an array, regardless of its ·jkey· property.</p></item><item><p>The pattern <code nobreak="false">jnode(*, record(Author, Title))[ancestor::books]</code> matches any
                     JNode whose ·jvalue· is an instance of the type <code nobreak="false">record(Author, Title)</code>, 
                     provided it has an ancestor with the ·jkey· value <code nobreak="false">"books"</code>.</p></item><item><p>The pattern <code nobreak="false">jnode(*, record(Author as enum("Dickens"), Title))</code> matches any
                     JNode whose ·jvalue· is a map having an <code nobreak="false">Author</code> entry with the value
                     <code nobreak="false">"Dickens"</code>, a <code nobreak="false">Title</code> entry with any value, and optionally
                     other entries.</p></item><item><p>The pattern <code nobreak="false">jnode(*)[jkey() = current-date()]</code> matches any
                     JNode whose ·jkey· property is an <code nobreak="false">xs:date</code> value equal to the current date.
                     The comparison uses the implicit timezone from the dynamic context. The rules for error
                  handling in patterns ensure that any JNode whose ·jkey· value is of a type other
                  than <code nobreak="false">xs:date</code> does not match, because evaluation of the predicate raises an error.</p></item></ulist></example><note><p>The <code nobreak="false">intersect</code> and <code nobreak="false">except</code> operators
                  do not always have the intuitive meaning. Simple cases such as
                  <code nobreak="false">* except A</code>, or <code nobreak="false">@* except (@code, @name)</code>
                  are unproblematic, but expressions using the descendant axis can
                  be surprising.</p><p>Consider the pattern <code nobreak="false">para except appendix//para</code>.
                  Perhaps unexpectedly, this matches the <code nobreak="false">para</code> element 
                  in the XML tree shown below:</p><eg xml:space="preserve">&lt;appendix&gt;
  &lt;section&gt;
     &lt;para/&gt;
  &lt;/section&gt;
&lt;/appendix&gt;  
</eg><p>This is because there is an element <code nobreak="false">$S</code> (specifically, 
                     the <code nobreak="false">section</code> element), such that the expression
                     <code nobreak="false">$S//(para except appendix//para)</code> selects this
                     <code nobreak="false">para</code> element.</p></note><note><p>An implementation, of course, may use any algorithm it wishes for evaluating
                     patterns, so long as the result corresponds with the formal definition above.
                     An implementation that followed the formal definition by evaluating the
                     equivalent expression and then testing the membership of a specific node in the
                     result would probably be very inefficient.</p></note></div5></div4></div3><div3 id="default-priority"><head>Default Priority for Patterns</head><changes><change issue="1394" PR="1442" date="2024-09-15">
                  Default priorities are added for new forms of <nt xmlns:xlink="http://www.w3.org/1999/xlink" def="prod-xslt40-ElementNodeType" xlink:type="simple"/> and <nt xmlns:xlink="http://www.w3.org/1999/xlink" def="prod-xslt40-AttributeNodeType" xlink:type="simple"/>,
                  for example <code nobreak="false">element(p:*)</code> and <code nobreak="false">element(a|b)</code>.
               </change><change issue="1770" PR="1772" date="2025-02-11">
                  The default priority for a template rule using a union pattern has changed.
                  This change may cause incompatible behavior.
               </change></changes><p><termdef id="dt-default-priority" term="default priority">If no <code nobreak="false">priority</code>
                  attribute is specified on an <elcode>xsl:template</elcode> element, a
                     <term>default priority</term> is computed, based on the syntactic form of 
                  the <termref def="dt-pattern">pattern</termref> 
               supplied in the <code nobreak="false">match</code> attribute.</termdef> 
               The default priority of a pattern is always greater than or equal to -1 (minus one),
               and less than or equal to +1 (plus one). The rules are as follows. </p><p>Unless otherwise specified, the default priority for a pattern is +0.5. For some simple patterns,
               listed below, there is a lower default priority in the range -1 (minus one) to +1.</p><note><p>A higher numeric value denotes a higher priority: a rule with priority 1 is selected
               in preference to a rule with priority 0, which in turn is prefered over one with priority -1.</p></note><div4 id="default-priority-for-predicate-patterns"><head>Default Priority for Predicate Patterns</head><p>The default priority for the pattern <code nobreak="false">.</code> (a predicate pattern with
               no predicates, which matches any item) is -1 (minus one).</p><p>For a <nt xmlns:xlink="http://www.w3.org/1999/xlink" def="doc-xslt40-PredicatePattern" xlink:type="simple">PredicatePattern</nt> having one or more
                  predicates, the default priority is +1.</p></div4><div4 id="default-priority-for-type-patterns"><head>Default Priority for Type Patterns</head><p>For a <nt xmlns:xlink="http://www.w3.org/1999/xlink" def="doc-xslt40-TypePattern" xlink:type="simple">TypePattern</nt> with no predicates, the default
               priority depends on the item type:</p><ulist><item><p>For a <xtermref spec="XP40" ref="dt-choice-item-type"/>, 
                        the default priority is the maximum priority of the item types included
                        in the choice, computed according to the rules below.</p></item><item><p>For the item type <code nobreak="false">item()</code>, the default priority is -1 (minus one).</p></item><item><p>For any item type that is a 
                        <nt xmlns:xlink="http://www.w3.org/1999/xlink" def="prod-xslt40-GNodeType" xlink:type="simple"/>, <nt xmlns:xlink="http://www.w3.org/1999/xlink" def="prod-xslt40-XNodeType" xlink:type="simple"/>
                        or <nt xmlns:xlink="http://www.w3.org/1999/xlink" def="prod-xslt40-JNodeType" xlink:type="simple"/>
                  (for example <code nobreak="false">jnode(*)</code>, <code nobreak="false">element()</code> or <code nobreak="false">element(N)</code>), the default
                  priority is the same as that of the corresponding GNode Pattern: 
                  see <specref ref="default-priority-for-gnode-patterns"/>.</p></item><item><p>For the item type <code nobreak="false">function(*)</code>,
                  the default priority is -0.5.</p></item><item><p>For the item types <code nobreak="false">array(*)</code> and <code nobreak="false">map(*)</code>,
                        the default priority is -0.25.</p></item><item><p>For the item type <code nobreak="false">xs:anyAtomicType</code>,
                  the default priority is -0.5.</p></item><item><p>For the 19 XSD-defined primitive atomic types, and for <code nobreak="false">xs:untypedAtomic</code>,
                        the default priority is 0.</p></item><item><p>For an atomic type other than a primitive type, the default priority is a value greater than
                  0 (zero) and less than 0.5 that reflects its depth in the type hierarchy. Specifically, the priority
                  is computed as <code nobreak="false">0.5 - 2^-<var>N</var></code> where <var>N</var> is the number of
                  derivation steps from <code nobreak="false">xs:anyAtomicType</code>. This formula also works for primitive types. For example:</p><table border="1" cellpadding="5" width="100%"><caption>Examples of default priorities for atomic types</caption><thead><tr><th rowspan="1" colspan="1" align="left" valign="top">Type</th><th rowspan="1" colspan="1" align="left" valign="top">Depth (<var>N</var>)</th><th rowspan="1" colspan="1" align="left" valign="top">Priority</th></tr></thead><tbody><tr><td rowspan="1" colspan="1" align="left" valign="top"><code nobreak="false">xs:decimal</code></td><td rowspan="1" colspan="1" align="left" valign="top">1</td><td rowspan="1" colspan="1" align="left" valign="top">0</td></tr><tr><td rowspan="1" colspan="1" align="left" valign="top"><code nobreak="false">xs:integer</code></td><td rowspan="1" colspan="1" align="left" valign="top">2</td><td rowspan="1" colspan="1" align="left" valign="top">0.25</td></tr><tr><td rowspan="1" colspan="1" align="left" valign="top"><code nobreak="false">xs:long</code></td><td rowspan="1" colspan="1" align="left" valign="top">3</td><td rowspan="1" colspan="1" align="left" valign="top">0.375</td></tr><tr><td rowspan="1" colspan="1" align="left" valign="top"><code nobreak="false">xs:int</code></td><td rowspan="1" colspan="1" align="left" valign="top">4</td><td rowspan="1" colspan="1" align="left" valign="top">0.4375</td></tr></tbody></table></item><item><p>For an <code nobreak="false">enum</code> type, the default priority is 0.25.</p></item><item><p>For any other item type, the default priority is 0.</p></item></ulist><p>For a <nt xmlns:xlink="http://www.w3.org/1999/xlink" def="doc-xslt40-TypePattern" xlink:type="simple">TypePattern</nt> having one or more predicates,
               the default priority is 0.5</p></div4><div4 id="default-priority-for-gnode-patterns"><head>Default Priority for GNode Patterns</head><olist><item><p>If the pattern is a <nt xmlns:xlink="http://www.w3.org/1999/xlink" def="prod-xslt40-ParenthesizedPattern" xlink:type="simple"/> then the default
                     priority is the default priority of the contained pattern.</p></item><item><p>If the pattern is a <nt xmlns:xlink="http://www.w3.org/1999/xlink" def="prod-xslt40-UnionExprP" xlink:type="simple"/> then the default
                     priority is the maximum of the default priorities of the alternatives.</p><note><p>This is a backwards incompatible change from XSLT 3.0 and earlier
                     versions, which treated the template rule as equivalent to multiple
                     template rules with different priorities.</p><p>The change is made because of the increasing complexity of extending
                     the rule to patterns like <code nobreak="false">@(a|b)</code>, or <code nobreak="false">attribute(a|b, xs:integer)</code>
                     which are defined to be semantically identical to equivalent union patterns;
                     and to prevent confusion with type patterns such as 
                     <code nobreak="false">type(element(a)|element(b))</code>, where different rules apply.</p><p>The change affects any template rule with a union pattern that 
                        (a) has no explicit priority attribute, and (b) has multiple branches with
                     different default priority. It is <rfc2119>recommended</rfc2119> that processors
                     should output a compatibility warning when such template rules are encountered.</p><p>The change has two effects. Firstly, if two alternatives 
                        in a union pattern have different priority
                     (for example in a pattern such as <code nobreak="false">a | b/c</code>, the priority of one of
                     the branches will be raised to that of the other branch. Secondly, in cases where
                     the same item matches both branches, a call on <code nobreak="false">xsl:next-match</code> will
                     never cause the same template rule to be evaluated repeatedly.</p></note></item><item><p>If the pattern is an <nt xmlns:xlink="http://www.w3.org/1999/xlink" def="prod-xslt40-IntersectExceptExprP" xlink:type="simple">IntersectExceptExprP</nt> 
                     then the default priority of the pattern is that of the first operand pattern. </p></item><item><p>If the pattern is a <nt xmlns:xlink="http://www.w3.org/1999/xlink" def="prod-xslt40-PathExprP" xlink:type="simple">PathExprP</nt> taking the form
                        <code nobreak="false">/</code>, then the priority is -0.5.</p></item><item><p>If the pattern is a <nt xmlns:xlink="http://www.w3.org/1999/xlink" def="prod-xslt40-PathExprP" xlink:type="simple">PathExprP</nt> taking the form of an
                        <termref def="dt-eqname">EQName</termref> optionally preceded by a <nt xmlns:xlink="http://www.w3.org/1999/xlink" def="prod-xslt40-ForwardAxisP" xlink:type="simple">ForwardAxisP</nt> or has the form
                        <code nobreak="false">processing-instruction(</code>
                     <xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="XP40" ref="prod-xpath40-StringLiteral" xlink:type="simple">StringLiteral</xnt>
                     <code nobreak="false">)</code> or <code nobreak="false">processing-instruction(</code>
                     <xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="Names" ref="NT-NCName" xlink:type="simple">NCName</xnt>
                     <code nobreak="false">)</code> optionally preceded by a <nt xmlns:xlink="http://www.w3.org/1999/xlink" def="prod-xslt40-ForwardAxisP" xlink:type="simple">ForwardAxisP</nt>, then the priority is 0.</p></item><item><p>If the pattern is a <nt xmlns:xlink="http://www.w3.org/1999/xlink" def="prod-xslt40-PathExprP" xlink:type="simple">PathExprP</nt> taking the form of an
                        <xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="XP40" ref="prod-xpath40-ElementNodeType" xlink:type="simple">ElementNodeType</xnt> 
                     or <xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="XP40" ref="prod-xpath40-AttributeNodeType" xlink:type="simple">AttributeNodeType</xnt>, optionally
                     preceded by a <nt xmlns:xlink="http://www.w3.org/1999/xlink" def="prod-xslt40-ForwardAxisP" xlink:type="simple">ForwardAxisP</nt>, then the priority is as
                     shown in the table below. In this table:</p><ulist><item><p>The symbols <var>E</var>,
                        <var>A</var>, and <var>T</var> represent an arbitrary element name, attribute
                        name, and type name respectively;</p></item><item><p>The symbol <var>W</var> represents a 
                        <xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="XP40" ref="prod-xpath40-Wildcard" xlink:type="simple">Wildcard</xnt> other than <code nobreak="false">*</code>
                        (for example <code nobreak="false">prefix:*</code> or <code nobreak="false">*:local</code>);</p></item><item><p>The symbol <code nobreak="false">*</code> represents
                        itself.</p></item></ulist><p>The presence or absence of the symbol <code nobreak="false">?</code> following a type
                     name does not affect the priority.</p><note><p>The default priority of a pattern is always less than one, which means that user-allocated
                     priorities greater than or equal to one will always rank higher than a defaulted priority.</p></note><table class="data" border="1" cellpadding="5" width="100%"><caption>Default Priority of Patterns</caption><thead><tr><th rowspan="1" colspan="1" align="left" valign="top">Format</th><th rowspan="1" colspan="1" align="left" valign="top">Priority</th><th rowspan="1" colspan="1" align="left" valign="top">Notes</th></tr></thead><tbody><tr><td rowspan="1" colspan="1" align="left" valign="top">
                              <code nobreak="false">element()</code>
                           </td><td rowspan="1" colspan="1" align="left" valign="top">-0.5</td><td rowspan="1" colspan="1" align="left" valign="top">(equivalent to <code nobreak="false">*</code>)</td></tr><tr><td rowspan="1" colspan="1" align="left" valign="top">
                              <code nobreak="false">element(*)</code>
                           </td><td rowspan="1" colspan="1" align="left" valign="top">-0.5</td><td rowspan="1" colspan="1" align="left" valign="top">(equivalent to <code nobreak="false">*</code>)</td></tr><tr><td rowspan="1" colspan="1" align="left" valign="top">
                              <code nobreak="false">attribute()</code>
                           </td><td rowspan="1" colspan="1" align="left" valign="top">-0.5</td><td rowspan="1" colspan="1" align="left" valign="top">(equivalent to <code nobreak="false">@*</code>)</td></tr><tr><td rowspan="1" colspan="1" align="left" valign="top">
                              <code nobreak="false">attribute(*)</code>
                           </td><td rowspan="1" colspan="1" align="left" valign="top">-0.5</td><td rowspan="1" colspan="1" align="left" valign="top">(equivalent to <code nobreak="false">@*</code>)</td></tr><tr><td rowspan="1" colspan="1" align="left" valign="top">
                              <code nobreak="false">element(<var>W</var>)</code>
                           </td><td rowspan="1" colspan="1" align="left" valign="top">-0.25</td><td rowspan="1" colspan="1" align="left" valign="top"/></tr><tr><td rowspan="1" colspan="1" align="left" valign="top">
                              <code nobreak="false">attribute(<var>W</var>)</code>
                           </td><td rowspan="1" colspan="1" align="left" valign="top">-0.25</td><td rowspan="1" colspan="1" align="left" valign="top"/></tr><tr><td rowspan="1" colspan="1" align="left" valign="top">
                              <code nobreak="false">element(<var>E</var>)</code>
                           </td><td rowspan="1" colspan="1" align="left" valign="top">0</td><td rowspan="1" colspan="1" align="left" valign="top">(equivalent to E)</td></tr><tr><td rowspan="1" colspan="1" align="left" valign="top">
                              <code nobreak="false">element(*, <var>T</var>)</code>
                           </td><td rowspan="1" colspan="1" align="left" valign="top">0</td><td rowspan="1" colspan="1" align="left" valign="top">(matches by type only)</td></tr><tr><td rowspan="1" colspan="1" align="left" valign="top">
                              <code nobreak="false">attribute(<var>A</var>)</code>
                           </td><td rowspan="1" colspan="1" align="left" valign="top">0</td><td rowspan="1" colspan="1" align="left" valign="top">(equivalent to <code nobreak="false">@A</code>)</td></tr><tr><td rowspan="1" colspan="1" align="left" valign="top">
                              <code nobreak="false">attribute(*, <var>T</var>)</code>
                           </td><td rowspan="1" colspan="1" align="left" valign="top">0</td><td rowspan="1" colspan="1" align="left" valign="top">(matches by type only)</td></tr><tr><td rowspan="1" colspan="1" align="left" valign="top">
                              <code nobreak="false">element(<var>W</var>, <var>T</var>)</code>
                           </td><td rowspan="1" colspan="1" align="left" valign="top">0.125</td><td rowspan="1" colspan="1" align="left" valign="top"/></tr><tr><td rowspan="1" colspan="1" align="left" valign="top">
                              <code nobreak="false">element(<var>E</var>, <var>T</var>)</code>
                           </td><td rowspan="1" colspan="1" align="left" valign="top">0.25</td><td rowspan="1" colspan="1" align="left" valign="top">(matches by name and type)</td></tr><tr><td rowspan="1" colspan="1" align="left" valign="top">
                              <code nobreak="false">schema-element(<var>E</var>)</code>
                           </td><td rowspan="1" colspan="1" align="left" valign="top">0.25</td><td rowspan="1" colspan="1" align="left" valign="top">(matches by substitution group and type)</td></tr><tr><td rowspan="1" colspan="1" align="left" valign="top">
                              <code nobreak="false">attribute(<var>W</var>, <var>T</var>)</code>
                           </td><td rowspan="1" colspan="1" align="left" valign="top">0.125</td><td rowspan="1" colspan="1" align="left" valign="top"/></tr><tr><td rowspan="1" colspan="1" align="left" valign="top">
                              <code nobreak="false">attribute(<var>A</var>, <var>T</var>)</code>
                           </td><td rowspan="1" colspan="1" align="left" valign="top">0.25</td><td rowspan="1" colspan="1" align="left" valign="top">(matches by name and type)</td></tr><tr><td rowspan="1" colspan="1" align="left" valign="top">
                              <code nobreak="false">schema-attribute(<var>A</var>)</code>
                           </td><td rowspan="1" colspan="1" align="left" valign="top">0.25</td><td rowspan="1" colspan="1" align="left" valign="top">(matches by name and type)</td></tr></tbody></table></item><item><p>For a pattern such as <code nobreak="false">element(A|B)</code> or <code nobreak="false">attribute(A|B)</code>
               (more specifically, for any <nt xmlns:xlink="http://www.w3.org/1999/xlink" def="prod-xslt40-ElementNodeType" xlink:type="simple"/> or
               <nt xmlns:xlink="http://www.w3.org/1999/xlink" def="prod-xslt40-AttributeNodeType" xlink:type="simple"/> whose <nt xmlns:xlink="http://www.w3.org/1999/xlink" def="prod-xslt40-NameTestUnion" xlink:type="simple">NameTestUnion</nt>
               contains more than one <nt xmlns:xlink="http://www.w3.org/1999/xlink" def="prod-xslt40-NameTest" xlink:type="simple">NameTest</nt>) the default priority is the
               highest of the priorities obtained by considering each of the <nt xmlns:xlink="http://www.w3.org/1999/xlink" def="prod-xslt40-NameTest" xlink:type="simple">NameTests</nt>
               individually.</p><p>For example, the default priority of <code nobreak="false">element(x|y)</code> is 0, and
                     the default priority of <code nobreak="false">element(p:*|q:*, t)</code> is 0.125.</p><note><p>The effect of this rule is to make the pattern <code nobreak="false">element(A|B)</code>
                  equivalent to <code nobreak="false">element(A)|element(B)</code>.</p></note></item><item><p>If the pattern is a <nt xmlns:xlink="http://www.w3.org/1999/xlink" def="prod-xslt40-PathExprP" xlink:type="simple">PathExprP</nt> taking the form of a
                        <nt xmlns:xlink="http://www.w3.org/1999/xlink" def="prod-xslt40-DocumentNodeType" xlink:type="simple"/>, then if
                     it includes no <nt xmlns:xlink="http://www.w3.org/1999/xlink" def="prod-xslt40-ElementNodeType" xlink:type="simple"/> or <nt xmlns:xlink="http://www.w3.org/1999/xlink" def="prod-xslt40-SchemaElementNodeType" xlink:type="simple"/> the priority is −0.5. If it does include an
                        <nt xmlns:xlink="http://www.w3.org/1999/xlink" def="prod-xslt40-ElementNodeType" xlink:type="simple"/> or <nt xmlns:xlink="http://www.w3.org/1999/xlink" def="prod-xslt40-SchemaElementNodeType" xlink:type="simple"/>,
                     then the priority is the same as the priority of that <nt xmlns:xlink="http://www.w3.org/1999/xlink" def="prod-xslt40-ElementNodeType" xlink:type="simple"/> or <nt xmlns:xlink="http://www.w3.org/1999/xlink" def="prod-xslt40-SchemaElementNodeType" xlink:type="simple"/>, computed
                     according to the table above.</p></item><item>If the default namespace for elements and types is <code nobreak="false">#any</code>, and the pattern includes
               an unprefixed element name <code nobreak="false">E</code>, then the default priority is calculated as if this had been written
               <code nobreak="false">*:E</code>.</item><item><p>If the pattern is a <nt xmlns:xlink="http://www.w3.org/1999/xlink" def="prod-xslt40-PathExprP" xlink:type="simple">PathExprP</nt> taking the form of an
                        <xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="Names" ref="NT-NCName" xlink:type="simple">NCName</xnt><code nobreak="false">:*</code><phrase diff="add" at="2022-01-01">, 
                           <xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="XP40" ref="prod-xpath40-BracedURILiteral" xlink:type="simple"/>*,</phrase> or
                        <code nobreak="false">*:</code><xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="Names" ref="NT-NCName" xlink:type="simple">NCName</xnt>, optionally
                     preceded by a <nt xmlns:xlink="http://www.w3.org/1999/xlink" def="prod-xslt40-ForwardAxisP" xlink:type="simple">ForwardAxisP</nt>, then the priority is
                     −0.25. </p></item><item><p>If the pattern is a <nt xmlns:xlink="http://www.w3.org/1999/xlink" def="prod-xslt40-PathExprP" xlink:type="simple">PathExprP</nt> taking the form of any
                     other <xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="XP40" ref="prod-xpath40-NodeTest" xlink:type="simple">NodeTest</xnt>, optionally
                     preceded by a <nt xmlns:xlink="http://www.w3.org/1999/xlink" def="prod-xslt40-ForwardAxisP" xlink:type="simple">ForwardAxisP</nt>, then the priority is
                     −0.5.</p></item><item><p>The default priority of the pattern <code nobreak="false">jnode(*)</code> is −0.5.</p><p>The default priority of the equivalent pattern 
                        <code nobreak="false">jnode(*, item()*)</code> is also −0.5.</p></item><item><p>The default priority of the pattern <code nobreak="false">jnode(<var>S</var>)</code>,
                        where <var>S</var> is any constant, is 0 (zero).</p><p>The default priority of the equivalent pattern <code nobreak="false">jnode(<var>S</var>, item()*)</code>,
                        where <var>S</var> is any constant, is also 0 (zero).</p></item><item><p>The default priority of the pattern <code nobreak="false">jnode(())</code> is 0 (zero).</p><p>The default priority of the equivalent pattern <code nobreak="false">jnode((), item()*)</code> is also 0 (zero).</p></item><item><p>The default priority of the pattern <code nobreak="false">jnode(*, <var>T</var>)</code>,
                        where <var>T</var> is any sequence type other than <code nobreak="false">item()*</code>, is 0 (zero).</p></item><item><p>The default priority of the pattern <code nobreak="false">jnode(<var>S</var>, <var>T</var>)</code>,
                        where <var>S</var> is any constant, and <var>T</var> is any sequence type other 
                        than <code nobreak="false">item()*</code>, is +0.25.</p></item><item><p>The default priority of the pattern <code nobreak="false">jnode((), <var>T</var>)</code>, 
                        where <var>T</var> is any sequence type other 
                        than <code nobreak="false">item()*</code>, is +0.25.</p></item><item><p>In all other cases, the default priority is +0.5.</p></item></olist><note><p>In many cases this means that highly selective patterns have higher priority than
                  less selective patterns. The most common kind of pattern (a pattern that tests for
                  a node of a particular kind, with a particular <termref def="dt-expanded-qname">expanded QName</termref> or a particular type) has priority 0. The next less
                  specific kind of pattern (a pattern that tests for a node of a particular kind and
                  an <termref def="dt-expanded-qname">expanded QName</termref> with a particular
                  namespace URI) has priority −0.25. Patterns less specific than this
                  (patterns that just test for nodes of a given kind) have priority −0.5.
                  Patterns that specify both the name and the required type have a priority of
                  +0.25, putting them above patterns that only specify the name <emph>or</emph> the
                  type. Patterns more specific than this, for example patterns that include
                  predicates or that specify the ancestry of the required node, have priority
                  0.5.</p><p>However, it is not invariably true that a more selective pattern has higher
                  priority than a less selective pattern. For example, the priority of the pattern
                     <code nobreak="false">node()[self::*]</code> is higher than that of the pattern
                     <code nobreak="false">salary</code>. Similarly, the patterns <code nobreak="false">attribute(*,
                     xs:decimal)</code> and <code nobreak="false">attribute(*, xs:short)</code> have the same
                  priority, despite the fact that the latter pattern matches a subset of the nodes
                  matched by the former. Therefore, to achieve clarity in a <termref def="dt-stylesheet">stylesheet</termref> it is good practice to allocate
                  explicit priorities.</p></note><note><p>The patterns <code nobreak="false">element(N)</code> and <code nobreak="false">element(N, xs:anyType?)</code>
               have different default priority even though they match exactly the same nodes.
               Conversely, <code nobreak="false">element(N, xs:anyType)</code> and <code nobreak="false">element(N, xs:anyType?)</code>
               have the same default priority even though the first is more restrictive (it does not match 
               elements that are nilled).</p></note></div4></div3><div3 id="pattern-errors"><head>Errors in Patterns</head><p>A <termref def="dt-dynamic-error">dynamic error</termref> or <termref def="dt-type-error">type error</termref> that occurs during the evaluation of a
                     <termref def="dt-pattern">pattern</termref> against a particular item has the effect that the item being tested is
                  treated as not matching the pattern. The error does not cause the transformation
                  to fail, and cannot be caught by a try/catch expression surrounding the
                  instruction that causes the pattern to be evaluated.</p><note><p>The reason for this provision is that it is difficult for the stylesheet author
                     to predict which predicates in a pattern will actually be evaluated. In the
                     case of match patterns in template rules, it is not even possible to predict
                     which patterns will be evaluated against a particular node.</p><p>There is a risk that ignoring errors in this way may make programming mistakes
                     harder to debug. Implementations may mitigate this by providing warnings or
                     other diagnostics when evaluation of a pattern triggers an error condition.</p><p>Static errors in patterns, including dynamic and type errors that are raised
                     statically as permitted by the specification, are raised in the normal way
                     and cause the transformation to fail.</p></note><p>The requirement to detect and raise a <termref def="dt-circularity"/> as a dynamic error overrides this rule.</p></div3></div2><div2 id="applying-templates"><head>Applying Template Rules</head><changes><change date="2022-01-01" issue="85">
                  The <elcode>xsl:for-each</elcode> and <elcode>xsl:apply-templates</elcode>
                  instructions acquire an attribute <code nobreak="false">separator</code> that can be
                  used to insert content between adjacent items. [This change was in the
                  editor's draft adopted as a baseline when the WG commenced work.]
               </change></changes><e:element-syntax xmlns:e="http://www.w3.org/1999/XSL/Spec/ElementSyntax" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" name="apply-templates">
      <e:in-category name="instruction"/>
      <e:attribute name="select">
         <e:data-type name="expression"/>
      </e:attribute>
      <e:attribute name="mode">
         <e:data-type name="token"/>
      </e:attribute>
      <e:attribute name="separator">
         <e:attribute-value-template>
            <e:data-type name="string"/>
         </e:attribute-value-template>
      </e:attribute>
      <e:choice repeat="zero-or-more">
         <e:element name="sort"/>
         <e:element name="with-param"/>
      </e:choice>
      <e:allowed-parents>
         <e:parent-category name="sequence-constructor"/>
      </e:allowed-parents>
   </e:element-syntax><p>The <elcode>xsl:apply-templates</elcode> instruction takes as input a sequence of
                  items (typically nodes in a <termref def="dt-source-tree">source tree</termref>), and produces as output a sequence of
               items; these will often be nodes to be added to a <termref def="dt-result-tree">result tree</termref>.</p><p>If the instruction has one or more <elcode>xsl:sort</elcode> children, then the input
               sequence is sorted as described in <specref ref="sorting"/>. The result of this sort
               is referred to below as the <term>sorted sequence</term>; if there are no
                  <elcode>xsl:sort</elcode> elements, then the sorted sequence is the same as the
               input sequence.</p><p>Each item in the input sequence is processed by
               finding a <termref def="dt-template-rule">template rule</termref> whose <termref def="dt-pattern">pattern</termref> matches that item. If there is more than one such template rule, the best among them
               is chosen, using rules described in <specref ref="conflict"/>. If there is no
               template rule whose pattern matches the item, a
               built-in template rule is used (see <specref ref="built-in-rule"/>). The chosen
               template rule is evaluated. The rule that matches the <var>N</var>th item in the sorted sequence is evaluated with that
                  item as the <termref def="dt-context-item">context item</termref>, with <var>N</var> as the <termref def="dt-context-position">context position</termref>, and with the length of the
               sorted sequence as the <termref def="dt-context-size">context size</termref>. Each
               template rule that is evaluated produces a sequence of items as its result. The
               resulting sequences (one for each item in the
               sorted sequence) are then concatenated, to form a single sequence. They are
               concatenated retaining the order of the items in
               the sorted sequence. The final concatenated sequence forms the result of the
                  <elcode>xsl:apply-templates</elcode> instruction. </p><example><head>Applying Template Rules</head><p>Suppose the source document is as follows:</p><eg xml:space="preserve" role="xml">&lt;message&gt;Proceed &lt;emph&gt;at once&lt;/emph&gt; to the exit!&lt;/message&gt;</eg><p>This can be processed using the two template rules shown below.</p><eg xml:space="preserve" role="xslt-declarations">&lt;xsl:template match="message"&gt;
  &lt;p&gt;
    &lt;xsl:apply-templates select="child::node()"/&gt;
  &lt;/p&gt;
&lt;/xsl:template&gt;

&lt;xsl:template match="emph"&gt;
  &lt;b&gt;
    &lt;xsl:apply-templates select="child::node()"/&gt;
  &lt;/b&gt;
&lt;/xsl:template&gt;</eg><p>There is no template rule for the document node; the built-in template rule for
                  this node will cause the <code nobreak="false">message</code> element to be processed. The
                  template rule for the <code nobreak="false">message</code> element causes a <code nobreak="false">p</code> element
                  to be written to the <termref def="dt-result-tree">result tree</termref>; the
                  contents of this <code nobreak="false">p</code> element are constructed as the result of the
                     <elcode>xsl:apply-templates</elcode> instruction. This instruction selects the
                  three child nodes of the <code nobreak="false">message</code> element (a text node containing the
                  value <code nobreak="false">Proceed </code>, an <code nobreak="false">emph</code> element node, and a text node
                  containing the value <code nobreak="false"> to the exit!</code>). The two text nodes are
                  processed using the built-in template rule for text nodes, which returns a copy of
                  the text node. The <code nobreak="false">emph</code> element is processed using the explicit
                  template rule that specifies <code nobreak="false">match="emph"</code>.</p><p>When the <code nobreak="false">emph</code> element is processed, this template rule constructs a
                     <code nobreak="false">b</code> element. The contents of the <code nobreak="false">b</code> element are
                  constructed by means of another <elcode>xsl:apply-templates</elcode> instruction,
                  which in this case selects a single node (the text node containing the value
                     <code nobreak="false">at once</code>). This is again processed using the built-in template
                  rule for text nodes, which returns a copy of the text node.</p><p>The final result of the <code nobreak="false">match="message"</code> template rule thus consists
                  of a <code nobreak="false">p</code> element node with three children: a text node containing the
                  value <code nobreak="false">Proceed </code>, a <code nobreak="false">b</code> element that is the parent of a
                  text node containing the value <code nobreak="false">at once</code>, and a text node containing
                  the value <code nobreak="false"> to the exit!</code>. This <termref def="dt-result-tree">result
                     tree</termref> might be serialized as:</p><eg xml:space="preserve" role="xml">&lt;p&gt;Proceed &lt;b&gt;at once&lt;/b&gt; to the exit!&lt;/p&gt;</eg></example><p>The default value of the <code nobreak="false">select</code> attribute is <code nobreak="false">child::node()</code>,
               which causes all the children of the context node to be processed.</p><p>
               <error spec="XT" type="type" class="TE" code="0510"><p>It is a <termref def="dt-type-error">type error</termref> if an
                        <elcode>xsl:apply-templates</elcode> instruction with no <code nobreak="false">select</code>
                     attribute is evaluated when the <termref def="dt-context-item">context
                        item</termref> is not a node. </p></error>
            </p><p>A <code nobreak="false">select</code> attribute can be used to process items selected by an expression instead of processing all children. The
               value of the <code nobreak="false">select</code> attribute is an <termref def="dt-expression">expression</termref>. </p><example><head>Applying Templates to Selected Nodes</head><p>The following example processes all of the <code nobreak="false">given-name</code> children of the
                     <code nobreak="false">author</code> elements that are children of
                  <code nobreak="false">author-group</code>:</p><eg xml:space="preserve" role="xslt-declaration xmlns:fo='fo'">&lt;xsl:template match="author-group"&gt;
  &lt;fo:wrapper&gt;
    &lt;xsl:apply-templates select="author/given-name"/&gt;
  &lt;/fo:wrapper&gt;
&lt;/xsl:template&gt;</eg></example><example><head>Applying Templates to Nodes that are not Descendants</head><p>It is also possible to process elements that are not descendants of the context
                  node. This example assumes that a <code nobreak="false">department</code> element has
                     <code nobreak="false">group</code> children and <code nobreak="false">employee</code> descendants. It finds an
                  employee’s department and then processes the <code nobreak="false">group</code> children of
                  the <code nobreak="false">department</code>.</p><eg xml:space="preserve" role="xslt-declaration xmlns:fo='fo'">&lt;xsl:template match="employee"&gt;
  &lt;fo:block&gt;
    Employee &lt;xsl:apply-templates select="name"/&gt; belongs to group
    &lt;xsl:apply-templates select="ancestor::department/group"/&gt;
  &lt;/fo:block&gt;
&lt;/xsl:template&gt;</eg></example><example><head>Matching Nodes by Schema-Defined Types</head><p>It is possible to write template rules that are matched according to the
                  schema-defined type of an element or attribute. The following example applies
                  different formatting to the children of an element depending on their type:</p><eg xml:space="preserve" role="xslt-declaration">&lt;xsl:template match="product"&gt;
  &lt;table&gt;
    &lt;xsl:apply-templates select="*"/&gt;
  &lt;/table&gt;
&lt;/xsl:template&gt;

&lt;xsl:template match="product/*" priority="3"&gt;
  &lt;tr&gt;
    &lt;td&gt;&lt;xsl:value-of select="name()"/&gt;&lt;/td&gt;
    &lt;td&gt;&lt;xsl:next-match/&gt;&lt;/td&gt;
  &lt;/tr&gt;
&lt;/xsl:template&gt;

&lt;xsl:template match="product/element(*, xs:decimal) | 
                     product/element(*, xs:double)" priority="2"&gt;  
  &lt;xsl:value-of select="format-number(xs:double(.), '#,###0.00')"/&gt;
&lt;/xsl:template&gt;

&lt;xsl:template match="product/element(*, xs:date)" priority="2"&gt;
  &lt;xsl:value-of select="format-date(., '[Mn] [D], [Y]')"/&gt;
&lt;/xsl:template&gt;

&lt;xsl:template match="product/*" priority="1.5"&gt;
  &lt;xsl:value-of select="."/&gt;
&lt;/xsl:template&gt;</eg><p>The <elcode>xsl:next-match</elcode> instruction is described in <specref ref="apply-imports"/>.</p></example><example><head>Re-ordering Elements in the Result Tree</head><p>Multiple <elcode>xsl:apply-templates</elcode> elements can be used within a single
                  template to do simple reordering. The following example creates two HTML tables.
                  The first table is filled with domestic sales while the second table is filled
                  with foreign sales.</p><eg xml:space="preserve" role="xslt-declaration">&lt;xsl:template match="product"&gt;
  &lt;table&gt;
    &lt;xsl:apply-templates select="sales/domestic"/&gt;
  &lt;/table&gt;
  &lt;table&gt;
    &lt;xsl:apply-templates select="sales/foreign"/&gt;
  &lt;/table&gt;
&lt;/xsl:template&gt;</eg></example><example><head>Processing Recursive Structures</head><p>It is possible for there to be two matching descendants where one is a descendant
                  of the other. This case is not treated specially: both descendants will be
                  processed as usual.</p><p> For example, given a source document</p><eg xml:space="preserve" role="xml">&lt;doc&gt;&lt;div&gt;&lt;div&gt;&lt;/div&gt;&lt;/div&gt;&lt;/doc&gt;</eg><p>the rule</p><eg xml:space="preserve" role="xslt-declaration">&lt;xsl:template match="doc"&gt;
  &lt;xsl:apply-templates select=".//div"/&gt;
&lt;/xsl:template&gt;</eg><p>will process both the outer <code nobreak="false">div</code> and inner <code nobreak="false">div</code>
                  elements.</p><p>This means that if the template rule for the <code nobreak="false">div</code> element processes
                  its own children, then these grandchildren will be processed more than once, which
                  is probably not what is required. The solution is to process one level at a time
                  in a recursive descent, by using <code nobreak="false">select="div"</code> in place of
                     <code nobreak="false">select=".//div"</code>
               </p></example><example><head>Applying Templates to Atomic Items</head><p>This example reads a non-XML text file and processes it line-by-line, applying
                  different template rules based on the content of each line:</p><eg xml:space="preserve" role="xslt-declarations" diff="chg" at="2022-01-01">&lt;xsl:template name="main"&gt;
  &lt;xsl:apply-templates select="unparsed-text-lines('input.txt')"/&gt;
&lt;/xsl:template&gt;

&lt;xsl:template match="type(xs:string)[starts-with(., '==')]"&gt;
  &lt;h2&gt;&lt;xsl:value-of select="replace(., '==', '')"/&gt;&lt;/h2&gt;
&lt;/xsl:template&gt;

&lt;xsl:template match="type(xs:string)[starts-with(., '::')]"&gt;
  &lt;p class="indent"&gt;&lt;xsl:value-of select="replace(., '::', '')"/&gt;&lt;/p&gt;
&lt;/xsl:template&gt;

&lt;xsl:template match="type(xs:string)"&gt;
  &lt;p class="body"&gt;&lt;xsl:value-of select="."/&gt;&lt;/p&gt;
&lt;/xsl:template&gt;

</eg></example><example><head>Applying Templates to JSON Documents</head><p>This example reads a JSON data file and formats it as XHTML.</p><p>It takes the following JSON data as input:</p><eg xml:space="preserve">[
  { "Title": "Computer Architecture",
    "Authors": [ "Enid Blyton"] ,
    "Category": "Computers",
    "Price": 42.60
  },
  { "Title": "Steppenwolf",
    "Authors": [ "Hermann Hesse" ],
    "Category": "Fiction",
    "Price": 12.00
  },
  {  "Title": "How to Explore Outer Space with Binoculars",
     "Authors": [ "Bruce Betts", "Erica Colon" ],
     "Category": "Science",
     "Price": 10.40
  }
]</eg><p>The following template rules are used. The setting <code nobreak="false">expand-text="yes"</code> is assumed:</p><eg xml:space="preserve">&lt;xsl:record-type name="book"&gt;
  &lt;xsl:field name="Title"/&gt;
  &lt;xsl:field name="Authors"/&gt;
  &lt;xsl:field name="Category"/&gt;
&lt;/xsl:record-type&gt;

&lt;xsl:template name="xsl:initial-template"&gt;
  &lt;xsl:apply-templates select="parse-json('input.json')"/&gt;
&lt;/xsl:template&gt;  

&lt;xsl:template match="array(book)"&gt;
  &lt;h1&gt;Christmas Book Selection&lt;/h1&gt;
  &lt;table&gt;
    &lt;thead&gt;
       &lt;tr&gt;
         &lt;th&gt;Title&lt;/th&gt;
         &lt;th&gt;Authors&lt;/th&gt;
         &lt;th&gt;Category&lt;/th&gt;
         &lt;th&gt;Price&lt;/th&gt;
       &lt;/tr&gt;
    &lt;/thead&gt;
    &lt;tbody&gt;
      &lt;xsl:apply-templates select="?*"/&gt;
    &lt;/tbody&gt;
  &lt;/table&gt;
&lt;/xsl:template&gt;

&lt;xsl:template match="type(book)"&gt;
  &lt;tr&gt;
    &lt;td&gt;{?Title}&lt;/td&gt;
    &lt;td&gt;{?Authors?* =&gt; string-join(", ")}&lt;/td&gt;
    &lt;td&gt;{?Category}&lt;/td&gt;
    &lt;td&gt;${?Price}&lt;/td&gt;
  &lt;/tr&gt;
&lt;/xsl:template&gt;
</eg></example><note><p>The <elcode>xsl:apply-templates</elcode> instruction is most commonly used to
                  process nodes that are descendants of the context node. Such use of
                     <elcode>xsl:apply-templates</elcode> cannot result in non-terminating
                  processing loops. However, when <elcode>xsl:apply-templates</elcode> is used to
                  process elements that are not descendants of the context node, the possibility
                  arises of non-terminating loops. For example,</p><eg role="error" xml:space="preserve">&lt;xsl:template match="foo"&gt;
  &lt;xsl:apply-templates select="."/&gt;
&lt;/xsl:template&gt;</eg><p>Implementations may be able to detect such loops in some cases, but the
                  possibility exists that a <termref def="dt-stylesheet">stylesheet</termref> may
                  enter a non-terminating loop that an implementation is unable to detect. This may
                  present a denial of service security risk.</p></note></div2><div2 id="apply-templates-separator" diff="add" at="2022-01-01"><head>The <code nobreak="false">separator</code> attribute</head><p>If the <code nobreak="false">separator</code> attribute of <elcode>xsl:apply-templates</elcode>
               is present, then its <termref def="dt-effective-value"/>
               is inserted, as a text node, into the output sequence, immediately after the results of processing each item in the sorted
               sequence other than the last.</p><p>For example, if the <code nobreak="false">ARTICLE</code> element has a number of element children named <code nobreak="false">AUTHOR</code>,
               the following code will produce a sorted, comma-separated list of authors:</p><eg xml:space="preserve">
&lt;xsl:template match="ARTICLE"&gt;
  &lt;article&gt;
     ...
     &lt;xsl:text&gt;Author(s): &lt;/xsl:text&gt;
     &lt;xsl:apply-templates select="AUTHOR" separator=", "&gt;
       &lt;xsl:sort select="LAST-NAME"/&gt;
       &lt;xsl:sort select="FIRST-NAME"/&gt;
     &lt;/xsl:apply-templates&gt;
     ...
  &lt;/article&gt;
&lt;/xsl:template&gt;
&lt;xsl:template match="AUTHOR" expand-text="yes"&gt;
  &lt;xsl:text&gt;{FIRST-NAME} {LAST-NAME}&lt;/xsl:text&gt;
&lt;/xsl:template&gt;  
 </eg><p>The node identity of any text nodes that are inserted is <termref def="dt-implementation-dependent"/>. Specifically,
               it is not defined whether all the text nodes inserted in the course of one evaluation of the instruction are identical
               to each other, nor whether they are identical to the text nodes inserted in the course of another evaluation of this
               instruction, nor whether they are identical to any other parentless text nodes having the same string value.</p><p>If the separator is a zero-length string, then a zero-length text node is inserted into the sequence. (If the
               sequence is used for constructing the value of a node, then zero-length text nodes will be discarded: see
               <specref ref="constructing-simple-content"/> and <specref ref="constructing-complex-content"/>.)</p></div2><div2 id="conflict"><head>Conflict Resolution for Template Rules</head><p>It is possible for a selected item to match more
               than one <termref def="dt-template-rule">template rule</termref> with a given
                  <termref def="dt-mode">mode</termref>
               <var>M</var>. When this happens, only one template rule is evaluated for the item. The template rule to be used is determined as
               follows:</p><olist><item><p>First, only the matching template rule or rules with the highest <termref def="dt-import-precedence">import precedence</termref> are considered. Other
                     matching template rules with lower precedence are eliminated from
                     consideration.</p></item><item><p>Next, of the remaining matching rules, only those with the highest priority are
                     considered. Other matching template rules with lower priority are eliminated
                     from consideration.</p><p><termdef term="priority" id="dt-priority">The <term>priority</term> of a
                        template rule is specified by the <code nobreak="false">priority</code> attribute on the
                           <elcode>xsl:template</elcode> declaration. If no priority is specified
                        explicitly for a template rule, its <termref def="dt-default-priority">default priority</termref> 
                        is used, as defined in <specref ref="default-priority"/>.</termdef></p><p>
                     <error spec="XT" type="static" class="SE" code="0530"><p>The value of the <code nobreak="false">priority</code> attribute <error.extra> of the
                                 <elcode>xsl:template</elcode> element</error.extra>
                           <rfc2119>must</rfc2119> conform to the rules for the
                              <code nobreak="false">xs:decimal</code> type defined in <bibref ref="xmlschema-2"/>.
                           Negative values are permitted.</p></error>
                  </p></item><item><p>If this leaves more than one matching template rule, then:</p><olist><item><p>If the <termref def="dt-mode">mode</termref>
                           <var>M</var> has an <elcode>xsl:mode</elcode> declaration, and the
                           attribute value <code nobreak="false">on-multiple-match="fail"</code> is specified in the
                           mode declaration, a dynamic error is raised. The error is treated as
                           occurring in the <elcode>xsl:apply-templates</elcode> instruction, and
                           can be recovered by wrapping that instruction in an
                              <elcode>xsl:try</elcode> instruction.</p><p>
                           <error spec="XT" type="dynamic" class="DE" code="0540"><p>It is a <termref def="dt-dynamic-error"> dynamic error</termref> if the
                                 conflict resolution algorithm for template rules leaves more than
                                 one matching template rule  when the
                                    declaration of the relevant <termref def="dt-mode">mode</termref> has an <code nobreak="false">on-multiple-match</code>
                                    attribute with the value <code nobreak="false">fail</code>.</p></error></p></item><item><p>Otherwise, of the matching template rules that remain, the one that
                           occurs last in <termref def="dt-declaration-order">declaration
                              order</termref> is used.</p></item></olist><note><p>This was a recoverable error in XSLT 2.0, meaning that it was
                        implementation-defined whether the error was raised, or whether the
                        ambiguity was resolved by taking the last matching rule in declaration
                        order.  In XSLT 3.0 and 4.0 this situation is not an error unless the
                        attribute value <code nobreak="false">on-multiple-match="fail"</code> is specified in the
                        mode declaration. It is also possible to request warnings when this
                        condition arises, by means of the attribute <code nobreak="false">warning-on-multiple-match="yes"</code>. </p></note></item></olist></div2><div2 id="modes"><head>Modes</head><p>
               <termdef id="dt-mode" term="mode"> A <term>mode</term> is a set of template rules;
                  when the <elcode>xsl:apply-templates</elcode> instruction selects a set of items
                  for processing, it identifies the rules to be used for processing those items by
                  nominating a mode, explicitly or implicitly.</termdef> Modes allow a node in a
                  <termref def="dt-source-tree">source tree</termref> (for example) to be processed
               multiple times, each time producing a different result. They also allow different
               sets of <termref def="dt-template-rule">template rules</termref> to be active when
               processing different trees, for example when processing documents loaded using the
                  <function>document</function> function (see <specref ref="func-document"/>). </p><p>Modes are identified by an <termref def="dt-expanded-qname">expanded QName</termref>; in addition to any named modes, there is always one
               unnamed mode available. Whether a mode is named or unnamed, its properties
                  <rfc2119>may</rfc2119> be defined in an <elcode>xsl:mode</elcode> declaration. If
               a mode name is used (for example in an <elcode>xsl:template</elcode> declaration or
               an <elcode>xsl:apply-templates</elcode> instruction) and no declaration of that mode
               appears in the stylesheet, the mode is implicitly declared with default
               properties.</p><div3 id="declaring-modes"><head>Declaring Modes</head><changes><change issue="750" PR="751" date="2023-10-16">
                     The <elcode>xsl:mode</elcode> declaration acquires an attribute
                     <code nobreak="false">as="sequence-type"</code> which declares the return type of 
                     all template rules in that mode.
                  </change><change issue="1724" PR="1929" date="2025-04-13">
                     The <elcode>xsl:mode</elcode> declaration acquires an attribute
                     <code nobreak="false">copy-namespaces</code> which determines whether or not the built-in
                     template rule copies unused namespace bindings.
                  </change></changes><e:element-syntax xmlns:e="http://www.w3.org/1999/XSL/Spec/ElementSyntax" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" name="mode">
      <e:in-category name="declaration"/>
      <e:attribute name="name">
         <e:data-type name="eqname"/>
      </e:attribute>
      <e:attribute name="as" required="no" default="'item()*'">
         <e:data-type name="sequence-type"/>
      </e:attribute>
      <e:attribute name="streamable" default="'no'">
         <e:data-type name="boolean"/>
      </e:attribute>
      <e:attribute name="use-accumulators" default="''">
         <e:data-type name="tokens"/>
      </e:attribute>
      <e:attribute name="on-no-match" default="'text-only-copy'">
         <e:constant value="deep-copy"/>
         <e:constant value="shallow-copy"/>
         <e:constant value="shallow-copy-all"/>
         <e:constant value="deep-skip"/>
         <e:constant value="shallow-skip"/>
         <e:constant value="text-only-copy"/>
         <e:constant value="fail"/>
      </e:attribute>
      <e:attribute name="on-multiple-match" default="'use-last'">
         <e:constant value="use-last"/>
         <e:constant value="fail"/>
      </e:attribute>
      <e:attribute name="warning-on-no-match">
         <e:data-type name="boolean"/>
      </e:attribute>
      <e:attribute name="warning-on-multiple-match">
         <e:data-type name="boolean"/>
      </e:attribute>
      <e:attribute name="typed" default="'unspecified'">
         <e:data-type name="string"/>
      </e:attribute>
      <e:attribute name="copy-namespaces" default="'yes'">
         <e:data-type name="boolean"/>
      </e:attribute>
      <e:attribute name="visibility" default="'private'">
         <e:constant value="public"/>
         <e:constant value="private"/>
         <e:constant value="final"/>
      </e:attribute>
      <e:sequence>
         <e:element repeat="zero-or-more" name="template"/>
      </e:sequence>
      <e:allowed-parents>
         <e:parent name="package"/>
         <e:parent name="stylesheet"/>
         <e:parent name="transform"/>
      </e:allowed-parents>
   </e:element-syntax><p>
                  <termdef id="dt-unnamed-mode" term="unnamed mode">The <term>unnamed mode</term> is the default mode used when no
                        <code nobreak="false">mode</code> attribute is specified on an
                        <elcode>xsl:apply-templates</elcode> instruction or
                        <elcode>xsl:template</elcode> declaration, unless a different <termref def="dt-default-mode"/>
                     has been specified using the <code nobreak="false">[xsl:]default-mode</code> attribute of a containing
                        element.</termdef>
               </p><p>Every <termref def="dt-mode">mode</termref> other than the <termref def="dt-unnamed-mode">unnamed mode</termref> is identified by an <termref def="dt-expanded-qname">expanded QName</termref>.</p><p>A <termref def="dt-stylesheet">stylesheet</termref> may contain multiple
                     <elcode>xsl:mode</elcode> declarations and may include or import <termref def="dt-stylesheet-module">stylesheet modules</termref> that also contain
                     <elcode>xsl:mode</elcode> declarations. The name of an
                     <elcode>xsl:mode</elcode> declaration is the value of its <code nobreak="false">name</code>
                  attribute, if any.</p><p>
                  <termdef id="dt-mode-definition" term="mode definition">All the
                        <elcode>xsl:mode</elcode> declarations in a <termref def="dt-package"/> that share the same
                     name are grouped into a named <term>mode definition</term>; those that have no
                     name are grouped into a single unnamed mode definition.</termdef>
               </p><p>The <code nobreak="false">declared-modes</code> attribute of
                     the <elcode>xsl:package</elcode> element determines whether implicit mode
                     declarations are allowed, as described in <specref ref="requiring-explicit-modes"/>. If the package allows implicit mode
                     declarations, then  if a <termref def="dt-stylesheet">stylesheet</termref> does not contain a declaration of the unnamed mode, a
                  declaration is implied equivalent to an <elcode>xsl:mode</elcode> element with
                     no attributes. Similarly, if there
                  is a mode that is named in an <elcode>xsl:template</elcode> or
                     <elcode>xsl:apply-templates</elcode> element, or in the <code nobreak="false">[xsl:]default-mode</code> attribute of a containing
                     element, and the <termref def="dt-stylesheet">stylesheet</termref>
                  does not contain a declaration of that mode, then a declaration is implied
                  comprising an <elcode>xsl:mode</elcode> element with a <code nobreak="false">name</code> attribute
                     equal to that mode name, plus the attribute
                        <code nobreak="false">visibility="private"</code>. </p><p>The attributes of the <elcode>xsl:mode</elcode> declaration establish values for a
                  number of properties of a mode. The allowed values and meanings of the attributes
                  are given in the following table.</p><table class="data" border="1" cellpadding="5" width="100%"><caption>Attributes of the <code nobreak="false">xsl:mode</code> Element</caption><thead><tr><th rowspan="1" colspan="1" align="left" valign="top">Attribute</th><th rowspan="1" colspan="1" align="left" valign="top">Values</th><th rowspan="1" colspan="1" align="left" valign="top">Meaning</th></tr></thead><tbody><tr><td valign="top" rowspan="1" colspan="1" align="left">name</td><td valign="top" rowspan="1" colspan="1" align="left">An <termref def="dt-eqname">EQName</termref></td><td valign="top" rowspan="1" colspan="1" align="left">Specifies the name of the mode. If omitted, this
                              <elcode>xsl:mode</elcode> declaration provides properties of the
                              <termref def="dt-unnamed-mode">unnamed mode</termref></td></tr><tr diff="add" at="2022-01-01"><td valign="top" rowspan="1" colspan="1" align="left">as</td><td valign="top" rowspan="1" colspan="1" align="left">A <code nobreak="false">SequenceType</code></td><td valign="top" rowspan="1" colspan="1" align="left">Declares the type of value returned by all
                           template rules in this mode. If any template rules in this mode declare their
                        return type using an <code nobreak="false">as</code> attribute on <elcode>xsl:template</elcode>,
                        the values must be consistent.</td></tr><tr><td valign="top" rowspan="1" colspan="1" align="left">streamable</td><td valign="top" rowspan="1" colspan="1" align="left"><code nobreak="false">yes</code> or <code nobreak="false">no</code> (default
                              <code nobreak="false">no</code>)</td><td valign="top" rowspan="1" colspan="1" align="left">Determines whether template rules in this mode are to be
                           capable of being processed using <termref def="dt-streaming"/>. If the
                           value <code nobreak="false">yes</code> is specified, then the body of any <termref def="dt-template-rule">template rule</termref> that uses this mode
                              <rfc2119>must</rfc2119> conform to the rules for streamable templates
                           given in <xspecref spec="SG40" ref="streamable-templates"/>.</td></tr><tr><td valign="top" rowspan="1" colspan="1" align="left">use-accumulators</td><td valign="top" rowspan="1" colspan="1" align="left">List of accumulator names, or <code nobreak="false">#all</code> (default is the empty list)</td><td valign="top" rowspan="1" colspan="1" align="left">Relevant only when this mode is the <termref def="dt-initial-mode"/>
                           of the transformation, determines which accumulators are applicable to documents
                           containing nodes in the <termref def="dt-initial-match-selection"/>. For
                        further details see <specref ref="applicability-of-accumulators"/>.</td></tr><tr><td valign="top" rowspan="1" colspan="1" align="left">on-no-match</td><td valign="top" rowspan="1" colspan="1" align="left">One of <code nobreak="false">deep-copy</code>,
                                 <code nobreak="false">shallow-copy</code>, <code nobreak="false">deep-skip</code>,
                                 <code nobreak="false">shallow-skip</code>, <code nobreak="false">text-only-copy</code> or
                                 <code nobreak="false">fail</code> (default
                           <code nobreak="false">text-only-copy</code>)</td><td valign="top" rowspan="1" colspan="1" align="left">Determines selection of the built-in <termref def="dt-template-rule">template rules</termref> that are used to
                           process an item when an
                              <elcode>xsl:apply-templates</elcode> instruction selects an item that does not match any
                           user-written <termref def="dt-template-rule">template rule</termref> in
                           the <termref def="dt-stylesheet">stylesheet</termref>. For details, see
                              <specref ref="built-in-rule"/>.</td></tr><tr><td valign="top" rowspan="1" colspan="1" align="left">on-multiple-match</td><td valign="top" rowspan="1" colspan="1" align="left">One of <code nobreak="false">fail</code> or <code nobreak="false">use-last</code> (default
                              <code nobreak="false">use-last</code>)</td><td valign="top" rowspan="1" colspan="1" align="left">Defines the action to be taken when
                              <elcode>xsl:apply-templates</elcode> is used in this mode and more
                           than one user-written <termref def="dt-template-rule">template
                              rule</termref> is available to process an item, each having the same <termref def="dt-import-precedence">import precedence</termref> and <termref def="dt-priority">priority</termref>. The value <code nobreak="false">fail</code>
                           indicates that it is a <termref def="dt-dynamic-error"> dynamic error</termref> if more
                           than one template rule matches an
                              item. The value <code nobreak="false">use-last</code> indicates that the
                           situation is not to be treated as an error (the last template in <termref def="dt-declaration-order">declaration order</termref> is the one that
                           is used). </td></tr><tr><td valign="top" rowspan="1" colspan="1" align="left">warning-on-no-match</td><td valign="top" rowspan="1" colspan="1" align="left">One of <code nobreak="false">yes</code> or <code nobreak="false">no</code>. The default is
                              <termref def="dt-implementation-defined"/>
                        </td><td valign="top" rowspan="1" colspan="1" align="left">Requests the <termref def="dt-processor">processor</termref> to output (or not to output) a warning message in
                           the case where an <elcode>xsl:apply-templates</elcode> instruction
                           selects an item that matches
                           no user-written template rule. The form and destination of such warnings
                           is <termref def="dt-implementation-defined">implementation-defined</termref>. The processor
                              <rfc2119>may</rfc2119> ignore this attribute, for example if the
                           environment provides no suitable means of communicating with the user.
                        </td></tr><tr><td valign="top" rowspan="1" colspan="1" align="left">warning-on-multiple-match</td><td valign="top" rowspan="1" colspan="1" align="left">One of <code nobreak="false">yes</code> or <code nobreak="false">no</code>. The default is
                              <termref def="dt-implementation-defined"/>
                        </td><td valign="top" rowspan="1" colspan="1" align="left">Requests the <termref def="dt-processor">processor</termref> to output a warning message in the case where an
                              <elcode>xsl:apply-templates</elcode> instruction selects an item that matches multiple
                           template rules having the same <termref def="dt-import-precedence">import
                              precedence</termref> and <termref def="dt-priority">priority</termref>. The form and destination of such warnings is
                              <termref def="dt-implementation-defined">implementation-defined</termref>. The processor
                              <rfc2119>may</rfc2119> ignore this attribute, for example if the
                           environment provides no suitable means of communicating with the
                           user.</td></tr><tr><td valign="top" rowspan="1" colspan="1" align="left">typed</td><td valign="top" rowspan="1" colspan="1" align="left">One of <code nobreak="false">yes</code>, <code nobreak="false">no</code>,
                              <code nobreak="false">strict</code>, <code nobreak="false">lax</code>, or <code nobreak="false">unspecified</code>.
                           The default is <code nobreak="false">unspecified</code>.</td><td valign="top" rowspan="1" colspan="1" align="left">See <specref ref="xsl-mode-typed"/>.</td></tr><tr><td valign="top" rowspan="1" colspan="1" align="left">copy-namespaces</td><td valign="top" rowspan="1" colspan="1" align="left">One of <code nobreak="false">yes</code> or <code nobreak="false">no</code>. The default is
                              <code nobreak="false">yes</code>.</td><td valign="top" rowspan="1" colspan="1" align="left">If <code nobreak="false">on-no-match</code> is <code nobreak="false">shallow-copy</code>,
                           <code nobreak="false">shallow-copy-all</code>, or <code nobreak="false">deep-copy</code>, this attribute determines the
                           effective value of the <code nobreak="false">copy-namespaces</code> attribute on the implicit <code nobreak="false">xsl:copy</code>
                           or <code nobreak="false">xsl:copy-of</code> instruction in the built-in template rule 
                           (see <specref ref="built-in-rule"/>). In other cases it is ignored, apart from checking that
                           its value is valid.
                        </td></tr><tr><td valign="top" rowspan="1" colspan="1" align="left">visibility</td><td valign="top" rowspan="1" colspan="1" align="left">One of <code nobreak="false">public</code>, <code nobreak="false">private</code>, or
                              <code nobreak="false">final</code>. The default is <code nobreak="false">private</code>.</td><td valign="top" rowspan="1" colspan="1" align="left">See <specref ref="visibility"/>. If the mode is unnamed, that is, if the
                                 <code nobreak="false">name</code> attribute is absent, then the
                                 <code nobreak="false">visibility</code> attribute if present
                                 <rfc2119>must</rfc2119> have the value
                              <code nobreak="false">private</code>.<phrase diff="del" at="2022-11-25"> A named mode is not
                              eligible to be used as the <termref def="dt-initial-mode"/> if its
                              visibility is <code nobreak="false">private</code>.</phrase>
                           <ednote><edtext>See issue 270.</edtext></ednote></td></tr></tbody></table><imp-def-feature id="idf-err-warningonmatch">The default values for the
                     <code nobreak="false">warning-on-no-match</code> and <code nobreak="false">warning-on-multiple-match</code>
                  attributes of <elcode>xsl:mode</elcode> are <termref def="dt-implementation-defined"/>.</imp-def-feature><imp-def-feature id="idf-err-matchmessages">The form of any warnings output when
                  there is no matching template rule, or when there are multiple matching template
                  rules, is <termref def="dt-implementation-defined"/>.</imp-def-feature><p>
                  <termdef id="dt-streamable-mode" term="streamable mode">A <term>streamable
                        mode</term> is a <termref def="dt-mode">mode</termref> that is declared in
                     an <elcode>xsl:mode</elcode> declaration with the attribute
                        <code nobreak="false">streamable="yes"</code>.</termdef>
               </p><p>For any named <termref def="dt-mode">mode</termref>, the <termref def="dt-effective-value"/> of each
                  attribute is taken from an <elcode>xsl:mode</elcode> declaration that has a
                  matching name in its <code nobreak="false">name</code> attribute, and that specifies an explicit
                  value for the required attribute. If there is
                     no such declaration, the default value of the attribute is used. If
                  there is more than one such declaration, the one with highest <termref def="dt-import-precedence">import precedence</termref> is used.</p><p>For the <termref def="dt-unnamed-mode">unnamed mode</termref>, the <termref def="dt-effective-value"/>
                  of each attribute is taken from an <elcode>xsl:mode</elcode> declaration that has
                  no <code nobreak="false">name</code> attribute, and that specifies an explicit value for the
                  required attribute. If there is no such declaration, the default value of the
                  attribute is used. If there is more than one such declaration, the one with
                  highest <termref def="dt-import-precedence">import precedence</termref> is
                  used.</p><p>
                  <error spec="XT" type="static" class="SE" code="0545"><p>It is a <termref def="dt-static-error">static error</termref> if for any
                        named or unnamed <termref def="dt-mode">mode</termref>, a package explicitly specifies two conflicting
                        values for the same attribute in different <elcode>xsl:mode</elcode>
                        declarations having the same <termref def="dt-import-precedence">import
                           precedence</termref>, unless there is another definition of the same
                        attribute with higher import precedence. The attributes in question are the
                        attributes other than <code nobreak="false">name</code> on the <elcode>xsl:mode</elcode>
                           element.</p></error>
               </p></div3><div3 id="using-modes"><head>Using Modes</head><p><termdef id="dt-applicable" term="applicable">A <termref def="dt-template-rule">template rule</termref> is <term>applicable</term> to one or more modes.
                     The modes to which it is applicable are defined by the <code nobreak="false">mode</code>
                     attribute of the <elcode>xsl:template</elcode> element. If the attribute is
                     omitted, then the template rule is applicable to the <termref def="dt-default-mode"/> 
                  specified in the <code nobreak="false">[xsl:]default-mode</code> attribute of the innermost containing
                           element that has such an attribute, which in turn defaults to
                        the <termref def="dt-unnamed-mode">unnamed mode</termref>. If the
                        <code nobreak="false">mode</code> attribute is present, then its value
                        <rfc2119>must</rfc2119> be a non-empty whitespace-separated list of tokens,
                     each of which defines a mode to which the template rule is
                     applicable.</termdef></p><p>Each token in the <code nobreak="false">mode</code> attribute <rfc2119>must</rfc2119> be one of
                  the following:</p><ulist><item><p>An <termref def="dt-eqname">EQName</termref>, which is expanded as described in <specref ref="qname"/> to define the name of the mode</p></item><item><p>The token <code nobreak="false">#default</code>, to indicate that the template rule is
                        applicable to the <termref def="dt-default-mode"/> that would apply if
                           the <code nobreak="false">mode</code> attribute were absent
                     </p></item><item><p>The token <code nobreak="false">#unnamed</code>, to indicate that the
                        template rule is applicable to the <termref def="dt-unnamed-mode">unnamed
                           mode</termref>
                     </p></item><item><p>The token <code nobreak="false">#all</code>, to indicate that the template rule is
                        applicable to all modes <phrase diff="chg" at="2022-01-01">other than <termref def="dt-enclosing-mode">enclosing modes</termref></phrase>
                        (specifically, to the unnamed mode and to every mode that is named explicitly or implicitly in an
                           <elcode>xsl:apply-templates</elcode> instruction  anywhere in
                        the stylesheet).</p><p diff="chg" at="2022-01-01">More specifically, when a template rule specifies <code nobreak="false">mode="#all"</code> this makes the
                        template rule <termref def="dt-applicable"/> to:</p><ulist><item><p>The unnamed mode.</p></item><item><p>Every mode, other than an <termref def="dt-enclosing-mode"/>, that is declared using an
                              <elcode>xsl:mode</elcode> declaration within the containing <termref def="dt-package"/>.</p></item><item><p>Every mode that is implicitly declared within the containing <termref def="dt-package"/>
                              by virtue of being referenced in an <elcode>xsl:template</elcode> or
                           <elcode>xsl:apply-templates</elcode> element.</p></item></ulist><p>The value <code nobreak="false">mode="#all"</code>
                        cannot be used on a template rule declared within an
                        <elcode>xsl:override</elcode> <phrase diff="add" at="2022-01-01">or <elcode>xsl:mode</elcode></phrase> element.</p></item></ulist><p/><p>
                  <error spec="XT" type="static" class="SE" code="0550"><p>It is a <termref def="dt-static-error">static error</termref> if the list of
                        modes <error.extra>in the <code nobreak="false">mode</code> attribute of
                              <elcode>xsl:template</elcode>
                        </error.extra> is empty, if the same token is included more than once in the
                        list, if the list contains an invalid token, or if the token
                           <code nobreak="false">#all</code> appears together with any other value.</p></error>
               </p><p>
                  <error spec="XT" type="static" class="SE" code="3440"><p>In the case of a <termref def="dt-template-rule"/> (that is, an
                           <elcode>xsl:template</elcode> element having a <code nobreak="false">match</code>
                        attribute) appearing as a child of <elcode>xsl:override</elcode>, it is a
                           <termref def="dt-static-error">static error</termref> if the list of
                        modes in the <code nobreak="false">mode</code> attribute contains <code nobreak="false">#all</code> or
                           <code nobreak="false">#unnamed</code>, or if it contains <code nobreak="false">#default</code> and the
                        <termref def="dt-default-mode"/> is the <termref def="dt-unnamed-mode"/>, or if the
                           <code nobreak="false">mode</code> attribute is omitted when the default mode is the
                           <termref def="dt-unnamed-mode"/>.</p></error>
               </p><p>The <elcode>xsl:apply-templates</elcode> element also has an optional
                     <code nobreak="false">mode</code> attribute. The value of this attribute
                     <rfc2119>must</rfc2119> be one of the following:</p><ulist><item><p>an <termref def="dt-eqname">EQName</termref>, which is expanded as described in <specref ref="qname"/> to define the name of a mode</p></item><item><p>the token <code nobreak="false">#default</code>, to indicate that the <termref def="dt-default-mode"/> 
                        from the static context of the instruction is to be used</p></item><item><p>the token <code nobreak="false">#unnamed</code>, to indicate that the
                           <termref def="dt-unnamed-mode">unnamed mode</termref> is to be used</p></item><item><p>the token <code nobreak="false">#current</code>, to indicate that the <termref def="dt-current-mode">current mode</termref> is to be used</p></item></ulist><p>If the attribute is omitted, the <termref def="dt-default-mode"/> from
                        the static context of the instruction is used.</p><p>When searching for a template rule to process each item selected by the <elcode>xsl:apply-templates</elcode>
                  instruction, only those template rules that are applicable to the selected mode
                  are considered.</p><p>
                  <termdef id="dt-current-mode" term="current mode">At any point in the processing
                     of a stylesheet, there is a <term>current mode</term>. When the transformation
                     is initiated, the current mode is the <termref def="dt-initial-mode"/>, as described in <specref ref="initiating"/>. Whenever an <elcode>xsl:apply-templates</elcode>
                     instruction is evaluated, the current mode becomes the mode selected by this
                     instruction.</termdef> When a <termref def="dt-non-contextual-function-call"/> is made, the current mode
                  is set to the <termref def="dt-unnamed-mode">unnamed mode</termref>. While
                  evaluating global variables and parameters, and the sequence constructor contained
                  in <elcode>xsl:key</elcode> or <elcode>xsl:sort</elcode>, the current mode is set
                  to the unnamed mode. No other instruction changes the current mode. The current
                  mode while evaluating an <termref def="dt-attribute-set">attribute set</termref>
                  is the same as the current mode of the caller. On completion of the
                     <elcode>xsl:apply-templates</elcode> instruction, or on return from a
                  stylesheet function call, the current mode reverts to its previous value. The
                  current mode is used when an <elcode>xsl:apply-templates</elcode> instruction uses
                  the syntax <code nobreak="false">mode="#current"</code>; it is also used by the
                     <elcode>xsl:apply-imports</elcode> and <elcode>xsl:next-match</elcode>
                  instructions (see <specref ref="apply-imports"/>).</p></div3><div3 id="apply-templates-function"><head>The <code nobreak="false">apply-templates</code> Function</head><changes><change issue="2005 2038" PR="2006" date="2025-05-16">A new function <code nobreak="false">fn:apply-templates</code> is introduced.</change></changes><p>Sometimes it is useful to be able to apply templates from within an XPath expression.
               A common example is when using XPath expressions to construct maps and arrays. For example,
               an array of maps might be constructed by the following code:</p><eg xml:space="preserve">
&lt;xsl:array for-each select="*"&gt;
      &lt;xsl:map&gt;
        &lt;xsl:for-each select="@*"&gt;
          &lt;xsl:map-entry key="local-name()"&gt;
            &lt;xsl:apply-templates select="."/&gt;
          &lt;/xsl:map-entry&gt;
        &lt;/xsl:for-each&gt;
      &lt;/xsl:map&gt;
&lt;/xsl:array&gt;</eg><p>Such code can become verbose, and it is difficult to read because the XML form of the instructions
                  bears literal relationship to the serialized form (typically JSON) of the result.
                  XSLT 4.0 offers the alternative of writing it like this:</p><eg xml:space="preserve">
&lt;xsl:select&gt;
   array{ * ! map:build(@*, local-name#1, apply-templates#1) }
&lt;/xsl:select&gt;</eg><note><p>Explanation: this constructs an array with one member for each element child <var>E</var> of
                  the context node. The member is a map constructed using the <function>map:build</function> function.
                  The map has one entry for each attribute <var>A</var> of element <var>E</var>. The
                  key of this entry is the local name of the attribute, and the corresponding value is
                  obtained by applying templates to the attribute node.</p></note><p>To make this possible, a subset of the functionality of the <elcode>xsl:apply-templates</elcode>
               instruction is available via the (XSLT-only) <function>apply-templates</function>
               function, whose specification follows.</p><div4 id="func-apply-templates"><head>fn:apply-templates</head><changes><change issue="2005" PR="2006" date="2025-05-20">New in 4.0</change></changes><glist><gitem><label>Summary</label><def><p>Applies template rules to selected items.</p></def></gitem><gitem><label>Signature</label><def><example role="signature"><proto isOp="no" prefix="fn" name="apply-templates" return-type="item()*" returnEmptyOk="no" returnSeq="no" returnVaries="no" isSchema="no" isDatatype="no" isSpecial="no"><arg name="select" type="item()*"/><arg name="options" type="map(*)?" default="{}"/></proto></example></def></gitem><gitem><label>Properties</label><def><p>This function is <xtermref spec="FO40" ref="dt-deterministic">deterministic</xtermref>, <xtermref spec="FO40" ref="dt-context-dependent">context-dependent</xtermref>,  and <xtermref spec="FO40" ref="dt-focus-independent">focus-independent</xtermref>. </p></def></gitem><gitem><label>Rules</label><def><p>The function call <code nobreak="false">apply-templates(<var>X</var>)</code>, used within an XPath 
            <termref def="dt-expression">expression</termref>, returns 
            the same result as the instruction <code nobreak="false">&lt;xsl:apply-templates select="<var>X</var>"/&gt;</code></p><p>The entries that may appear in the <code nobreak="false">$options</code> map are as follows.
         The <xtermref spec="FO40" ref="option-parameter-conventions"/> apply.</p><example role="record"><record returnEmptyOk="no" returnSeq="no" prefix="fn" returnVaries="no" isSchema="no" isDatatype="no" isSpecial="no" isOp="no"><arg name="params" type="map(xs:QName, item()*)" occur="opt"/><arg name="tunnel-params" type="map(xs:QName, item()*)" occur="opt"/><arg name="mode" type="(xs:QName | enum(&#34;#current&#34;, &#34;#unnamed&#34;))" occur="opt"/></record></example><table class="fos-options" border="1" cellpadding="5" width="100%"><thead><tr><th rowspan="1" colspan="1" align="left" valign="top">Key</th><th rowspan="1" colspan="1" align="left" valign="top">Value</th><th rowspan="1" colspan="1" align="left" valign="top">Meaning</th></tr></thead><tbody><tr><td rowspan="1" colspan="1" align="left" valign="top"><p><code nobreak="false">params?</code></p></td><td class="fos-thin" colspan="2" rowspan="1" align="left" valign="top">Supplies values for non-tunnel parameters. Each entry in the <code nobreak="false">params</code>
               map binds a parameter (identified by an <code nobreak="false">xs:QName</code> value) to a supplied value.
               <ulist><item><p><term>Type: </term><code nobreak="false">map(xs:QName, item()*)</code></p></item><item><p><term>Default: </term><code nobreak="false">{}</code></p></item></ulist></td></tr><tr><td rowspan="1" colspan="1" align="left" valign="top"><p><code nobreak="false">tunnel-params?</code></p></td><td class="fos-thin" colspan="2" rowspan="1" align="left" valign="top">Supplies values for tunnel parameters. Each entry in the <code nobreak="false">tunnel-params</code>
               map binds a tunnel parameter (identified by an <code nobreak="false">xs:QName</code> value) to a supplied value.<ulist><item><p><term>Type: </term><code nobreak="false">map(xs:QName, item()*)</code></p></item><item><p><term>Default: </term><code nobreak="false">{}</code></p></item></ulist></td></tr><tr><td rowspan="4" colspan="1" align="left" valign="top"><p><code nobreak="false">mode?</code></p></td><td class="fos-thick" colspan="2" rowspan="1" align="left" valign="top">Selects the mode to be used. The value may be set to an <code nobreak="false">xs:QName</code>
               that matches a declared mode in the stylesheet, or to one of the special values
               <code nobreak="false">#current</code> or <code nobreak="false">#unnamed</code>.<ulist><item><p><term>Type: </term><code nobreak="false">(xs:QName | enum("#current", "#unnamed"))</code></p></item><item><p><term>Default: </term><code nobreak="false">"#unnamed"</code></p></item></ulist></td></tr><tr><td class="fos-thin" rowspan="1" colspan="1" align="left" valign="top"><code nobreak="false">xs:QName</code></td><td rowspan="1" colspan="1" align="left" valign="top">Selects a declared mode by name.</td></tr><tr><td class="fos-thin" rowspan="1" colspan="1" align="left" valign="top"><code nobreak="false">#current</code></td><td rowspan="1" colspan="1" align="left" valign="top">Selects the <termref def="dt-current-mode"/>.</td></tr><tr><td class="fos-thick" rowspan="1" colspan="1" align="left" valign="top"><code nobreak="false">#unnamed</code></td><td rowspan="1" colspan="1" align="left" valign="top">Selects the <termref def="dt-unnamed-mode"/>.</td></tr></tbody></table><p>For each item in the value of the <code nobreak="false">$select</code> argument, the function finds
         the best matching template rule in the selected mode and invokes that template rule with the supplied
         parameters (if any). The result of
         the function is the sequence concatenation of the results of performing this process for each
         item in the selected input, in turn.</p></def></gitem><gitem><label>Error Conditions</label><def><p>Errors may arise in the same situations as for the <elcode>xsl:apply-templates</elcode>
         instruction: for example, if the <elcode>xsl:mode</elcode> declaration specifies 
         <code nobreak="false">on-no-match="fail"</code> and no matching template rule is found.</p><p><error spec="XT" type="dynamic" class="DE" code="0565"><p>It is a <termref def="dt-dynamic-error">dynamic error</termref> if a call
                        on the <function>apply-templates</function> function selects a <termref def="dt-mode"/>
                        that is not explicitly declared in the containing package, or accepted
                        from a used package, or whose visibility is <code nobreak="false">private</code>.</p></error>
         </p><note><p>Modes are private by default: for a mode to be available for reference by
         the <function>apply-templates</function> function, it must be explicitly declared
         with <code nobreak="false">visibility="public"</code>.</p></note></def></gitem><gitem><label>Notes</label><def><note><p>Unlike the <elcode>xsl:apply-templates</elcode> instruction, the name of the required mode, and the
            names of the supplied parameters, can be evaluated dynamically.</p><p>If no mode is specified, the function uses the unnamed mode. It does not use the default mode
          (as defined by a containing <code nobreak="false">[xsl:]default-mode</code> attribute). This decision was made
         in order to avoid having to retain the default mode for each XPath expression at evaluation time,
         and to avoid complex rules for edge cases involving dynamic function calls.</p><p>See also the rules in <specref ref="dynamic-component-references"/>, which are relevant
         to resolution of the mode name.</p></note></def></gitem><gitem><label>Examples</label><def role="example"><table role="medium" border="1" cellpadding="5" width="100%"><tbody><tr><td colspan="2" rowspan="1" align="left" valign="top"><p>The function call:</p></td></tr><tr><td colspan="2" rowspan="1" align="left" valign="top"><eg xml:space="preserve"><code nobreak="false">apply-templates(*, {'mode': '#current', 'params': { #expand : false() } })</code></eg></td></tr><tr><td colspan="2" rowspan="1" align="left" valign="top"><p>has the same effect as the instruction:</p></td></tr><tr><td colspan="2" rowspan="1" align="left" valign="top"><eg xml:space="preserve">&lt;xsl:apply-templates 
        select="*"
        mode="#current"&gt;
    &lt;xsl:with-param name="expand" select="false()"/&gt;
&lt;/xsl:apply-templates&gt;</eg></td></tr></tbody></table></def></gitem></glist></div4></div3><div3 id="xsl-mode-typed"><head>Declaring the Type of Values Processed by a Mode</head><changes><change issue="2337" PR="2736" date="2026-01-09">
                     <p>The <code nobreak="false">xsl:mode/@typed</code> attribute has been clarified and expanded
                  to provide better control over the handling of items other than XNodes.</p></change></changes><p>Typically the template rules in a particular <termref def="dt-mode"/> will be
                  designed to process a specific kind of input document. The <code nobreak="false">typed</code>
                  attribute of <elcode>xsl:mode</elcode> gives the stylesheet author the opportunity
                  to provide information about this document to the processor. This information may
                  enable the processor to improve diagnostics or to optimize performance.</p><p>The allowed values of the attribute are as follows:</p><ulist><item><p><code nobreak="false">yes</code>, <code nobreak="false">true</code>, <code nobreak="false">1</code>: the items processed
                  by this mode must be XNodes, and they must not have a type annotation
                  of <code nobreak="false">xs:untyped</code> or <code nobreak="false">xs:untypedAtomic</code>.</p></item><item><p><code nobreak="false">no</code>, <code nobreak="false">false</code>, <code nobreak="false">0</code>: the items processed
                  by this mode must be XNodes, and if they are elements or attributes then they must have a type annotation
                  of <code nobreak="false">xs:untyped</code> or <code nobreak="false">xs:untypedAtomic</code>.</p></item><item><p>The value <code nobreak="false">strict</code> is equivalent to <code nobreak="false">yes</code>, with the
                        additional provision that in the match pattern of any template rule that is
                           <termref def="dt-applicable"/> to this mode, any <code nobreak="false">NameTest</code>
                        used in the <code nobreak="false">ForwardStepP</code> of the first <code nobreak="false">StepExprP</code> of
                        a <code nobreak="false">RelativePathExprP</code> is interpreted as follows:</p><ulist><item><p>If the <code nobreak="false">NameTest</code> is an <code nobreak="false">EQName</code>
                              <var>E</var>, and the principal node kind of the axis of this step is
                                 <code nobreak="false">Element</code>, then:</p><ulist><item><p>It is a static error if the in-scope schema declarations do
                                       not include a global element declaration for element name
                                          <var>E</var>
                                    </p></item><item><p>When matching templates in this mode, the element name
                                          <var>E</var> appearing in this step is interpreted as
                                          <code nobreak="false">schema-element(E)</code>. (Informally, this means
                                       that it will only match an element if it has been validated
                                       against this element declaration). </p></item></ulist></item><item><p>Otherwise (the <code nobreak="false">NameTest</code> is a wildcard or the principal
                              node kind is <code nobreak="false">Attribute</code> or <code nobreak="false">Namespace</code>), the
                              template matching proceeds as if the <code nobreak="false">typed</code> attribute were
                              absent. </p></item></ulist></item><item><p>The value <code nobreak="false">lax</code> is equivalent to <code nobreak="false">yes</code>, with the
                        additional provision that in the match pattern of any template rule that is
                           <termref def="dt-applicable"/> to this mode, any <code nobreak="false">NameTest</code>
                        used in the <code nobreak="false">ForwardStepP</code> of the first <code nobreak="false">StepExprP</code> of
                        a <code nobreak="false">RelativePathExprP</code> is interpreted as follows:</p><ulist><item><p>If the <code nobreak="false">NameTest</code> is an <code nobreak="false">EQName</code>
                              <var>E</var>, and the principal node kind of the axis of this step is
                                 <code nobreak="false">Element</code>, and the in-scope schema declarations include
                              a global element declaration for element name <var>E</var>, then:</p><ulist><item><p>When matching templates in this mode, the element name
                                          <var>E</var> appearing in this step is interpreted as
                                          <code nobreak="false">schema-element(E)</code>. (Informally, this means
                                       that it will only match an element if it has been validated
                                       against this element declaration). </p></item></ulist></item><item><p>Otherwise (the <code nobreak="false">NameTest</code> is a wildcard, or the principal
                              node kind is <code nobreak="false">Attribute</code> or <code nobreak="false">Namespace</code>, or
                              there is no element declaration for <var>E</var>), the template
                              matching proceeds as if the <code nobreak="false">typed</code> attribute were absent.
                           </p></item></ulist></item><item><p>If the value is <code nobreak="false">~</code> followed by an <xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="XP40" ref="ItemType" xlink:type="simple"/>,
                     for example <code nobreak="false">~xs:anyAtomicType</code> or <code nobreak="false">~jnode()</code> or <code nobreak="false">~map(*)</code>, this indicates
                     that all items to be processed using template rules in this mode must be
                     of the specified item type.</p></item><item><p>If the value is the string <code nobreak="false">"unspecified"</code>, or if it is omitted,
                     this is equivalent to specifying <code nobreak="false">~item()</code>, indicating that there
                     are no constraints.</p></item></ulist><p>
                  <error spec="XT" type="type" class="TE" code="3100"><p>It is a <termref def="dt-type-error">type error</termref> if an
                           <elcode>xsl:apply-templates</elcode> instruction in a particular
                           <code nobreak="false">mode</code> selects an item that does not satisfy the constraints
                        imposed by the <code nobreak="false">@typed</code> attribute.</p></error>
               </p><p>
                  <error spec="XT" type="static" class="SE" code="3105"><p>It is a <termref def="dt-static-error">static error</termref> if a template
                        rule applicable to a mode that is defined with <code nobreak="false">typed="strict"</code>
                        uses a match pattern that contains a <code nobreak="false">RelativePathExprP</code> whose
                        first <code nobreak="false">StepExprP</code> is an <code nobreak="false">AxisStepP</code> whose
                           <code nobreak="false">ForwardStepP</code> uses an axis whose principal node kind is
                           <code nobreak="false">Element</code> and whose <code nobreak="false">NodeTest</code> is an
                           <code nobreak="false">EQName</code> that does not correspond to the name of any global
                        element declaration in the <termref def="dt-in-scope-schema-component">in-scope schema components</termref>.</p></error>
               </p></div3><div3 id="mode-result-type" diff="chg" at="2023-10-16"><head>Declaring the Result Type of a Mode</head><changes><change issue="233 750 1382" PR="751 1386" date="2023-10-18">
                     The result type of a mode can be declared using an <code nobreak="false">as</code> attribute. The result type
                  of all template rules in this mode must be consistent with this, as must the values returned
                  by any built-in template rules for the mode.
                  </change></changes><p>Traditionally, template rules have most commonly been used to construct XDM nodes, and the <elcode>xsl:apply-templates</elcode>
               instruction has been used to add nodes to a result tree. However, it is also possible to use template rules to produce
               other kinds of value, for example strings, booleans, or maps. For the <elcode>xsl:apply-templates</elcode> 
               instruction to be useful, it will generally be the case that all template rules in a mode produce the same kind
               of value: for example, if one rule delivers a boolean, then the other rules will also deliver a boolean.</p><p>XSLT 4.0 therefore allows the result type of the template rules in a mode to be declared using the <code nobreak="false">as</code>
               attribute on the <elcode>xsl:mode</elcode> declaration. If this is absent, it defaults to <code nobreak="false">item()*</code>.
               The presence of an <code nobreak="false">as</code> attribute on a mode provides useful documentation and consistency checking,
               and enables the XSLT processor to infer a static type for an <elcode>xsl:apply-templates</elcode> instruction,
               which can be useful for optimization.</p><p>If a template rule <var>R</var> is <termref def="dt-applicable"/> to a mode <var>M</var>, 
                  and <var>M</var> is declared with an <code nobreak="false">as</code> attribute whose value is the <code nobreak="false">SequenceType</code> 
                  <var>T</var>, then:</p><ulist><item><p>If <var>R</var> has an <code nobreak="false">as</code> attribute, the <code nobreak="false">SequenceType</code> <var>S</var> declared
                     by <var>R</var> must be a subtype of <var>T</var>.</p><p><error spec="XT" type="static" class="SE" code="4040"><p>It is a <termref def="dt-static-error">static error</termref> if a <termref def="dt-template-rule"/>
                        <var>R</var> has an <code nobreak="false">as</code> attribute <var>S</var>, 
                        and the template rule is <termref def="dt-applicable"/>
                        to a <termref def="dt-mode"/> <var>M</var> that is declared with an <code nobreak="false">as</code> attribute <var>T</var>,
                        and the sequence type <var>S</var> is not a subtype of the sequence type <var>T</var> as defined
                     by the relationship <code nobreak="false">subtype(S, T)</code> in <xspecref spec="XP40" ref="id-seqtype-subtype"/>.</p></error></p></item><item><p>If <var>R</var> has no <code nobreak="false">as</code> attribute, then it is treated as if it had an <code nobreak="false">as</code>
                     attribute set to <var>T</var>. This means that a <termref def="dt-type-error"/> 
                     <errorref spec="XT" class="TE" code="0505"/> is raised
                     if the result of the template rule cannot be coerced to a value of type <var>T</var>.</p><p>If <var>R</var> is applicable
                     to more than one mode, then it must meet the requirements of each one, which implies that these requirements
                     must be consistent with each other: for example, if one mode specifies <code nobreak="false">as="node()"</code> and another specifies
                        <code nobreak="false">as="map(*)"</code>, then a type error is inevitable if the template rule is actually evaluated, and
                        like other type errors this can be raised statically if detected statically. An
                     <xtermref spec="XP40" ref="dt-implausible">implausibility</xtermref> <rfc2119>may</rfc2119> 
                        be reported if the only value that would satisfy both types is the empty sequence, map, or array.</p><note><p>In practice the best way to satisfy this rule is to ensure 
                     that if a template rule is applicable to more than one mode (including
                  the case <code nobreak="false">mode="#all"</code>), then either (a) all those modes should have the same declared result type,
                  or (b) the template rule should declare an explicit result type that is compatible with each one of the relevant modes.</p></note></item><item><p>The requirement to return values of the correct type extends also to the built-in
                     template rule for the mode (see <specref ref="built-in-rule"/>). Since it is not possible to
                     determine statically whether the explicit template rules for a mode provide complete coverage
                     of all possible inputs, any failure of the built-in template rule to return a value 
                     that can be coerced to the expected type <rfc2119>must</rfc2119> be raised 
                     dynamically <errorref spec="XT" class="TE" code="0505"/>.</p></item></ulist></div3><div3 id="enclosing-modes" diff="add" at="2022-01-01"><head>Enclosing Modes</head><changes><change issue="82" PR="542" date="2023-06-20">
                     A mode (called an enclosing mode) can be defined in which all the relevant 
                     template rules are children of the <code nobreak="false">xsl:mode</code> element.
                     This is intended to allow a stylesheet design in which it is easier to
                     determine which rules might apply to a given <elcode>xsl:apply-templates</elcode>
                     call.
                  </change></changes><p><termdef id="dt-enclosing-mode" term="enclosing mode">A mode declared by
                  an <elcode>xsl:mode</elcode> declaration that has one or more contained <elcode>xsl:template</elcode>
                  declarations is referred to as an <term>enclosing mode</term>.</termdef></p><p>An enclosing mode ensures that all the template rules for a mode are together in one place, which
               makes it easier for someone reading the stylesheet to establish what is going to happen when an
               <elcode>xsl:apply-templates</elcode> instruction in that mode is evaluated.</p><p>An enclosing mode <rfc2119>must</rfc2119> satisfy the following rules:</p><olist><item><p>The mode must have a name.</p></item><item><p>Every contained <elcode>xsl:template</elcode> element must have a <code nobreak="false">match</code>
                  attribute and no <code nobreak="false">name</code> attribute.</p></item><item><p>Every contained <elcode>xsl:template</elcode> element must have no <code nobreak="false">mode</code>
                  attribute: the template is implicitly <termref def="dt-applicable"/> only to the containing mode.</p></item><item><p>An <elcode>xsl:mode</elcode> declaration with one or more <elcode>xsl:template</elcode>
                  children effectively has a <code nobreak="false">default-mode</code> attribute whose value is the mode’s name;
                     it must not have a <code nobreak="false">default-mode</code> attribute with any other value.</p><note><p>This means that <elcode>xsl:apply-templates</elcode> instructions within the template
                  rules of the enclosing mode default to using the enclosing mode.</p></note></item><item><p>No <elcode>xsl:template</elcode> that is in the same <phrase diff="chg" at="2022-11-01"><termref def="dt-package"/></phrase>
                     as the containing mode, but not declared within the containing mode, may be <termref def="dt-applicable"/>
                  to the containing mode.</p><note><p>Template rules in an enclosing mode may, however, be overridden within an 
                     <elcode>xsl:override</elcode> element in a using <termref def="dt-package"/>.</p></note></item><item><p>There must be no other <elcode>xsl:mode</elcode> declaration in the containing <termref def="dt-package"/>
                  having the same name and the same <termref def="dt-import-precedence"/>.</p></item></olist><p>These rules give rise to the following error conditions:</p><p><error spec="XT" type="static" class="SE" code="4005"><p>It is a <termref def="dt-static-error">static error</termref> if an <elcode>xsl:mode</elcode>
                     declaration with one or more <elcode>xsl:template</elcode> children has no <code nobreak="false">name</code>
                     attribute.</p></error></p><p><error spec="XT" type="static" class="SE" code="4010"><p>It is a <termref def="dt-static-error">static error</termref> if an <elcode>xsl:mode</elcode>
                     declaration has a child <elcode>xsl:template</elcode> element with a <code nobreak="false">name</code> attribute,
                     with a <code nobreak="false">mode</code> attribute, or with no <code nobreak="false">match</code> attribute.</p></error></p><p><error spec="XT" type="static" class="SE" code="4015"><p>It is a <termref def="dt-static-error">static error</termref> if an <elcode>xsl:mode</elcode>
                     declaration having one or more child <elcode>xsl:template</elcode> elements has a <code nobreak="false">default-mode</code>
                     attribute whose value differs from its <code nobreak="false">name</code> attribute, or if any of those child <elcode>xsl:template</elcode> 
                     elements has a <code nobreak="false">default-mode</code> attribute that differs from the <code nobreak="false">name</code> attribute
                     of the <elcode>xsl:mode</elcode> declaration.</p></error></p><p><error spec="XT" type="static" class="SE" code="4020"><p>It is a <termref def="dt-static-error">static error</termref> if a
                     <termref def="dt-package"/> contains both (a) an <elcode>xsl:mode</elcode>
                     declaration having one or more child <elcode>xsl:template</elcode> elements, and (b) 
                     an <elcode>xsl:template</elcode> declaration that is not
                     one of those children but that references that <elcode>xsl:mode</elcode> declaration in its
                     <code nobreak="false">mode</code> attribute.</p></error></p><p><error spec="XT" type="static" class="SE" code="4025"><p>It is a <termref def="dt-static-error">static error</termref> if a
                     <termref def="dt-package"/> contains (a) an <elcode>xsl:mode</elcode>
                     declaration having one or more child <elcode>xsl:template</elcode> elements, and (b) 
                     a second <elcode>xsl:mode</elcode> declaration having the same name and the same
                     <termref def="dt-import-precedence"/>.</p></error></p><example><head>An Enclosing Mode</head><p>The following mode might be used for formatting of numbers appearing in text:</p><eg role="xslt-declaration" xml:space="preserve">
&lt;xsl:mode name="numbers-in-text" as="xs:string" visibility="final"&gt;
  &lt;xsl:template match="type(xs:integer)[. gt 0 and . lt 21]"&gt;
    &lt;xsl:number value="." format="w"/&gt;
  &lt;/xsl:template&gt;
  &lt;xsl:template match="type(xs:integer)[. lt 10000]"&gt;
    &lt;xsl:number value="." format="1"/&gt;
  &lt;/xsl:template&gt;
  &lt;xsl:template match="type(xs:integer)"&gt;
    &lt;xsl:number value="." format="1" grouping-separator="," grouping-size="3"/&gt;
  &lt;/xsl:template&gt;  
&lt;/xsl:mode&gt;
                     </eg></example></div3></div2><div2 id="built-in-rule"><head>Built-in Template Rules</head><changes><change issue="570" PR="718" date="2023-09-26">
                  To allow recursive-descent transformation on a tree of maps and arrays, a new
                  set of built-in templates rules <code nobreak="false">shallow-copy-all</code> is introduced.
               </change></changes><p>When an item is
               selected by <elcode>xsl:apply-templates</elcode> and there is no user-specified
                  <termref def="dt-template-rule">template rule</termref> in the <termref def="dt-stylesheet">stylesheet</termref> that can be used to process that item, then a built-in template rule is
               evaluated instead. </p><p>The built-in <termref def="dt-template-rule">template rules</termref> have lower
                  <termref def="dt-import-precedence">import precedence</termref> than all other
               template rules. Thus, the stylesheet author can override a built-in template rule by
               including an explicit template rule.</p><p>There are <phrase diff="chg" at="issue570">seven</phrase> sets of built-in template rules available. The set
               that is chosen is a property of the <termref def="dt-mode">mode</termref> selected by
               the <elcode>xsl:apply-templates</elcode> instruction. This property is set using the
                  <code nobreak="false">on-no-match</code> attribute of the <elcode>xsl:mode</elcode> declaration,
               which takes one of the values <code nobreak="false">deep-copy</code>, <code nobreak="false">shallow-copy</code>,
               <phrase diff="add" at="issue570"><code nobreak="false">shallow-copy-all</code>,</phrase>
                  <code nobreak="false">deep-skip</code>, <code nobreak="false">shallow-skip</code>, 
               <code nobreak="false">text-only-copy</code>, or
                  <code nobreak="false">fail</code>, the default being <code nobreak="false">text-only-copy</code>. The effect of
               these <phrase diff="chg" at="issue570">seven</phrase> sets of built-in template rules is explained in the following
               subsections.</p><div3 id="built-in-templates-text-only-copy"><head>Built-in Templates: Text-only Copy</head><p>The effect of processing a
                     tree using a <termref def="dt-mode">mode</termref> that specifies
                        <code nobreak="false">on-no-match="text-only-copy"</code> is that the textual
                  content of the source document is retained while losing the markup, except where
                  explicit template rules dictate otherwise. When an element is encountered for
                  which there is no explicit <termref def="dt-template-rule">template
                  rule</termref>, the processing continues with the children of that element. Text
                  nodes are copied to the output.</p><p>The built-in rule for document nodes and element nodes is equivalent to calling
                     <elcode>xsl:apply-templates</elcode> with no <code nobreak="false">select</code> attribute, and
                  with the <code nobreak="false">mode</code> attribute set to <code nobreak="false">#current</code>. If the built-in
                  rule was invoked with parameters, those parameters are passed on in the implicit
                     <elcode>xsl:apply-templates</elcode> instruction.</p><p>This is equivalent to the following in the case where
                  there are no parameters:</p><eg role="xslt-declaration" xml:space="preserve">&lt;xsl:template match="document-node()|element()" mode="M"&gt;
  &lt;xsl:apply-templates mode="#current"/&gt;
&lt;/xsl:template&gt;</eg><p>The built-in <termref def="dt-template-rule">template
                     rule</termref> for text and attribute nodes returns a text node containing the
                     <termref def="dt-string-value">string value</termref> of the context node. It
                  is effectively:</p><eg xml:space="preserve" role="xslt-declaration">&lt;xsl:template match="text()|@*" mode="M"&gt;
  &lt;xsl:value-of select="string(.)"/&gt;
&lt;/xsl:template&gt;</eg><note><p>This text node may have a string value that is zero-length.</p></note><p>The built-in <termref def="dt-template-rule">template
                     rule</termref> for atomic items returns a
                  text node containing the value. It is effectively:</p><eg xml:space="preserve" role="xslt-declaration">&lt;xsl:template match=".[. instance of xs:anyAtomicType]" mode="M"&gt;
  &lt;xsl:value-of select="string(.)"/&gt;
&lt;/xsl:template&gt;</eg><note><p>This text node may have a string value that is zero-length.</p></note><p>The built-in <termref def="dt-template-rule">template
                     rule</termref> for processing instructions, comments, and namespace nodes does
                  nothing (it returns the empty sequence).</p><eg xml:space="preserve" role="xslt-declaration">&lt;xsl:template 
   match="processing-instruction()|comment()|namespace-node()" 
   mode="M"/&gt;</eg><p>The built-in <termref def="dt-template-rule">template
                     rule</termref> for functions (including
                     maps) does nothing (it returns the empty sequence).</p><eg xml:space="preserve" role="xslt-declaration">&lt;xsl:template 
   match=".[. instance of fn(*)]" 
   mode="M"/&gt;</eg><p>The built-in <termref def="dt-template-rule"/> for
               arrays (see <specref ref="arrays"/>) is to apply templates to the members of the array.
               It is equivalent to invoking <elcode>xsl:apply-templates</elcode> with the <code nobreak="false">select</code>
               attribute set to <code nobreak="false">?*</code> (which selects the members of the array), and with the 
                  <code nobreak="false">mode</code> attribute set to <code nobreak="false">#current</code>. If the built-in
                  rule was invoked with parameters, those parameters are passed on in the implicit
                  <elcode>xsl:apply-templates</elcode> instruction.</p><p>This is equivalent to the following in the case where
                  there are no parameters:</p><eg role="xslt-declaration" xml:space="preserve">&lt;xsl:template match=".[. instance of array(*)]" mode="M"&gt;
  &lt;xsl:apply-templates mode="#current" select="?*"/&gt;
&lt;/xsl:template&gt;</eg><p>The following example illustrates the use of built-in template rules when there
                  are parameters.</p><example><head>Using a Built-In Template Rule</head><p>Suppose the stylesheet contains the following instruction:</p><eg xml:space="preserve" role="xslt-instruction">&lt;xsl:apply-templates select="title" mode="M"&gt;
  &lt;xsl:with-param name="init" select="10"/&gt;
&lt;/xsl:apply-templates&gt;</eg><p>If there is no explicit template rule that matches the <code nobreak="false">title</code>
                     element, then the following implicit rule is used:</p><eg xml:space="preserve" role="xslt-declaration">&lt;xsl:template match="title" mode="M"&gt;
  &lt;xsl:param name="init"/&gt;
  &lt;xsl:apply-templates mode="#current"&gt;
    &lt;xsl:with-param name="init" select="$init"/&gt;
  &lt;/xsl:apply-templates&gt;
&lt;/xsl:template&gt;</eg></example></div3><div3 id="built-in-templates-deep-copy"><head>Built-in Templates: Deep Copy</head><p>The effect of processing a tree using a
                        <termref def="dt-mode">mode</termref> that specifies
                        <code nobreak="false">on-no-match="deep-copy"</code> is that an unmatched element
                  in the source tree is copied unchanged to the output, together with its entire
                  subtree. Other unmatched items are also copied unchanged. The subtree is copied
                  unconditionally, without attempting to match nodes in the subtree against template
                  rules.</p><p>When this default action is selected for a mode <var>M</var>, all items (nodes, atomic items, and functions, including maps and arrays) are processed
                  using a template rule that is equivalent to the following:</p><eg xml:space="preserve" role="xslt-declaration">&lt;xsl:template match="." mode="M"&gt;
  &lt;xsl:copy-of select="." validation="preserve" copy-namespaces="CN"/&gt;
&lt;/xsl:template&gt;</eg><p>where <var>CN</var> is the value of the <code nobreak="false">copy-namespaces</code> attribute of the relevant
               <elcode>xsl:mode</elcode> declaration, defaulting to <code nobreak="false">yes</code>.</p></div3><div3 id="built-in-templates-shallow-copy"><head>Built-in Templates: Shallow Copy</head><p>The effect of processing a tree using a
                        <termref def="dt-mode">mode</termref> that specifies
                        <code nobreak="false">on-no-match="shallow-copy"</code> is that the source tree is
                  copied unchanged to the output, except for nodes where different processing is
                  specified using an explicit <termref def="dt-template-rule">template
                     rule</termref>.</p><p>When this default action is selected for a mode <var>M</var>, all items (nodes, atomic items, and functions, including maps and arrays) are processed
                  using a template rule that is equivalent to the following, except that all
                  parameters supplied in <elcode>xsl:with-param</elcode> elements are passed on
                  implicitly to the called templates:</p><eg xml:space="preserve" role="xslt-declaration">&lt;xsl:template match="." mode="M"&gt;
  &lt;xsl:copy validation="preserve" copy-namespaces="CN"&gt;
    &lt;xsl:apply-templates select="@*" mode="M"/&gt;
    &lt;xsl:apply-templates select="node()" mode="M"/&gt;
  &lt;/xsl:copy&gt;
&lt;/xsl:template&gt;</eg><p>where <var>CN</var> is the value of the <code nobreak="false">copy-namespaces</code> attribute of the relevant
               <elcode>xsl:mode</elcode> declaration, defaulting to <code nobreak="false">yes</code>.</p><p>This rule is often referred to as the <emph>identity template</emph>, though it
                  should be noted that it does not preserve node identity.</p><note><p>This rule differs from the traditional identity template rule by using two
                        <elcode>xsl:apply-templates</elcode> instructions, one to process the
                     attributes and one to process the children. The only observable difference from
                     the traditional <code nobreak="false">select="node() | @*"</code> is that with two separate
                     instructions, the value of <code nobreak="false">position()</code> in the called templates
                     forms one sequence starting at 1 for the attributes, and a new sequence
                     starting at 1 for the children.</p></note><example><head>Modified Identity Transformation</head><p>The following stylesheet transforms an input document by deleting all elements
                     named <code nobreak="false">note</code>, together with their attributes and descendants:</p><eg xml:space="preserve" role="xslt-document">&lt;xsl:stylesheet version="3.0"
     xmlns:xsl="http://www.w3.org/1999/XSL/Transform"&gt;
				  
&lt;xsl:mode on-no-match="shallow-copy" streamable="true"/&gt;

&lt;xsl:template match="note"&gt;
  &lt;!-- no action --&gt;
&lt;/xsl:template&gt;

&lt;/xsl:stylesheet&gt;</eg></example></div3><div3 id="built-in-templates-shallow-copy-all" diff="add" at="issue570"><head>Built-in Templates: Shallow Copy All</head><p>This processing mode is introduced in XSLT 4.0 as a variant of <code nobreak="false">shallow-copy</code>
               to enable recursive descent processing of trees involving maps and arrays, such as might result
               from parsing JSON input.
               </p><p>For all items other than maps and arrays, the effect of <code nobreak="false">shallow-copy-all</code>
               is exactly the same as <code nobreak="false">shallow-copy</code>.</p><p>For arrays, the processing is as follows. A new result array is created, and its content
                  is populated by decomposing the input array to a sequence of <term>value records</term>
               using the function <function>array:members</function>. Each of these value records is processed
                  by a call on <elcode>xsl:apply-templates</elcode> (using the current mode, and passing
                  on the values of all template parameters); the result of the called template
                  is expected to be a value record.</p><p>That is, the template rule is equivalent to the following, except that this does not show
                  the propagation of template parameters:</p><eg xml:space="preserve">&lt;xsl:array use="?value"&gt;
  &lt;xsl:apply-templates select="array:members(.)" mode="#current"/&gt;
&lt;/xsl:array&gt;  
    </eg><ednote><edtext>TODO: the use attribute is no more. Example need reworking.</edtext></ednote><note><p>A <term>value record</term> is a single-entry map: it has a single key-value pair with the key <code nobreak="false">"value"</code>,
               the corresponding value being a member of the original array. The default processing for a value
               record, unless specified otherwise, is to apply templates to the value, as indicated by the rules
               that follow.</p></note><p>For maps, the processing is as follows:</p><ulist><item><p>If the map contains two or more entries,
                     then a new result map is created, and its content is populated
                     by decomposing the input map using the function <function>map:entries</function> to 
                     produce a sequence of single-entry maps (each containing one key and one value), and then applying
                     templates to this sequence, using the current mode, and passing
                     on the values of all template parameters.</p></item><item><p>If the map contains a single entry <code nobreak="false">{ <var>K</var> : <var>V/0</var> }</code>, then a new single entry
                     map <code nobreak="false">{ <var>K</var>: <var>V/1</var> }</code> is constructed in which <var>V/1</var> is the
                     result of applying templates to <var>V/0</var> (using the current mode, and passing
                     on the values of all template parameters).</p><note><p>This rule has the effect that if the input is a value record, the output will also
                     be a value record.</p></note></item><item><p>If the map is empty, the result is the empty map.</p></item></ulist><p>In the first case, the template rule is equivalent to the following, except that this does not show
                  the propagation of template parameters:</p><eg xml:space="preserve">&lt;xsl:map&gt;
  &lt;xsl:apply-templates select="map:entries(.)" mode="#current"/&gt;
&lt;/xsl:map&gt;</eg><p>In the second case, the template rule is equivalent to the following, except that this does not show
                  the propagation of template parameters:</p><eg xml:space="preserve">&lt;xsl:map-entry key="map:keys(.)"&gt;
  &lt;xsl:apply-templates select="map:items(.)" mode="#current"/&gt;
&lt;/xsl:map-entry&gt;</eg><p>The reason there is a special rule for maps with one entry is to ensure that the process
               terminates.</p><p>The overall effect is best understood with an example.</p><example><head>Modified Identity Transformation of a JSON Document</head><p>The following stylesheet transforms a supplied JSON document by deleting all properties
                     named <code nobreak="false">"Note"</code>, appearing at any level:</p><eg xml:space="preserve" role="xslt-document">&lt;xsl:stylesheet version="3.0"
     xmlns:xsl="http://www.w3.org/1999/XSL/Transform"&gt;
				  
&lt;xsl:mode on-no-match="shallow-copy-all"/&gt;

&lt;xsl:template match="record(Note)"&gt;
  &lt;!-- no action --&gt;
&lt;/xsl:template&gt;

&lt;/xsl:stylesheet&gt;</eg><p>Consider the following JSON input, converted to an array of maps by calling 
                     the function <function>parse-json</function>:</p><eg xml:space="preserve">[
  { "Title": "Computer Architecture",
    "Authors": [ "Enid Blyton", { "Note": "possibly misattributed" } ],
    "Category": "Computers",
    "Price": 42.60
  },
  { "Title": "Steppenwolf",
    "Authors": [ "Hermann Hesse" ],
    "Category": "Fiction",
    "Price": 12.00,
    "Note": "out of print"
  },
  { "Title": "How to Explore Outer Space with Binoculars",
    "Authors": [ "Bruce Betts", "Erica Colon" ],
    "Category": "Science",
    "Price": 10.40
  }
]</eg><p>The logic proceeds as follows:</p><olist><item><p>The outermost array is processed by applying templates to a sequence of value records, 
                        the first being in the form:</p><eg xml:space="preserve">{ "value": map: { "Title": ..., "Author": ..., ... }</eg><p>The result of applying templates to these value records is expected to comprise a new sequence
                        of value records, which is used to construct the final output array.</p></item><item><p>Each of the value records is processed using the rule for single-entry maps. This rule
                        produces a new value record by applying templates to the value, that is, to a map of the form
                        <code nobreak="false">map: { "Title": ..., "Author": ..., ... }</code> representing a book.</p></item><item><p>Each of these books, being represented by a map with more than two entries, is processed by
                     a template rule that splits the map into its multiple entries, each represented as a singleton
                     map (a map with one key and one value). One of these single-entry maps, for example, would be
                     <code nobreak="false">{"Title": "Steppenwolf"}</code>.</p></item><item><p>The default processing for a single-entry map of the form 
                        <code nobreak="false">{ "Title": "Steppenwolf" }</code> is to return the value unchanged.
                        This is achieved by applying templates to the string <code nobreak="false">"Steppenwolf"</code>;
                     the default template rule for strings returns the string unchanged.</p></item><item><p>When a single-entry map in the form <code nobreak="false">{ "Note": "out of print" }</code> is encountered, no output
                     is produced, meaning that entry in the parent map is effectively dropped. This is because there
                     is an explicit template rule with <code nobreak="false">match="record(Note)"</code> that matches such single-entry maps.</p></item><item><p>When a single-entry map in the form <code nobreak="false">"Authors": [ "Bruce Betts", "Erica Colon" ]</code> 
                        is encountered, a new single-entry map is produced; it has the same key (<code nobreak="false">"Authors"</code>),
                        and a value obtained by applying templates to the array <code nobreak="false">[ "Bruce Betts", "Erica Colon" ]</code>.
                        The default processing for an array, in which none of the constituents are matched by explicit
                        template rules, ends up delivering a copy of the array.</p></item><item><p>When the single-entry map <code nobreak="false">"Authors": [ "Enid Blyton", { "Note": "possibly misattributed" } ]</code>
                        is encountered, the recursive processing results in templates being applied to the map
                        <code nobreak="false">{ "Note": "possibly misattributed" }</code>. This matches the template rule having
                        <code nobreak="false">match="record(Note)"</code>, which returns no output, so the entry is effectively deleted.</p><note><p>The map entry is deleted, but the map itself remains, so the value becomes
                           <code nobreak="false">"Authors": [ "Enid Blyton", map: {} ]</code>.</p></note></item></olist></example></div3><div3 id="built-in-templates-deep-skip"><head>Built-in Templates: Deep Skip</head><p>The effect of processing a tree using a <termref def="dt-mode">mode</termref> that specifies
                     <code nobreak="false">on-no-match="deep-skip"</code> is that where no explicit template rule is
                  specified for an element, that element and all its descendants are ignored, and
                  are not copied to the result tree.</p><p>The effect of choosing <code nobreak="false">on-no-match="deep-skip"</code> is as follows:</p><ulist><item><p>The built-in rule for document nodes is equivalent to calling
                           <elcode>xsl:apply-templates</elcode> with no <code nobreak="false">select</code>
                        attribute, and with the <code nobreak="false">mode</code> attribute set to
                           <code nobreak="false">#current</code>. If the built-in rule was invoked with parameters,
                        those parameters are passed on in the implicit
                           <elcode>xsl:apply-templates</elcode> instruction.</p><p>In the case where there are no parameters, this
                        is equivalent to the following rule:</p><eg xml:space="preserve" role="xslt-declaration">&lt;xsl:template match="document-node()" mode="M"&gt;
  &lt;xsl:apply-templates mode="#current"/&gt;
&lt;/xsl:template&gt;</eg></item><item><p>The built-in rule for all items other than document nodes (that is, for all 
                        other kinds of node, as well as atomic
                           items and functions, including
                              maps and  and arrays) is to do nothing, that is, to return the empty
                        sequence (without applying templates to any children or ancestors).</p><p>This is equivalent to the following rule:</p><eg role="xslt-declaration" xml:space="preserve">&lt;xsl:template match="." mode="M"/&gt;</eg></item></ulist></div3><div3 id="built-in-templates-shallow-skip"><head>Built-in Templates: Shallow Skip</head><p>The effect of processing a tree using a
                        <termref def="dt-mode">mode</termref> that specifies
                        <code nobreak="false">on-no-match="shallow-skip"</code> is to drop both the textual
                  content and the markup from the result document, except where there is an explicit
                  user-written <termref def="dt-template-rule">template rule</termref> that dictates
                  otherwise.</p><p>The built-in rule for document nodes and element nodes  applies templates (in the current mode) first to the node’s
                     attributes and then to its children. If the built-in rule was invoked
                  with parameters, those parameters are passed on in the implicit
                     <elcode>xsl:apply-templates</elcode>
                  instructions.</p><p>In the case where there are no parameters, this is
                  equivalent to the following rule:</p><eg xml:space="preserve" role="xslt-declaration">&lt;xsl:template match="document-node()|element()" mode="M"&gt;
  &lt;xsl:apply-templates select="@*" mode="#current"/&gt;
  &lt;xsl:apply-templates mode="#current"/&gt;
&lt;/xsl:template&gt;</eg><p>The built-in template rule for all other kinds of node, and for atomic items and
                  functions (including maps, but not arrays) is empty:
                  that is, when the item is matched, the built-in template rule returns the empty
                  sequence.</p><p>This is equivalent to the following rule:</p><eg xml:space="preserve" role="xslt-declaration">&lt;xsl:template match="." mode="M"/&gt;</eg><p>The built-in <termref def="dt-template-rule"/> for
                  arrays (see <specref ref="arrays"/>) is to apply templates to the members of the array.
                  It is equivalent to invoking <elcode>xsl:apply-templates</elcode> with the <code nobreak="false">select</code>
                  attribute set to <code nobreak="false">?*</code> (which selects the members of the array), and with the 
                  <code nobreak="false">mode</code> attribute set to <code nobreak="false">#current</code>. If the built-in
                  rule was invoked with parameters, those parameters are passed on in the implicit
                  <elcode>xsl:apply-templates</elcode> instruction.</p><p>This is equivalent to the following in the case where
                  there are no parameters:</p><eg role="xslt-declaration" xml:space="preserve">&lt;xsl:template match=".[. instance of array(*)]" mode="M"&gt;
  &lt;xsl:apply-templates mode="#current" select="?*"/&gt;
&lt;/xsl:template&gt;</eg></div3><div3 id="built-in-templates-fail"><head>Built-in Templates: Fail</head><p>The effect of choosing <code nobreak="false">on-no-match="fail"</code> for a
                     <termref def="dt-mode">mode</termref> is that every item selected in an <elcode>xsl:apply-templates</elcode> instruction
                  must be matched by an explicit user-written <termref def="dt-template-rule">template rule</termref>.</p><p>The built-in template rule is effectively: </p><eg xml:space="preserve" role="xslt-declaration">&lt;xsl:template match="." mode="M"&gt;
  &lt;xsl:message terminate="yes" error-code="err:XTDE0555"/&gt;
&lt;/xsl:template&gt;</eg><p>with an <termref def="dt-implementation-dependent"/> message body.</p><p>
                  <error spec="XT" type="dynamic" class="DE" code="0555"><p>It is a <termref def="dt-dynamic-error"> dynamic error</termref> if
                           <elcode>xsl:apply-templates</elcode>, <elcode>xsl:apply-imports</elcode>
                        or <elcode>xsl:next-match</elcode> is used to process 
                        <phrase diff="chg" at="2022-01-01">an item</phrase> using a mode
                        whose declaration specifies <code nobreak="false">on-no-match="fail"</code> when there is no
                           <termref def="dt-template-rule"/> in the <termref def="dt-stylesheet"/>
                        whose match pattern matches that <phrase diff="chg" at="2022-01-01">item</phrase>. </p></error>
               </p></div3></div2><div2 id="apply-imports"><head>Overriding Template Rules</head><changes><change issue="1861" PR="1875" date="2025-03-25">
                  The <elcode>xsl:apply-imports</elcode> and <elcode>xsl:next-match</elcode> instructions automatically
                  pass supplied parameters to the overridden template rule.
               </change></changes><e:element-syntax xmlns:e="http://www.w3.org/1999/XSL/Spec/ElementSyntax" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" name="apply-imports">
      <e:in-category name="instruction"/>
      <e:element name="with-param" repeat="zero-or-more"/>
      <e:allowed-parents>
         <e:parent-category name="sequence-constructor"/>
      </e:allowed-parents>
   </e:element-syntax><e:element-syntax xmlns:e="http://www.w3.org/1999/XSL/Spec/ElementSyntax" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" name="next-match">
      <e:in-category name="instruction"/>
      <e:choice repeat="zero-or-more">
         <e:element name="with-param"/>
         <e:element name="fallback"/>
      </e:choice>
      <e:allowed-parents>
         <e:parent-category name="sequence-constructor"/>
      </e:allowed-parents>
   </e:element-syntax><p>A <termref def="dt-template-rule">template rule</termref> that is being used to
               override another template rule (see <specref ref="conflict"/>) can use the
                  <elcode>xsl:apply-imports</elcode> or <elcode>xsl:next-match</elcode> instruction
               to invoke the overridden template rule. The <elcode>xsl:apply-imports</elcode>
               instruction only considers template rules in imported stylesheet modules; the
                  <elcode>xsl:next-match</elcode> instruction considers all template rules that
               have not already been used. Both instructions will invoke the built-in template rule for the
                  context item (see <specref ref="built-in-rule"/>) if no other template rule is found.</p><p>
               <termdef id="dt-current-template-rule" term="current template rule">At any point in
                  the processing of a <termref def="dt-stylesheet">stylesheet</termref>, there may
                  be a <term>current template rule</term>. Whenever a <termref def="dt-template-rule">template rule</termref> is chosen as a result of
                  evaluating <elcode>xsl:apply-templates</elcode>,
                     <elcode>xsl:apply-imports</elcode>, or <elcode>xsl:next-match</elcode>, the
                  template rule becomes the current template rule for the evaluation of the rule’s
                  sequence constructor.</termdef>
             </p><p>
               The <termref def="dt-current-template-rule"/> is cleared (becomes <termref def="dt-absent"/>)
                  by any instruction that evaluates an operand with changed focus. It is therefore cleared
                  when evaluating <termref def="dt-instruction">instructions</termref> contained within:
            </p><ulist><item><p><elcode>xsl:for-each</elcode></p></item><item><p><elcode>xsl:for-each-group</elcode></p></item><item><p><elcode>xsl:analyze-string</elcode></p></item><item><p><elcode>xsl:iterate</elcode></p></item><item><p><elcode>xsl:source-document</elcode></p></item><item><p><elcode>xsl:merge</elcode></p></item><item><p><elcode>xsl:sort</elcode></p></item><item><p><elcode>xsl:key</elcode></p></item><item><p><elcode>xsl:copy</elcode> if and only if there is a <code nobreak="false">select</code> attribute</p></item><item><p>A global <elcode>xsl:variable</elcode> or <elcode>xsl:param</elcode></p></item><item><p><elcode>xsl:function</elcode></p></item><item><p><elcode>xsl:template</elcode> if and only if the called template specifies <code nobreak="false">&lt;xsl:context-item use="absent"/&gt;</code></p></item></ulist><note><p>The current template rule is not affected by invoking named attribute sets (see <specref ref="attribute-sets"/>), or named templates (see <specref ref="named-templates"/>) unless <code nobreak="false">&lt;xsl:context-item use="absent"/&gt;</code> is specified. 
                  While evaluating a <termref def="dt-global-variable">global variable</termref> or the default value of a <termref def="dt-stylesheet-parameter">stylesheet parameter</termref> (see <specref ref="global-variables"/>) the current template rule is <termref def="dt-absent"/>.</p></note><p>These rules ensure that when <elcode>xsl:apply-imports</elcode> or
                     <elcode>xsl:next-match</elcode> is called, the <termref def="dt-context-item">context item</termref> is the same as when the current template rule was
                     invoked.</p><p> Both <elcode>xsl:apply-imports</elcode> and <elcode>xsl:next-match</elcode> search
               for a <termref def="dt-template-rule">template rule</termref> that matches the
                  <termref def="dt-context-item">context
                  item</termref>, and that is applicable to the <termref def="dt-current-mode">current mode</termref> (see <specref ref="modes"/>). In
               choosing a template rule, they use the usual criteria such as the priority and
                  <termref def="dt-import-precedence">import precedence</termref> of the template
               rules, but they consider as candidates only a subset of the template rules in the
                  <termref def="dt-stylesheet">stylesheet</termref>. This subset differs between the
               two instructions:</p><ulist><item><p>The <elcode>xsl:apply-imports</elcode> instruction considers as candidates only
                     those template rules contained in <termref def="dt-stylesheet-level">stylesheet
                        levels</termref> that are descendants in the <termref def="dt-import-tree">import tree</termref> of the <termref def="dt-stylesheet-level">stylesheet
                        level</termref> that contains the <termref def="dt-current-template-rule">current template rule</termref>.</p><note><p>This is <emph>not</emph> the same as saying that the search considers all
                        template rules whose import precedence is lower than that of the current
                        template rule.</p></note><p><error spec="XT" type="static" class="SE" code="3460"><p>It is a <termref def="dt-static-error"/> if an
                              <elcode>xsl:apply-imports</elcode> element appears in a <termref def="dt-template-rule"/> declared within an
                              <elcode>xsl:override</elcode> element. (To invoke the template rule
                           that is being overridden, <elcode>xsl:next-match</elcode> should
                           therefore be used.)</p></error></p></item><item><p>The <elcode>xsl:next-match</elcode> instruction considers as candidates all
                     those template rules that come after the <termref def="dt-current-template-rule">current template rule</termref> in the
                     ordering of template rules implied by the conflict resolution rules given in
                        <specref ref="conflict"/>.</p><note><p>Because a template rule declared as a child of <elcode>xsl:override</elcode>
                        has higher precedence than any template rule declared in the used package
                        (see <specref ref="modes-and-packages"/>), the effect of
                           <elcode>xsl:next-match</elcode> within such a template rule is to
                        consider as candidates first any other template rules for the same mode within the
                        same <elcode>xsl:use-package</elcode> element (taking into account explicit and implicit
                        priority, and document order, in the usual way), and then all template rules in
                        the used package.</p></note></item></ulist><p diff="add" at="2023-03-29">If no matching template rule is found, both <elcode>xsl:apply-imports</elcode> and <elcode>xsl:next-match</elcode>
            cause the built-in template rule for the mode to be invoked.</p><p diff="add" at="2023-03-29">If multiple matching template rules with the same explicit or implicit priority are found, 
               both <elcode>xsl:apply-imports</elcode> and <elcode>xsl:next-match</elcode>
               respect the <code nobreak="false">on-multiple-match</code> and <code nobreak="false">warning-on-multiple-match</code> attributes of the 
               mode declaration.</p><note diff="add" at="2023-03-29"><p>If is entirely possible for <elcode>xsl:apply-templates</elcode> to identify a template
               rule unambiguously, and for <elcode>xsl:apply-imports</elcode> or <elcode>xsl:next-match</elcode> 
               then to fail because there is no unambiguous second-choice template rule.</p></note><p>If a matching template rule <var>R</var> is found, then the result
               of the <elcode>xsl:next-match</elcode> or <elcode>xsl:apply-imports</elcode> instruction is the 
               result of invoking <var>R</var>. The parameters that are passed to <var>R</var> are as follows:</p><ulist><item><p>All parameters explicitly set using <elcode>xsl:with-param</elcode>
                  child elements (see <specref ref="with-param"/>).</p></item><item><p>If the <termref def="dt-effective-version"/> of the <elcode>xsl:next-match</elcode> 
                     or <elcode>xsl:apply-imports</elcode> instruction is 4.0 or greater, then 
                     all non-tunnel parameters that were supplied in the invocation of the
                     current template rule, excluding any whose names match the names of
                     parameters appearing in child <elcode>xsl:with-param</elcode> elements.</p></item><item><p>All <termref def="dt-tunnel-parameter">tunnel parameters</termref> 
                     as described in <specref ref="tunnel-params"/>.</p></item></ulist><note><p>The implicit passing of non-tunnel parameters is new in XSLT 4.0, and happens only if
                  <code nobreak="false">[xsl:]version</code> is set to 4.0 (or greater) on the instruction, or on some ancestor element
                  in the stylesheet. There may be cases where this
               change introduces a backward incompatibility: specifically, if the invoked template rule declares a default
               value for an optional parameter, it will now take the implicitly passed value rather than the
               default value. The 3.0 behavior can be therefore be retained by setting <code nobreak="false">version="3.0"</code>
               on the <elcode>xsl:next-match</elcode> or <elcode>xsl:apply-imports</elcode> instruction.</p></note><p>The template rule <var>R</var> is evaluated with the same <termref def="dt-focus"/> 
               as the <elcode>xsl:next-match</elcode> 
               or <elcode>xsl:apply-imports</elcode> instruction. The <termref def="dt-current-template-rule"/>
               changes to be <var>R</var>. The <termref def="dt-current-mode"/> does not change. 
            </p><note><p>In the case where the current template rule <var>T</var> is 
               declared within an <elcode>xsl:override</elcode> element in a using package <var>P</var>, while 
               the selected rule <var>R</var> is declared within a different package <var>Q</var>, and where 
               the current mode is <var>M/P</var> (mode <var>M</var> in package <var>P</var>), the effect 
               is that the current mode for evaluation of <var>R</var> 
               remains <var>M/P</var> rather than reverting to its corresponding mode <var>M/Q</var> 
               (mode <var>M</var> in package <var>Q</var>). 
               If <var>R</var> contains an <elcode>xsl:apply-templates</elcode> instruction that uses
               <code nobreak="false">mode="#current"</code>, then the set of template rules considered by this instruction 
               will therefore include any overriding template rules declared in <var>P</var> as well as the original 
               rules declared in <var>Q</var>.
            </p></note><p>If no matching template rule is found that satisfies these criteria, the built-in
               template rule for the context item is used (see
                  <specref ref="built-in-rule"/>).</p><p>
               <error spec="XT" type="dynamic" class="DE" code="0560"><p>It is a <termref def="dt-dynamic-error"> dynamic error</termref> if
                        <elcode>xsl:apply-imports</elcode> or <elcode>xsl:next-match</elcode> is
                     evaluated when the <termref def="dt-current-template-rule">current template
                        rule</termref> is <termref def="dt-absent"/>.</p></error>
            </p><example><head>Using <elcode>xsl:apply-imports</elcode>
               </head><p>For example, suppose the stylesheet <code nobreak="false">doc.xsl</code> contains a <termref def="dt-template-rule">template rule</termref> for <code nobreak="false">example</code>
                  elements:</p><eg xml:space="preserve" role="xslt-declaration">&lt;xsl:template match="example"&gt;
  &lt;pre&gt;&lt;xsl:apply-templates/&gt;&lt;/pre&gt;
&lt;/xsl:template&gt;</eg><p>Another stylesheet could import <code nobreak="false">doc.xsl</code> and modify the treatment of
                     <code nobreak="false">example</code> elements as follows:</p><eg xml:space="preserve" role="xslt-declaration">&lt;xsl:import href="doc.xsl"/&gt;

&lt;xsl:template match="example"&gt;
  &lt;div style="border: solid red"&gt;
     &lt;xsl:apply-imports/&gt;
  &lt;/div&gt;
&lt;/xsl:template&gt;</eg><p>The combined effect would be to transform an <code nobreak="false">example</code> into an element
                  of the form:</p><eg xml:space="preserve" role="xml">&lt;div style="border: solid red"&gt;&lt;pre&gt;...&lt;/pre&gt;&lt;/div&gt;</eg></example><p>An <elcode>xsl:fallback</elcode> instruction appearing as a child of an
                  <elcode>xsl:next-match</elcode> instruction is ignored by an XSLT 2.0, 3.0, or 4.0 processor, 
               but can be used to define fallback
               behavior when the stylesheet is processed by an XSLT 1.0 processor with forwards
               compatible behavior.</p><example><head>Using <elcode>xsl:next-match</elcode></head><p>This example shows how an input element such as:</p><eg xml:space="preserve">&lt;phrase upper-case="true" italic="true" bold="false" underscore="true"&gt;Hannover&lt;/phrase&gt;</eg><p>might be transformed into:</p><eg xml:space="preserve">&lt;italic&gt;&lt;underscore&gt;HANNOVER&lt;/underscore&gt;&lt;/italic&gt;</eg><p>The following template rules achieve the required effect:</p><eg xml:space="preserve">
&lt;xsl:template match="phrase" priority="10"&gt;
  &lt;xsl:next-match&gt;
     &lt;xsl:with-param name="upper-case" select="xs:boolean(@upper-case)"/&gt;
  &lt;/xsl:next-match&gt;
&lt;/xsl:template&gt;  

&lt;xsl:template match="phrase[xs:boolean(@italic)]" priority="8"&gt;
  &lt;italic&gt;
    &lt;xsl:next-match/&gt;
  &lt;/italic&gt;
&lt;/xsl:template&gt;

&lt;xsl:template match="phrase[xs:boolean(@bold)]" priority="6"&gt;
  &lt;bold&gt;
    &lt;xsl:next-match/&gt;
  &lt;/bold&gt;
&lt;/xsl:template&gt;

&lt;xsl:template match="phrase[xs:boolean(@underscore)]" priority="4"&gt;
  &lt;underscore&gt;
    &lt;xsl:next-match/&gt;
  &lt;/underscore&gt;
&lt;/xsl:template&gt;

&lt;xsl:template match="phrase" priority="2"&gt;
  &lt;xsl:param name="upper-case" as="xs:boolean?"/&gt;
  &lt;xsl:if test="$upper-case" then="upper-case(.)" else="string(.)"/&gt;
&lt;/xsl:template&gt;

</eg><p>Note how the <code nobreak="false">$upper-case</code> parameter is passed implicitly through the chain of template rules.</p></example></div2><div2 id="parameters-to-template-rules"><head>Passing Parameters to Template Rules</head><p>A template rule may have parameters. The parameters are declared in the body of the
               template using <elcode>xsl:param</elcode> elements, as described in <specref ref="parameters"/>.</p><p>Values for these parameters may be supplied in the calling
                  <elcode>xsl:apply-templates</elcode>, <elcode>xsl:apply-imports</elcode>, or
                  <elcode>xsl:next-match</elcode> instruction by means of
                  <elcode>xsl:with-param</elcode> elements appearing as children of the calling
               instruction. The <termref def="dt-expanded-qname">expanded QName</termref>
               represented by the <code nobreak="false">name</code> attribute of the <elcode>xsl:with-param</elcode>
               element must match the <termref def="dt-expanded-qname">expanded QName</termref>
               represented by the <code nobreak="false">name</code> attribute of the corresponding
                  <elcode>xsl:param</elcode> element. </p><p>It is not an error for these instructions to supply a parameter that does not match
               any parameter declared in the template rule that is invoked; unneeded parameter
               values are simply ignored.</p><p>A parameter may be declared as a <termref def="dt-tunnel-parameter">tunnel
                  parameter</termref> by specifying <code nobreak="false">tunnel="yes"</code> in the
                  <elcode>xsl:param</elcode> declaration; in this case the caller must supply the
               value as a tunnel parameter by specifying <code nobreak="false">tunnel="yes"</code> in the
               corresponding <elcode>xsl:with-param</elcode> element. Tunnel parameters differ from
               ordinary template parameters in that they are passed transparently through multiple
               template invocations. They are fully described in <specref ref="tunnel-params"/>.</p></div2></div1><div1 id="repetition"><head>Repetition</head><p>XSLT offers two constructs for processing each <phrase diff="chg">entry in a collection</phrase>:
               <elcode>xsl:for-each</elcode> and <elcode>xsl:iterate</elcode>.</p><p diff="add" at="2022-01-01">Both instructions can be used to process the items in a sequence, the
         elements in an array, or the entries in a map. Arrays and maps are processed by reducing them
         to a sequence of items, so in what follows, the terms <term>item</term> and <term>sequence</term> 
         are used generically.</p><p>The main difference between the two constructs is that with
               <elcode>xsl:for-each</elcode>, the processing applied to each item in the sequence is
            independent of the processing applied to any other item; this means that the items may
            be processed in any order or in parallel, though the order of the output sequence is
            well defined and corresponds to the order of the input (sorted if so requested). By
            contrast, with <elcode>xsl:iterate</elcode>, the processing is explicitly sequential:
            while one item is being processed, values may be computed which are then available for
            use while the next item is being processed. This makes <elcode>xsl:iterate</elcode>
            suitable for tasks such as creating a running total over a sequence of financial
            transactions.</p><p>A further difference is that <elcode>xsl:for-each</elcode> permits
            sorting of the input sequence, while <elcode>xsl:iterate</elcode> does not.</p><div2 id="for-each"><head>The <code nobreak="false">xsl:for-each</code> instruction</head><changes><change date="2022-01-01">
                  The <elcode>xsl:for-each</elcode> and <elcode>xsl:apply-templates</elcode>
                  instructions acquire an attribute <code nobreak="false">separator</code> that can be
                  used to insert content between adjacent items. [This change was in the
                  editor's draft adopted as a baseline when the WG commenced work.]
               </change></changes><e:element-syntax xmlns:e="http://www.w3.org/1999/XSL/Spec/ElementSyntax" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" name="for-each">
      <e:in-category name="instruction"/>
      <e:attribute name="select" required="yes">
         <e:data-type name="expression"/>
      </e:attribute>
      <e:attribute name="separator">
         <e:attribute-value-template>
            <e:data-type name="string"/>
         </e:attribute-value-template>
      </e:attribute>
      <e:sequence>
         <e:element repeat="zero-or-more" name="sort"/>
         <e:model name="sequence-constructor"/>
      </e:sequence>
      <e:allowed-parents>
         <e:parent-category name="sequence-constructor"/>
      </e:allowed-parents>
   </e:element-syntax><p>The <elcode>xsl:for-each</elcode> instruction processes each  in a sequence of
               items, evaluating the <termref def="dt-sequence-constructor">sequence
                  constructor</termref> within the <elcode>xsl:for-each</elcode> instruction once
               for each item in that sequence.</p><p> The <code nobreak="false">select</code> attribute is <rfc2119>required</rfc2119>; it contains an
                  <termref def="dt-expression">expression</termref> which is evaluated to produce a
               sequence, called the input sequence. If there is an <elcode>xsl:sort</elcode> element
               present (see <specref ref="sorting"/>) the input sequence is sorted to produce a
               sorted sequence. Otherwise, the sorted sequence is the same as the input
               sequence.</p><p>The <elcode>xsl:for-each</elcode> instruction contains a <termref def="dt-sequence-constructor">sequence constructor</termref>. The <termref def="dt-sequence-constructor">sequence constructor</termref> is evaluated once for
               each item in the sorted sequence, with the <termref def="dt-focus">focus</termref>
               set as follows:</p><ulist><item><p>The <termref def="dt-context-item">context item</termref> is the item being
                     processed. 
                  </p></item><item><p>The <termref def="dt-context-position">context position</termref> is the
                     position of this item in the sorted sequence.</p></item><item><p>The <termref def="dt-context-size">context size</termref> is the size of the
                     sorted sequence (which is the same as the size of the input sequence).</p></item></ulist><p> For each item in the input sequence, evaluating the <termref def="dt-sequence-constructor">sequence constructor</termref> produces a sequence
               of items (see <specref ref="sequence-constructors"/>). These output sequences are
               concatenated; if item <var>Q</var> follows item <var>P</var> in the sorted sequence,
               then the result of evaluating the sequence constructor with <var>Q</var> as the
               context item is concatenated after the result of evaluating the sequence constructor
               with <var>P</var> as the context item. The result of the
                  <elcode>xsl:for-each</elcode> instruction is the concatenated sequence of
               items.</p><example><head>Using <elcode>xsl:for-each</elcode> to process a sequence</head><p>For example, given an XML document with this structure</p><eg xml:space="preserve" role="xml">&lt;customers&gt;
  &lt;customer&gt;
    &lt;name&gt;...&lt;/name&gt;
    &lt;order&gt;...&lt;/order&gt;
    &lt;order&gt;...&lt;/order&gt;
  &lt;/customer&gt;
  &lt;customer&gt;
    &lt;name&gt;...&lt;/name&gt;
    &lt;order&gt;...&lt;/order&gt;
    &lt;order&gt;...&lt;/order&gt;
  &lt;/customer&gt;
&lt;/customers&gt;</eg><p>the following would create an HTML document containing a table with a row for each
                     <code nobreak="false">customer</code> element</p><eg xml:space="preserve" role="xslt-declaration">&lt;xsl:template match="/"&gt;
  &lt;html&gt;
    &lt;head&gt;
      &lt;title&gt;Customers&lt;/title&gt;
    &lt;/head&gt;
    &lt;body&gt;
      &lt;table&gt;
	 &lt;tbody&gt;
	  &lt;xsl:for-each select="customers/customer"&gt;
	    &lt;tr&gt;
	      &lt;th&gt;
           &lt;xsl:apply-templates select="name"/&gt;
	      &lt;/th&gt;
	      &lt;xsl:for-each select="order"&gt;
           &lt;td&gt;
             &lt;xsl:apply-templates/&gt;
           &lt;/td&gt;
	      &lt;/xsl:for-each&gt;
	    &lt;/tr&gt;
	  &lt;/xsl:for-each&gt;
	&lt;/tbody&gt;
      &lt;/table&gt;
    &lt;/body&gt;
  &lt;/html&gt;
&lt;/xsl:template&gt;</eg></example><example diff="chg" at="2022-11-01"><head>Using <elcode>xsl:for-each</elcode> to process an array</head><p>Consider a JSON document of the form:</p><eg xml:space="preserve">[
  { "city": "London", "latitude": 51.5099, "longitude": -0.1181 },
  { "city": "Paris",  "latitude": 48.8647, "longitude": 2.3488 },
  { "city": "Berlin", "latitude": 52.5200, "longitude": 13.4049 }                  
]</eg><p>The following code processes this array to produce an XML representation of the same information. The
               cities are sorted by name:</p><eg xml:space="preserve">&lt;xsl:for-each select="json-doc('input.json')?*"&gt;
   &lt;xsl:sort select="?city"/&gt;
   &lt;city number="{position()}" 
         name="{?city}" 
         latitude="{?latitude}" 
         longitude="{?longitude}"/&gt;
&lt;/xsl:for-each&gt;</eg><p>In this example it is possible to use the expression <code nobreak="false">$array?*</code> to convert an array to a sequence.
               This works because the members of the array are all single items. In the more general case (a member
               of the array might be the empty sequence, corresponding to the JSON value <code nobreak="false">null</code>, or it
               might be a sequence containing several items), <phrase diff="chg" at="2023-04-04">the function <code nobreak="false">array:members</code> can be
               used to deliver the contents of the array as a sequence of <emph>value records</emph>. This is 
               illustrated in the next example.</phrase></p></example><example diff="chg" at="2022-11-01"><head>Using <elcode>xsl:for-each</elcode> to process an array containing nulls</head><p>Consider a JSON document of the form:</p><eg xml:space="preserve">[
   { "city": "London", "data": [12.3, 15.6, null, 18.2] },
   { "city": "Paris",  "data": [7.9, 19.1, 23.0, null] },
   { "city": "Berlin", "data": [5.6, null, 14.6, 9.5] }                  
]</eg><p>The requirement is to convert this to the following XML:</p><eg xml:space="preserve">&lt;cities&gt;
  &lt;city name="London" Q1="12.3" Q2="15.6" Q3="" Q4="18.2"/&gt;
  &lt;city name="Paris" Q1="7.9" Q2="19.1" Q3="23.0" Q4=""/&gt;
  &lt;city name="Berlin" Q1="5.6" Q2="" Q3="14.6" Q4="9.5"/&gt;
&lt;/cities&gt;</eg><p>The following code achieves this transformation:</p><eg xml:space="preserve">&lt;xsl:for-each select="json-doc('input.json')?*"&gt;
   &lt;city name="{?city}"&gt;
     &lt;xsl:for-each select="array:members(?data)"&gt;
       &lt;xsl:attribute name="Q{position()}" select="?value"/&gt;
     &lt;/xsl:for-each&gt;
   &lt;/city&gt;  
&lt;/xsl:for-each&gt;</eg><p>In this example the expression <code nobreak="false">$array?*</code> cannot be used on the inner arrays
                  because JSON nulls (which translate to the empty sequence in XDM) would be lost. Instead
                  the function <xfunction>array:members</xfunction> is used to create a sequence of
                  value records: a non-null entry is represented by a value such as <code nobreak="false">{ 'value': 12.3 }</code>,
                  while a null entry would be <code nobreak="false">{ 'value': () }</code>.</p></example><example diff="add" at="2022-11-01"><head>Using <elcode>xsl:for-each</elcode> to process a map</head><p>Consider a JSON document of the form:</p><eg xml:space="preserve">{
  "London": { "latitude": 51.5099, "longitude": -0.1181 },
  "Paris":  { "latitude": 48.8647, "longitude": 2.3488 },
  "Berlin": { "latitude": 52.5200, "longitude": 13.4049 }                  
}</eg><p>The following code processes this map to produce an XML representation of the same information. The
                  cities are sorted by name:</p><eg xml:space="preserve">&lt;xsl:for-each select="map:pairs(json-doc('input.json'))"&gt;
   &lt;xsl:sort select="?key"/&gt;
   &lt;city number="{position()}" 
         name="{?key}" 
         latitude="{?value?latitude}" 
         longitude="{?value?longitude}"/&gt;
&lt;/xsl:for-each&gt;</eg><p>In this example the map is decomposed to a sequence of key-value pairs, each represented as
               a map with two entries, <code nobreak="false">"key"</code> and <code nobreak="false">"value"</code>, which can be accessed using
               the lookup expressions <code nobreak="false">?key</code> and <code nobreak="false">?value</code>.</p></example><div3 id="for-each-separator" diff="add" at="2022-01-01"><head>The <code nobreak="false">separator</code> attribute</head><p>If the <code nobreak="false">separator</code> attribute is present, then its <termref def="dt-effective-value"/>
               is inserted, as a text node, into the output sequence, immediately after the results of processing each item in the sorted
               sequence other than the last.</p><p>For example, the following instruction:</p><eg xml:space="preserve">
&lt;xsl:for-each select="6, 3, 9" separator="|"&gt;
   &lt;xsl:sort select="."/&gt;
   &lt;xsl:sequence select="., . + 1"/&gt;
&lt;/xsl:for-each&gt;</eg><p>produces a sequence comprising, in order: the integer 3, the integer 4, a text node with string value <code nobreak="false">"|"</code>,
               the integer 6, the integer 7, another text node with string value <code nobreak="false">"|"</code>,
            the integer 9, and the integer 10.</p><p>The node identity of any text nodes that are inserted is <termref def="dt-implementation-dependent"/>. Specifically,
            it is not defined whether all the text nodes inserted in the course of one evaluation of the instruction are identical
            to each other, nor whether they are identical to the text nodes inserted in the course of another evaluation of this
            instruction, nor whether they are identical to any other parentless text nodes having the same string value.</p><p>If the separator is a zero-length string, then a zero-length text node is inserted into the sequence. (If the
            sequence is used for constructing the value of a node, then zero-length text nodes will be discarded: see
               <specref ref="constructing-simple-content"/> and <specref ref="constructing-complex-content"/>.)</p></div3></div2><div2 id="iterate"><head>The <code nobreak="false">xsl:iterate</code> Instruction</head><p>The <code nobreak="false">xsl:iterate</code> instruction processes the items in a sequence
            in order; unlike <code nobreak="false">xsl:for-each</code>, the result of processing one item can affect the way that
            subsequent items are processed.</p><e:element-syntax xmlns:e="http://www.w3.org/1999/XSL/Spec/ElementSyntax" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" name="iterate">
      <e:in-category name="instruction"/>
      <e:attribute name="select" required="yes">
         <e:data-type name="expression"/>
      </e:attribute>
      <e:sequence>
         <e:element repeat="zero-or-more" name="param"/>
         <e:element repeat="zero-or-one" name="on-completion"/>
         <e:model name="sequence-constructor"/>
      </e:sequence>
      <e:allowed-parents>
         <e:parent-category name="sequence-constructor"/>
      </e:allowed-parents>
   </e:element-syntax><e:element-syntax xmlns:e="http://www.w3.org/1999/XSL/Spec/ElementSyntax" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" name="next-iteration">
      <e:in-category name="instruction"/>
      <e:sequence>
         <e:element repeat="zero-or-more" name="with-param"/>
      </e:sequence>
      <e:allowed-parents>
         <e:parent-category name="sequence-constructor"/>
      </e:allowed-parents>
   </e:element-syntax><e:element-syntax xmlns:e="http://www.w3.org/1999/XSL/Spec/ElementSyntax" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" name="break">
      <e:in-category name="instruction"/>
      <e:attribute name="select" required="no">
         <e:data-type name="expression"/>
      </e:attribute>
      <e:model name="sequence-constructor"/>
      <e:allowed-parents>
         <e:parent-category name="sequence-constructor"/>
      </e:allowed-parents>
   </e:element-syntax><e:element-syntax xmlns:e="http://www.w3.org/1999/XSL/Spec/ElementSyntax" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" name="on-completion">
      <e:attribute name="select" required="no">
         <e:data-type name="expression"/>
      </e:attribute>
      <e:model name="sequence-constructor"/>
      <e:allowed-parents>
         <e:parent name="iterate"/>
      </e:allowed-parents>
   </e:element-syntax><example diff="add" at="2022-01-01"><head>Processing an array using <code nobreak="false">xsl:iterate</code></head><p>Consider the following JSON document representing transactions in a bank account:</p><eg xml:space="preserve">[
  { "date": "2008-09-01", credit: 12.00 },
  { "date": "2008-09-01", credit: 8.00 },
  { "date": "2008-09-02", debit: 2.00 },
  { "date": "2008-09-02", credit: 12.00 }
]</eg><p>The following code converts this to an XML representation that includes a running balance:</p><eg xml:space="preserve">&lt;xsl:iterate select="json-doc('account.json') =&gt; array:members()"&gt;
   &lt;xsl:param name="balance" as="xs:decimal" select="0"/&gt;               
   &lt;xsl:variable name="delta" select="?value?credit otherwise -?value?debit"/&gt;               
   &lt;entry date="{ ?value?date }"
          amount="{ $delta }"
          balance="{ $balance + $delta }"/&gt;
   &lt;xsl:next-iteration&gt;
      &lt;xsl:with-param name="balance" select="$balance + $delta"/&gt;
   &lt;/xsl:next-iteration&gt;   
&lt;/xsl:iterate&gt;</eg><p>Using <code nobreak="false">array:members()</code> in this way makes it possible to process any array, including one whose members
               are arbitrary sequences rather than single items. In this particular case, if it is known that the JSON array
               will not contain any <code nobreak="false">null</code> entries, or if any <code nobreak="false">null</code> entries are to be ignored,
                  it becomes possible to simplify the code as follows:</p><eg xml:space="preserve">&lt;xsl:iterate select="json-doc('account.json')?*"&gt;
   &lt;xsl:param name="balance" as="xs:decimal" select="0"/&gt;               
   &lt;xsl:variable name="delta" select="?credit otherwise -?debit"/&gt;               
   &lt;entry date="{ ?date }"
          amount="{ $delta }"
          balance="{ $balance + $delta }"/&gt;
   &lt;xsl:next-iteration&gt;
      &lt;xsl:with-param name="balance" select="$balance + $delta"/&gt;
   &lt;/xsl:next-iteration&gt;   
&lt;/xsl:iterate&gt;</eg></example><p>The <code nobreak="false">select</code> attribute contains an
                  <termref def="dt-expression">expression</termref> which is evaluated to produce a
               sequence, called the input sequence.</p><p>The <termref def="dt-sequence-constructor"/> contained in the
                  <elcode>xsl:iterate</elcode> instruction is evaluated once for each item in the
               input sequence, in order, or until the loop exits by evaluating an
                  <elcode>xsl:break</elcode> instruction, whichever is earlier. Within the <termref def="dt-sequence-constructor">sequence constructor</termref> that forms the body
               of the <elcode>xsl:iterate</elcode> instruction, the <termref def="dt-context-item">context item</termref> is set to each item from the value of the
                  <code nobreak="false">select</code> expression in turn; the <termref def="dt-context-position">context position</termref> reflects the position of this item in the input
               sequence, and the <termref def="dt-context-size">context size</termref> is the number
               of items in the input sequence (which may be greater than the number of iterations,
               if the loop exits prematurely using <elcode>xsl:break</elcode>).</p><note><p>If <elcode>xsl:iterate</elcode> is used in conjunction with
                     <elcode>xsl:source-document</elcode> to achieve streaming, calls on the function
                     <xfunction>last</xfunction> will be disallowed. </p></note><p>The <elcode>xsl:break</elcode> and
                  <elcode>xsl:on-completion</elcode> elements may have either a <code nobreak="false">select</code>
               attribute or a non-empty contained <termref def="dt-sequence-constructor"/> but not
               both. The effect of the element in both cases is obtained by evaluating the
                  <code nobreak="false">select</code> expression if present or the contained sequence constructor
               otherwise; if neither is present, the value is the empty sequence.</p><note><p>The <elcode>xsl:on-completion</elcode> element appears before other children
                  of <elcode>xsl:iterate</elcode>
                  to ensure that variables declared in the sequence constructor are not in scope
                  within <elcode>xsl:on-completion</elcode>, since such variables do not have a
                  defined value within <elcode>xsl:on-completion</elcode> especially in the case
                  where the value of the <code nobreak="false">select</code> attribute is the empty sequence.</p></note><p>The effect of <elcode>xsl:next-iteration</elcode> is to cause the iteration to
               continue by processing the next item in the input sequence, potentially with
               different values for the iteration parameters. The effect of
                  <elcode>xsl:break</elcode> is to cause the iteration to finish, whether or not all
               the items in the input sequence have been processed. In both cases the affected
               iteration is the one controlled by the innermost ancestor
                  <elcode>xsl:iterate</elcode> element.</p><p>The instructions <elcode>xsl:next-iteration</elcode> and <elcode>xsl:break</elcode>
               are allowed only as descendants of an <elcode>xsl:iterate</elcode> instruction, and
               only in a <termref def="dt-tail-position">tail position</termref> within the <termref def="dt-sequence-constructor">sequence constructor</termref> forming the body of
               the <elcode>xsl:iterate</elcode> instruction. </p><p>
               <termdef id="dt-tail-position" term="tail position" open="true">An <termref def="dt-instruction">instruction</termref>
                  <var>J</var> is in a <term>tail position</term> within a <termref def="dt-sequence-constructor">sequence constructor</termref>
                  <var>SC</var> if it satisfies one of the following conditions:</termdef></p><ulist><item><p><var>J</var> is the last instruction in <var>SC</var>, ignoring any
                        <elcode>xsl:fallback</elcode> instructions.</p></item><item><p><var>J</var> is in a <termref def="dt-tail-position">tail position</termref>
                     within the sequence constructor that forms the body of an
                        <elcode>xsl:if</elcode> instruction that is itself in a <termref def="dt-tail-position">tail position</termref> within <var>SC</var>.</p></item><item><p><var>J</var> is in a <termref def="dt-tail-position">tail position</termref>
                     within the sequence constructor that forms the body of an
                        <elcode>xsl:when</elcode> or <elcode>xsl:otherwise</elcode> branch of an
                        <elcode>xsl:choose</elcode> <phrase diff="add" at="issue920">or <elcode>xsl:switch</elcode></phrase> 
                     instruction that is itself in a <termref def="dt-tail-position">tail position</termref> within <var>SC</var>.</p></item><item><p><var>J</var> is in a <termref def="dt-tail-position">tail position</termref>
                     within the sequence constructor that forms the body of an
                        <elcode>xsl:try</elcode> instruction that is itself in a <termref def="dt-tail-position">tail position</termref> within <var>SC</var> (that
                     is, it is immediately followed by an <elcode>xsl:catch</elcode> element,
                     ignoring any <elcode>xsl:fallback</elcode> elements).</p></item><item><p><var>J</var> is in a <termref def="dt-tail-position">tail position</termref>
                     within the sequence constructor that forms the body of an
                        <elcode>xsl:catch</elcode> element within an <elcode>xsl:try</elcode>
                     instruction that is itself in a <termref def="dt-tail-position">tail
                        position</termref> within <var>SC</var>.</p></item></ulist><p role="closetermdef"/><p>
               <error spec="XT" type="static" class="SE" code="3120"><p>It is a <termref def="dt-static-error">static error</termref> if an
                        <elcode>xsl:break</elcode> or <elcode>xsl:next-iteration</elcode> element
                     appears other than in a <termref def="dt-tail-position">tail position</termref>
                     within the <termref def="dt-sequence-constructor">sequence
                        constructor</termref> forming the body of an <elcode>xsl:iterate</elcode>
                     instruction.</p></error>
            </p><p>
               <error spec="XT" type="static" class="SE" code="3125"><p>It is a <termref def="dt-static-error">static error</termref> if the
                        <code nobreak="false">select</code> attribute of <elcode>xsl:break</elcode> or
                        <elcode>xsl:on-completion</elcode> is present and the instruction has
                     children.</p></error>
            </p><p>
               <error spec="XT" type="static" class="SE" code="3130"><p>It is a <termref def="dt-static-error">static error</termref> if the
                        <code nobreak="false">name</code> attribute of an <elcode>xsl:with-param</elcode> child of
                     an <elcode>xsl:next-iteration</elcode> element does not match the
                        <code nobreak="false">name</code> attribute of an <elcode>xsl:param</elcode> child of the
                        innermost containing
                        <elcode>xsl:iterate</elcode> instruction.</p></error>
            </p><p>Parameter names in <elcode>xsl:with-param</elcode> must be unique: <errorref spec="XT" class="SE" code="0670"/>.</p><p>The result of the <elcode>xsl:iterate</elcode> instruction is the concatenation of
               the sequences that result from the repeated evaluation of the contained <termref def="dt-sequence-constructor">sequence constructor</termref>, followed by the
               sequence that results from evaluating the <elcode>xsl:break</elcode> or
                  <elcode>xsl:on-completion</elcode> element if any.</p><p>Any <elcode>xsl:param</elcode> element that appears as a child of
                  <elcode>xsl:iterate</elcode> declares a parameter whose value may vary from one
               iteration to the next. The initial value of the parameter is the value obtained
               according to the rules given in <specref ref="variable-values"/>. The dynamic context
               for evaluating the initial value of an <elcode>xsl:param</elcode> element is the same
               as the dynamic context for evaluating the <code nobreak="false">select</code> expression of the
                  <elcode>xsl:iterate</elcode> instruction (the context item is thus
                  <emph>not</emph> the first item in the input sequence).</p><p>On the first iteration a parameter always takes its initial value (which may depend
               on variables or other aspects of the dynamic context). Subsequently:</p><ulist><item><p>If an <elcode>xsl:next-iteration</elcode> instruction is evaluated, then
                     parameter values for processing the next item in the input sequence can be set
                     in the <elcode>xsl:with-param</elcode> children of that instruction; in the
                     absence of an <elcode>xsl:with-param</elcode> element that names a particular
                     parameter, that parameter will retain its value from the previous
                     iteration.</p></item><item><p>If an <elcode>xsl:break</elcode> instruction is evaluated, no further items in
                     the input sequence are processed.</p></item><item><p>If neither an <elcode>xsl:next-iteration</elcode> nor an
                        <elcode>xsl:break</elcode> instruction is evaluated, then the next item in
                     the input sequence is processed using parameter values that are unchanged from
                     the previous iteration.</p></item></ulist><p>The <elcode>xsl:next-iteration</elcode> instruction contributes nothing to the result
               sequence (technically, it returns the empty sequence). The instruction supplies
               parameter values for the next iteration, which are evaluated according to the rules
               given in <specref ref="with-param"/>; if there are no further items in the input
               sequence then it supplies parameter values for use while evaluating the body of the
                  <elcode>xsl:on-completion</elcode> element if any.</p><p>The <elcode>xsl:break</elcode> instruction indicates that the iteration should
               terminate without processing any remaining items from the input sequence. The <code nobreak="false">select</code> expression or  contained sequence
               constructor is evaluated using the same context item, position, and size as the
                  <elcode>xsl:break</elcode> instruction itself, and the result is appended to the
               result of the <elcode>xsl:iterate</elcode> instruction as a whole.</p><p>If neither an <elcode>xsl:next-iteration</elcode> nor an <elcode>xsl:break</elcode>
               instruction is evaluated, the next item in the input sequence is processed with
               parameter values unchanged from the previous iteration; if there are no further items
               in the input sequence, the iteration terminates.</p><p>The optional <elcode>xsl:on-completion</elcode> element (which is not technically an
                  <termref def="dt-instruction">instruction</termref> and is not technically part of
               the <termref def="dt-sequence-constructor"/>) is evaluated when the input sequence is
               exhausted. It is not evaluated if the evaluation is terminated using
                  <elcode>xsl:break</elcode>. During evaluation of its <code nobreak="false">select</code> expression or sequence constructor
               the context item, position, and size are <termref def="dt-absent">absent</termref>
               (that is, any reference to these values is an error). However, the values of the
               parameters to <elcode>xsl:iterate</elcode> are available, and take the values
               supplied by the <elcode>xsl:next-iteration</elcode> instruction evaluated while
               processing the last item in the sequence.</p><p>If the input sequence is empty, then the result of the
                  <elcode>xsl:iterate</elcode> instruction is the result of evaluating the <code nobreak="false">select</code> attribute or <termref def="dt-sequence-constructor">sequence constructor</termref> forming the body of
               the <elcode>xsl:on-completion</elcode> element, using the initial values of the
                  <elcode>xsl:param</elcode> elements. If there is no
                  <elcode>xsl:on-completion</elcode> element, the result is the empty sequence.</p><note><p>Conceptually, <elcode>xsl:iterate</elcode> behaves like a tail-recursive function.
                  The <elcode>xsl:next-iteration</elcode> instruction then represents the recursive
                  call, supplying the tail of the input sequence as an implicit parameter. There are
                  two main reasons for providing the <elcode>xsl:iterate</elcode> instruction. One
                  is that many XSLT users find writing recursive functions to be a difficult skill,
                  and this construct promises to be easier to learn. The other is that recursive
                  function calls are difficult for an optimizer to analyze. Because
                     <elcode>xsl:iterate</elcode> is more constrained than a general-purpose
                  head-tail recursive function, it should be more amenable to optimization. In
                  particular, when the instruction is used in conjunction with
                     <elcode>xsl:source-document</elcode>, it is designed to make it easy for the
                  implementation to use streaming techniques, processing the nodes in an input
                  document sequentially as they are read, without building the entire document tree
                  in memory.</p></note><note><p>One of the motivations for introducing the <elcode>xsl:iterate</elcode> instruction
               was to enable information to be retained while processing a streamed sequence of
               sibling nodes. For examples illustrating this, see <xspecref spec="SG40" ref="streaming-with-xsl-iterate"/>.</p></note></div2></div1><div1 id="conditionals"><head>Conditional Processing</head><p>There are several instructions in XSLT that support conditional processing:
               <elcode>xsl:if</elcode>, <elcode>xsl:choose</elcode><phrase diff="add" at="2022-01-01">, and <elcode>xsl:switch</elcode></phrase>. 
            The <elcode>xsl:if</elcode>
            instruction provides simple <phrase diff="chg" at="2022-11-01">if-then-else</phrase> conditionality; the <elcode>xsl:choose</elcode>
            instruction supports selection of one choice when there are several possibilities,
            <phrase diff="add" at="2022-01-01">and <elcode>xsl:switch</elcode> allows a branch to be selected based on the value of a given
         expression.</phrase></p><p>XSLT 3.0 also supports <elcode>xsl:try</elcode> and
               <elcode>xsl:catch</elcode> which define conditional processing to handle <termref def="dt-dynamic-error">dynamic errors</termref>.</p><note diff="add" at="2022-11-01"><p>XSLT offers a number of ways of expressing conditional logic.</p><p>XSLT 1.0 offered the <elcode>xsl:if</elcode> instruction for cases where output was to be produced only if a condition was true,
         with <elcode>xsl:choose</elcode> available for multi-way branches where different output was to be produced under different
         input conditions. In addition, of course, XSLT 1.0 also offered the option of rule-based processing using templates and match patterns.</p><p>XSLT 2.0 added the XPath conditional expression providing two-way branches for use at a finer-grained level where
            <elcode>xsl:choose</elcode> could be excessively verbose: it allowed constructs such as 
            <code nobreak="false">&lt;xsl:value-of select="if ($x) then 'red' else 'green'/&gt;</code> to be reduced from eight lines of code to one.</p><p>XSLT 4.0 introduces the <code nobreak="false">then</code> and <code nobreak="false">else</code> attributes for <elcode>xsl:if</elcode>,
            which are particularly useful in contexts such as the body of an <elcode>xsl:function</elcode> declaration where
            the alternative results are conveniently evaluated using XPath expressions rather than XSLT instructions:
            for example a recursive function might have as its body the instruction 
               <code nobreak="false">&lt;xsl:if test="empty($seq)" then="1" else="head($seq) * my:f(tail($seq))"/&gt;</code>.
            The <code nobreak="false">select</code> attribute of <elcode>xsl:when</elcode> and <elcode>xsl:otherwise</elcode>
               is introduced for similar reasons: XSLT instructions
            are most useful when contructing node trees, whereas XPath expressions are more convenient when computing
            atomic items. Again, the main contribution of these enhancements is to reduce visual clutter, making
            the code more concise and more easily readable.</p><p>The <elcode>xsl:switch</elcode> instruction is introduced in XSLT 4.0 as an alternative to <elcode>xsl:choose</elcode>
            for the common use case where the conditions test for multiple different values of some common expression. By avoiding
            repetition of the common expression whose value is being tested, the logic becomes self-explanatory both to the human reader
            of the code and to an optimizing compiler, making it easier to generate efficient branching code.</p></note><div2 id="xsl-if"><head>Conditional Processing with <elcode>xsl:if</elcode></head><changes><change issue="167" PR="237" date="2022-11-25">
                  The <elcode>xsl:if</elcode> instruction now allows <code nobreak="false">then</code> and <code nobreak="false">else</code>
                  attributes.
               </change></changes><e:element-syntax xmlns:e="http://www.w3.org/1999/XSL/Spec/ElementSyntax" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" name="if">
      <e:in-category name="instruction"/>
      <e:attribute name="test" required="yes">
         <e:data-type name="expression"/>
      </e:attribute>
      <e:attribute name="then" required="no">
         <e:data-type name="expression"/>
      </e:attribute>
      <e:attribute name="else" required="no" default="()">
         <e:data-type name="expression"/>
      </e:attribute>
      <e:model name="sequence-constructor"/>
      <e:allowed-parents>
         <e:parent-category name="sequence-constructor"/>
      </e:allowed-parents>
   </e:element-syntax><p>The <elcode>xsl:if</elcode> element has a mandatory <code nobreak="false">test</code> attribute,
               whose value is an <termref def="dt-expression">expression</termref>. The content is
               a <termref def="dt-sequence-constructor"/>.</p><p diff="add" at="2022-01-01">If the <elcode>xsl:if</elcode> element has a <code nobreak="false">then</code> attribute, then it
               <rfc2119>must</rfc2119> have no children. That is, the <code nobreak="false">then</code> attribute and the
               contained sequence constructor are mutually exclusive.</p><p>The result of the <elcode>xsl:if</elcode> instruction depends on the <xtermref spec="XP40" ref="dt-ebv">effective boolean value</xtermref> of the expression in
               the <code nobreak="false">test</code> attribute. The rules for determining the effective boolean
               value of an expression are given in <bibref ref="xpath-40"/>: they are the same as
               the rules used for XPath conditional expressions.</p><p diff="add" at="2022-01-01">If the effective boolean value of the <termref def="dt-expression">expression</termref> is <code nobreak="false">true</code>, then:</p><ulist diff="add" at="2022-01-01"><item><p>If there is a <code nobreak="false">then</code> attribute, the expression in the <code nobreak="false">then</code>
                  attribute is evaluated, and the resulting value is returned as the result of the 
                  <elcode>xsl:if</elcode> instruction.</p></item><item><p>If there is a non-empty sequence constructor, it is evaluated and the
                  resulting value is returned as the result of the 
                  <elcode>xsl:if</elcode> instruction.</p></item><item><p>Otherwise, the result of the 
                  <elcode>xsl:if</elcode> instruction is the empty sequence.</p></item></ulist><p diff="add" at="2022-01-01">If the effective boolean value of the <code nobreak="false">test</code> <termref def="dt-expression">expression</termref> is <code nobreak="false">false</code>, then:</p><ulist diff="add" at="2022-01-01"><item><p>If there is an <code nobreak="false">else</code> attribute, the expression in the <code nobreak="false">else</code>
                  attribute is evaluated, and the resulting value is returned as the result of the 
                  <elcode>xsl:if</elcode> instruction.</p></item><item><p>Otherwise, the result of the 
                  <elcode>xsl:if</elcode> instruction is the empty sequence.</p></item></ulist><p diff="add" at="2022-01-01">If the <code nobreak="false">test</code> expression has no effective boolean value (for example,
            if it is a sequence of several integers, or a map), then a <termref def="dt-dynamic-error"/> occurs. 
            (See <xerrorref spec="FO" class="RG" code="0006"/>.)</p><note diff="add" at="2022-11-01"><p>The semantics of the <elcode>xsl:if</elcode> instruction are essentially equivalent to the semantics
               of the conditional expression in XPath: the construct <code nobreak="false">&lt;xsl:if test="C" then="X" else="Y"/&gt;</code>
                  can equivalently be written <code nobreak="false">&lt;xsl:sequence select="if (C) then X else Y"/&gt;</code>. The same
                  effect can also be achieved by writing 
                  <code nobreak="false">&lt;xsl:choose&gt;&lt;xsl:when test="C" select="X"/&gt;&lt;xsl:otherwise select="Y"/&gt;&lt;/xsl:choose&gt;.</code>
                  The choice of which of these constructs to use is a largely matter of personal style.
                  
               </p></note><example><head>Using <elcode>xsl:if</elcode> to insert separators</head><p>In the following example, the names in a group of names are formatted as a comma
                  separated list:</p><eg xml:space="preserve" role="xslt-declaration">&lt;xsl:template match="namelist/name"&gt;
  &lt;xsl:apply-templates/&gt;
  &lt;xsl:if test="not(position()=last())"&gt;, &lt;/xsl:if&gt;
&lt;/xsl:template&gt;</eg><p diff="add" at="2022-11-01">This adds a comma after every item except the last. This can also be
                  expressed as:</p><eg diff="add" at="2022-11-01" xml:space="preserve" role="xslt-declaration">&lt;xsl:template match="namelist/name"&gt;
  &lt;xsl:if test="not(position()=1)"&gt;, &lt;/xsl:if&gt;
  &lt;xsl:apply-templates/&gt; 
&lt;/xsl:template&gt;</eg><p diff="add" at="2022-11-01">which inserts a comma before every item except the first. (This formulation might
                  be more efficient, since determining whether an item is the last may involve look-ahead.)</p></example><example><head>Using <elcode>xsl:if</elcode> as the body of a function</head><p diff="add" at="2022-11-01">The following example shows the use of <elcode>xsl:if</elcode> to
                  deliver the result of a recursive function:</p><eg xml:space="preserve" role="xslt-declaration" diff="chg" at="2022-01-01">&lt;xsl:function name="f:product" as="xs:double"&gt;
   &lt;xsl:param name="in" as="xs:double*"/&gt;
   &lt;xsl:if test="empty($in)" then="1e0" else="head($in) * f:product(tail($in))"/&gt;
&lt;/xsl:function&gt;</eg></example></div2><div2 id="xsl-choose"><head>Conditional Processing with <elcode>xsl:choose</elcode></head><changes><change issue="167" PR="237" date="2022-11-25">
                  In <elcode>xsl:choose</elcode>, the <elcode>xsl:when</elcode> and
                  <code nobreak="false">xsl:otherwise</code> elements can take a <code nobreak="false">select</code> attribute
                  in place of a sequence constructor. 
               </change></changes><e:element-syntax xmlns:e="http://www.w3.org/1999/XSL/Spec/ElementSyntax" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" name="choose">
      <e:in-category name="instruction"/>
      <e:sequence>
         <e:element repeat="one-or-more" name="when"/>
         <e:element repeat="zero-or-one" name="otherwise"/>
      </e:sequence>
      <e:allowed-parents>
         <e:parent-category name="sequence-constructor"/>
      </e:allowed-parents>
   </e:element-syntax><e:element-syntax xmlns:e="http://www.w3.org/1999/XSL/Spec/ElementSyntax" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" name="when">
      <e:attribute name="test" required="yes">
         <e:data-type name="expression"/>
      </e:attribute>
      <e:attribute name="select" required="no">
         <e:data-type name="expression"/>
      </e:attribute>
      <e:model name="sequence-constructor"/>
      <e:allowed-parents>
         <e:parent name="choose"/>
      </e:allowed-parents>
   </e:element-syntax><e:element-syntax xmlns:e="http://www.w3.org/1999/XSL/Spec/ElementSyntax" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" name="otherwise">
      <e:attribute name="select" required="no">
         <e:data-type name="expression"/>
      </e:attribute>
      <e:model name="sequence-constructor"/>
      <e:allowed-parents>
         <e:parent name="choose"/>
      </e:allowed-parents>
   </e:element-syntax><p>The <elcode>xsl:choose</elcode> element selects one among a number of possible
               alternatives. It consists of a sequence of one or more <elcode>xsl:when</elcode>
               elements followed by an optional <elcode>xsl:otherwise</elcode> element. Each
               <elcode>xsl:when</elcode> element has <phrase diff="chg" at="2022-01-01">an</phrase> attribute, <code nobreak="false">test</code>, which
               specifies an <termref def="dt-expression">expression</termref> used as a condition.</p><p diff="add" at="2022-01-01">The effective value of an <elcode>xsl:when</elcode> or <elcode>xsl:otherwise</elcode>
               branch may be supplied using either a <code nobreak="false">select</code> attribute or a contained
               <termref def="dt-sequence-constructor"/>. These are
               mutually exclusive: if the <code nobreak="false">select</code> attribute is present then the
               sequence constructor must be empty, and if the sequence constructor is non-empty
               then the <code nobreak="false">select</code> attribute must be absent 
               <phrase diff="add" at="2023-05-10"><errorref spec="XT" class="SE" code="3185"/></phrase>. 
               If the <code nobreak="false">select</code>
               attribute is absent and the sequence constructor is empty, then the
               effective value is the empty sequence.</p><p>When an <elcode>xsl:choose</elcode> element is processed, each of the
               <elcode>xsl:when</elcode> elements is tested in turn (that is, in the order that
               the elements appear in the stylesheet), until one of the <elcode>xsl:when</elcode>
               elements is satisfied. If none of the <elcode>xsl:when</elcode> elements is
               satisfied, then the <elcode>xsl:otherwise</elcode> element is considered, as
               described below.</p><p>An <elcode>xsl:when</elcode> element is satisfied if the <xtermref spec="XP40" ref="dt-ebv">effective boolean value</xtermref> of the <termref def="dt-expression">expression</termref> in its <code nobreak="false">test</code> attribute is
               <code nobreak="false">true</code>. The rules for determining the effective boolean value of an
               expression are given in <bibref ref="xpath-40"/>: they are the same as the rules used
               for XPath conditional expressions.</p><p>The <phrase diff="del" at="2022-01-01">content of the</phrase> first, and only the first, <elcode>xsl:when</elcode> element that
               is satisfied is evaluated, and the resulting sequence <phrase diff="add" at="2022-01-01">(that is,
                  the result of evaluating its <code nobreak="false">select</code> attribute or contained <termref def="dt-sequence-constructor"/> 
                  as appropriate)</phrase> is returned as the result of
               the <elcode>xsl:choose</elcode> instruction. If no <elcode>xsl:when</elcode> element
               is satisfied, the content of the <elcode>xsl:otherwise</elcode> element is evaluated,
               and the resulting sequence is returned as the result of the
               <elcode>xsl:choose</elcode> instruction. If no <elcode>xsl:when</elcode> element
               is satisfied, and no <elcode>xsl:otherwise</elcode> element is present, the result of
               the <elcode>xsl:choose</elcode> instruction is the empty sequence.</p><p><phrase diff="chg" at="2022-01-01">The <code nobreak="false">select</code> expressions and sequence constructors of  
               <elcode>xsl:when</elcode> and
               <elcode>xsl:otherwise</elcode> instructions after the selected one are not evaluated.</phrase> 
               The <code nobreak="false">test</code>
               expressions for <elcode>xsl:when</elcode> instructions after the selected one are not
               evaluated.</p><example><head>Using <elcode>xsl:choose</elcode> for formatting a numbered list
               </head><p>The following example enumerates items in an ordered list using arabic numerals,
                  letters, or roman numerals depending on the depth to which the ordered lists are
                  nested.</p><eg xml:space="preserve" role="xslt-declaration xmlns:fo='fo'">&lt;xsl:template match="orderedlist/listitem"&gt;
  &lt;fo:list-item indent-start='2pi'&gt;
    &lt;fo:list-item-label&gt;
      &lt;xsl:variable name="level"
                    select="count(ancestor::orderedlist) mod 3"/&gt;
      &lt;xsl:choose&gt;
        &lt;xsl:when test='$level=1'&gt;
          &lt;xsl:number format="i"/&gt;
        &lt;/xsl:when&gt;
        &lt;xsl:when test='$level=2'&gt;
          &lt;xsl:number format="a"/&gt;
        &lt;/xsl:when&gt;
        &lt;xsl:otherwise&gt;
          &lt;xsl:number format="1"/&gt;
        &lt;/xsl:otherwise&gt;
      &lt;/xsl:choose&gt;
      &lt;xsl:text&gt;. &lt;/xsl:text&gt;
    &lt;/fo:list-item-label&gt;
    &lt;fo:list-item-body&gt;
      &lt;xsl:apply-templates/&gt;
    &lt;/fo:list-item-body&gt;
  &lt;/fo:list-item&gt;
&lt;/xsl:template&gt;</eg></example><example diff="add" at="2022-01-01"><head>Using the <code nobreak="false">select</code> attribute of <elcode>xsl:when</elcode> and <elcode>xsl:otherwise</elcode></head><p>The following example is equivalent to the one above:</p><eg xml:space="preserve" role="xslt-declaration xmlns:fo='fo'">&lt;xsl:template match="orderedlist/listitem"&gt;
  &lt;fo:list-item indent-start='2pi'&gt;
    &lt;fo:list-item-label&gt;
      &lt;xsl:variable name="level"
                    select="count(ancestor::orderedlist) mod 3"/&gt;
      &lt;xsl:variable name="format" as="xs:string"&gt;
        &lt;xsl:choose&gt;
          &lt;xsl:when test='$level=1' select="'i'"/&gt;
          &lt;xsl:when test='$level=2' select="'a'"/&gt;
          &lt;xsl:otherwise select="'1'"/&gt;
        &lt;/xsl:choose&gt;
      &lt;/xsl:variable&gt;  
      &lt;xsl:number format="{ $format }"/&gt;
      &lt;xsl:text&gt;. &lt;/xsl:text&gt;
    &lt;/fo:list-item-label&gt;
    &lt;fo:list-item-body&gt;
      &lt;xsl:apply-templates/&gt;
    &lt;/fo:list-item-body&gt;
  &lt;/fo:list-item&gt;
&lt;/xsl:template&gt;</eg></example></div2><div2 diff="add" at="2022-01-01" id="xsl-switch"><head>Conditional Processing with <elcode>xsl:switch</elcode></head><changes><change issue="167" PR="237" date="2022-11-25">
                  A new <elcode>xsl:switch</elcode> instruction is introduced.
               </change></changes><e:element-syntax xmlns:e="http://www.w3.org/1999/XSL/Spec/ElementSyntax" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" name="switch">
      <e:in-category name="instruction"/>
      <e:attribute name="select" required="yes">
         <e:data-type name="expression"/>
      </e:attribute>
      <e:sequence>
         <e:element repeat="one-or-more" name="when"/>
         <e:element repeat="zero-or-one" name="otherwise"/>
         <e:element repeat="zero-or-more" name="fallback"/>
      </e:sequence>
      <e:allowed-parents>
         <e:parent-category name="sequence-constructor"/>
      </e:allowed-parents>
   </e:element-syntax><e:element-syntax xmlns:e="http://www.w3.org/1999/XSL/Spec/ElementSyntax" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" name="when">
      <e:attribute name="test" required="yes">
         <e:data-type name="expression"/>
      </e:attribute>
      <e:attribute name="select" required="no">
         <e:data-type name="expression"/>
      </e:attribute>
      <e:model name="sequence-constructor"/>
      <e:allowed-parents>
         <e:parent name="choose"/>
      </e:allowed-parents>
   </e:element-syntax><e:element-syntax xmlns:e="http://www.w3.org/1999/XSL/Spec/ElementSyntax" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" name="otherwise">
      <e:attribute name="select" required="no">
         <e:data-type name="expression"/>
      </e:attribute>
      <e:model name="sequence-constructor"/>
      <e:allowed-parents>
         <e:parent name="choose"/>
      </e:allowed-parents>
   </e:element-syntax><p>The <elcode>xsl:switch</elcode> element selects one among a number of possible
               alternatives. The <code nobreak="false">select</code> attribute of the <elcode>xsl:switch</elcode> element
               is evaluated to obtain an atomic item, which is compared with the values given by the
               <code nobreak="false">test</code> attributes of the <elcode>xsl:when</elcode> elements, in turn.</p><p>The content of the <elcode>xsl:switch</elcode> element consists of a sequence of one or more <elcode>xsl:when</elcode>
               elements followed by an optional <elcode>xsl:otherwise</elcode> element. Each
               <elcode>xsl:when</elcode> element has <phrase diff="chg">an</phrase> attribute, <code nobreak="false">test</code>, which
               contains an <termref def="dt-expression">expression</termref>.</p><p>The result of an <elcode>xsl:when</elcode> or <elcode>xsl:otherwise</elcode>
               branch may be supplied using either a <code nobreak="false">select</code> attribute or a contained
               <termref def="dt-sequence-constructor"/>. These are
               mutually exclusive: if the <code nobreak="false">select</code> attribute is present then the
               sequence constructor must be empty, and if the sequence constructor is non-empty
               then the <code nobreak="false">select</code> attribute must be absent. If the <code nobreak="false">select</code>
               attribute is absent and the sequence constructor is empty, then the
               result is the empty sequence.</p><p>Any <elcode>xsl:fallback</elcode> children are ignored by an XSLT 4.0 processor, but
               can be used to define the recovery action to be taken by a processor for an earlier version of XSLT when
               operating with <termref def="dt-forwards-compatible-behavior"/>.</p><p>An <elcode>xsl:switch</elcode> element is processed as follows:</p><ulist><item><p>The <code nobreak="false">select</code> expression of the <elcode>xsl:switch</elcode>
                  element is evaluated.</p></item><item><p>The result of the evaluation is converted to a single atomic item
                  by applying the <termref def="dt-coercion-rules"/>; a type error occurs
                  if this conversion is not possible. This value is referred to below as the
                  <term>selector</term>.</p></item><item><p>Each of the
                  <elcode>xsl:when</elcode> elements is tested in turn (that is, in the order that
                  the elements appear in the stylesheet), until one of the <elcode>xsl:when</elcode>
                  elements is satisfied. If none of the <elcode>xsl:when</elcode> elements is
                  satisfied, then the <elcode>xsl:otherwise</elcode> element is considered, as
                  described below.</p><p>An <elcode>xsl:when</elcode> element is tested by first evaluating its <code nobreak="false">test</code>
                     expression and converting the result to a sequence of atomic items
                     by applying the <termref def="dt-coercion-rules"/>, and then
                     comparing this sequence of atomic items with the <code nobreak="false">selector</code> value. The
                     comparison is performed using the rules of the XPath <code nobreak="false">=</code> operator,
                     using the default collation that is in scope for the <elcode>xsl:switch</elcode>
                     instruction.</p><p>An <elcode>xsl:when</elcode> element is satisfied if the result of this comparison is
                     <code nobreak="false">true</code>.</p></item><item><p>The first, and only the first, <elcode>xsl:when</elcode> element that
                  is satisfied is evaluated, and the resulting sequence <phrase diff="add" at="2022-01-01">(that is,
                     the result of evaluating its <code nobreak="false">select</code> attribute or contained <termref def="dt-sequence-constructor"/> 
                     as appropriate)</phrase> is returned as the result of
                  the <elcode>xsl:switch</elcode> instruction. If no <elcode>xsl:when</elcode> element
                  is satisfied, the content of the <elcode>xsl:otherwise</elcode> element is evaluated,
                  and the resulting sequence is returned as the result of the
                  <elcode>xsl:switch</elcode> instruction. If no <elcode>xsl:when</elcode> element
                  is satisfied, and no <elcode>xsl:otherwise</elcode> element is present, the result of
                  the <elcode>xsl:switch</elcode> instruction is the empty sequence.</p></item><item><p>The <code nobreak="false">select expressions</code> and sequence constructors of  
                  <elcode>xsl:when</elcode> and
                  <elcode>xsl:otherwise</elcode> instructions after the selected one are not evaluated. 
                  The <code nobreak="false">test</code>
                  expressions for <elcode>xsl:when</elcode> instructions after the selected one are not
                  evaluated.</p></item></ulist><note><p>There is no requirement that the values of <code nobreak="false">select</code> expressions
               should be literals, nor that the values should be distinct.</p></note><example><head>Using <elcode>xsl:switch</elcode> as a lookup table</head><p>The following example shows a simple function to convert a month number to a month name:</p><eg xml:space="preserve" role="xslt-declaration xmlns:fo='fo'">&lt;xsl:function name="f:month-name" as="xs:string"&gt;
    &lt;xsl:param name="month-number" as="xs:integer"/&gt;
    &lt;xsl:switch select="$month-number"&gt;
      &lt;xsl:when test="1" select="'January'"/&gt;
      &lt;xsl:when test="2" select="'February'"/&gt;
      &lt;xsl:when test="3" select="'March'"/&gt;
      &lt;xsl:when test="4" select="'April'"/&gt;
      &lt;xsl:when test="5" select="'May'"/&gt;
      &lt;xsl:when test="6" select="'June'"/&gt;
      &lt;xsl:when test="7" select="'July'"/&gt;
      &lt;xsl:when test="8" select="'August'"/&gt;
      &lt;xsl:when test="9" select="'September'"/&gt;
      &lt;xsl:when test="10" select="'October'"/&gt;
      &lt;xsl:when test="11" select="'November'"/&gt;
      &lt;xsl:when test="12" select="'December'"/&gt;
      &lt;xsl:otherwise select="error('Unknown month')"/&gt;
    &lt;/xsl:switch&gt;
  &lt;/xsl:function&gt;</eg></example><example><head>Using <elcode>xsl:switch</elcode> to return the number of days in the month</head><p>This function returns the number of days in a month, returning the empty sequence 
                  if the supplied month is invalid.</p><eg xml:space="preserve">&lt;xsl:function name="f:days-in-month" as="xs:integer?"&gt;
    &lt;xsl:param name="month-number" as="xs:integer"/&gt;
    &lt;xsl:param name="leap-year" as="xs:boolean"/&gt;
    &lt;xsl:switch select="$month-number"&gt;
      &lt;xsl:when test="1, 3, 5, 7, 8, 10, 12" select="31"/&gt;
      &lt;xsl:when test="4, 6, 9, 11" select="30"/&gt;
      &lt;xsl:when test="2"&gt;
         &lt;xsl:if test="$leap-year" then="29" else="28"/&gt;
      &lt;/xsl:when&gt;
    &lt;/xsl:switch&gt;
  &lt;/xsl:function&gt;</eg></example></div2><div2 id="try-catch"><head>Try/Catch</head><changes><change issue="1503" PR="1505" date="2024-11-26">
                  New variables <code nobreak="false">err:stack-trace</code>, <code nobreak="false">err:additional</code>, 
                  and <code nobreak="false">err:map</code> are available within an <elcode>xsl:catch</elcode> clause.
               </change></changes><p>The <elcode>xsl:try</elcode> instruction can be used to trap
               dynamic errors occurring within the expression it wraps; the recovery action if such
               errors occur is defined using a child <elcode>xsl:catch</elcode> element.</p><e:element-syntax xmlns:e="http://www.w3.org/1999/XSL/Spec/ElementSyntax" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" name="try">
      <e:in-category name="instruction"/>
      <e:attribute name="select" required="no">
         <e:data-type name="expression"/>
      </e:attribute>
      <e:attribute name="rollback-output" default="'yes'">
         <e:data-type name="boolean"/>
      </e:attribute>
      <e:sequence>
         <e:model name="sequence-constructor"/>
         <e:element name="catch"/>
         <e:choice repeat="zero-or-more">
            <e:element name="catch"/>
            <e:element name="fallback"/>
         </e:choice>
      </e:sequence>
      <e:allowed-parents>
         <e:parent-category name="sequence-constructor"/>
      </e:allowed-parents>
   </e:element-syntax><note><p>Because a sequence constructor may contain an <elcode>xsl:fallback</elcode>
                  element, the effect of this content model is that an <elcode>xsl:fallback</elcode>
                  instruction may appear as a child of <elcode>xsl:try</elcode> in any position.</p></note><e:element-syntax xmlns:e="http://www.w3.org/1999/XSL/Spec/ElementSyntax" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" name="catch">
      <e:attribute name="errors" required="no" default="'*'">
         <e:data-type name="tokens"/>
      </e:attribute>
      <e:attribute name="select" required="no">
         <e:data-type name="expression"/>
      </e:attribute>
      <e:model name="sequence-constructor"/>
      <e:allowed-parents>
         <e:parent name="try"/>
      </e:allowed-parents>
   </e:element-syntax><p>An <elcode>xsl:try</elcode> instruction evaluates either the expression contained in
               its <code nobreak="false">select</code> attribute, or its contained <termref def="dt-sequence-constructor">sequence constructor</termref>, and returns the
               result of that evaluation if it succeeds without error. If a <termref def="dt-dynamic-error">dynamic error</termref> occurs during the evaluation, the
               processor evaluates the first <elcode>xsl:catch</elcode> child element applicable to
               the error, and returns that result instead.</p><p>If the <elcode>xsl:try</elcode> element has a <code nobreak="false">select</code> attribute, then it
                  <rfc2119>must</rfc2119> have no children other than <elcode>xsl:catch</elcode> and
                  <elcode>xsl:fallback</elcode>. That is, the <code nobreak="false">select</code> attribute and the
               contained sequence constructor are mutually exclusive. If neither is present, the
               result of the <elcode>xsl:try</elcode> is the empty sequence (no dynamic error can
               occur in this case).</p><p>The <code nobreak="false">rollback-output</code> attribute is described in
                  <specref ref="recovery"/>. The default value is <code nobreak="false">yes</code>.</p><p>
               <error spec="XT" type="static" class="SE" code="3140"><p>It is a <termref def="dt-static-error">static error</termref> if the
                        <code nobreak="false">select</code> attribute of the <elcode>xsl:try</elcode> element is
                     present and the element has children other than <elcode>xsl:catch</elcode> and
                        <elcode>xsl:fallback</elcode> elements.</p></error>
            </p><p>Any <elcode>xsl:fallback</elcode> children of the <elcode>xsl:try</elcode> element
               are ignored by an XSLT 3.0 processor, but can be used to define the recovery action
               taken by an XSLT 1.0 or XSLT 2.0 processor operating with <termref def="dt-forwards-compatible-behavior"/>.</p><p>The <elcode>xsl:catch</elcode> element has an optional <code nobreak="false">errors</code> attribute,
               which lists the error conditions that the <elcode>xsl:catch</elcode> element is
               designed to intercept. The default value is <code nobreak="false">errors="*"</code>, which catches
               all errors. The value is a whitespace-separated list of <xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="XP40" ref="prod-xpath40-NameTest" xlink:type="simple">NameTests</xnt>; an <elcode>xsl:catch</elcode> element
               catches an error condition if this list includes a <code nobreak="false">NameTest</code> that matches
               the error code associated with that error condition.</p><note><p>Error codes are QNames. Those defined in this specification and in related
                  specifications are all in the <termref def="dt-standard-error-namespace">standard
                     error namespace</termref>, and may therefore be caught using an
                     <elcode>xsl:catch</elcode> element such as <code nobreak="false">&lt;xsl:catch
                     errors="err:FODC0001 err:FODC0005"&gt;</code> where the namespace prefix
                     <code nobreak="false">err</code> is bound to this namespace. Errors defined by implementers,
                  and errors raised by an explicit call of the <xfunction>error</xfunction> function
                  or by use of the <elcode>xsl:message</elcode>
                  or <elcode>xsl:assert</elcode> instruction, may
                  use error codes in other namespaces.</p></note><p>If more than one <elcode>xsl:catch</elcode> element matches an error, the error is
               processed using the first one that matches, in document order. If no
                  <elcode>xsl:catch</elcode> matches the error, then the error is not caught (that
               is, evaluation of the <elcode>xsl:try</elcode> element fails with the dynamic
               error).</p><p>An <elcode>xsl:catch</elcode> element may have either a <code nobreak="false">select</code>
               attribute, or a contained <termref def="dt-sequence-constructor">sequence
                  constructor</termref>.</p><p>
               <error spec="XT" type="static" class="SE" code="3150"><p>It is a <termref def="dt-static-error">static error</termref> if the
                        <code nobreak="false">select</code> attribute of the <elcode>xsl:catch</elcode> element is
                     present unless the element has empty content.</p></error>
            </p><p>The result of evaluating the <elcode>xsl:catch</elcode> element is the result of
               evaluating the XPath expression in its <code nobreak="false">select</code> attribute or the result of
               evaluating the contained sequence constructor; if neither is present, the result is
               the empty sequence. This result is delivered as the result of the <elcode>xsl:try</elcode>
               instruction.</p><p>If a dynamic error occurs during the evaluation of <elcode>xsl:catch</elcode>, it
               causes the containing <elcode>xsl:try</elcode> to fail with this error. The error is
               not caught by other sibling <elcode>xsl:catch</elcode> elements within the same
                  <elcode>xsl:try</elcode> instruction, but it may be caught by an
                  <elcode>xsl:try</elcode> instruction at an outer level, or by an
                  <elcode>xsl:try</elcode> instruction nested within the <elcode>xsl:catch</elcode>. </p><p>Within the <code nobreak="false">select</code> expression, or within the sequence constructor
               contained by the <elcode>xsl:catch</elcode> element, a number of variables are
               implicitly declared, giving information about the error that occurred. These are
               lexically scoped to the <elcode>xsl:catch</elcode> element. These variables are all in
               the <termref def="dt-standard-error-namespace">standard error namespace</termref>,
               and they are initialized as described in the following table:</p><table class="data" border="1" cellpadding="5" width="100%"><caption>Variables Available within <code nobreak="false">xsl:catch</code></caption><thead><tr><th rowspan="1" colspan="1" align="left" valign="top">Variable</th><th rowspan="1" colspan="1" align="left" valign="top">Type</th><th rowspan="1" colspan="1" align="left" valign="top">Value</th></tr></thead><tbody><tr><td rowspan="1" colspan="1" align="left" valign="top">err:code</td><td rowspan="1" colspan="1" align="left" valign="top">xs:QName</td><td rowspan="1" colspan="1" align="left" valign="top">The error code</td></tr><tr><td rowspan="1" colspan="1" align="left" valign="top">err:description</td><td rowspan="1" colspan="1" align="left" valign="top">xs:string?</td><td rowspan="1" colspan="1" align="left" valign="top">A description of the error condition; the empty sequence if no description is available (for example, if
                           the <xfunction>error</xfunction> function was called with one
                           argument).</td></tr><tr><td rowspan="1" colspan="1" align="left" valign="top">err:value</td><td rowspan="1" colspan="1" align="left" valign="top">item()*</td><td rowspan="1" colspan="1" align="left" valign="top">Value associated with the error. For an error raised by
                        calling the <xfunction>error</xfunction> function, this is the value of the
                        third argument (if supplied). For an error raised by evaluating
                           <elcode>xsl:message</elcode> with <code nobreak="false">terminate="yes"</code>, or a failing <elcode>xsl:assert</elcode>, this
                        is the document node at the root of the tree containing the XML message
                        body.</td></tr><tr><td rowspan="1" colspan="1" align="left" valign="top">err:module</td><td rowspan="1" colspan="1" align="left" valign="top">xs:string?</td><td rowspan="1" colspan="1" align="left" valign="top">The URI (or system ID) of the stylesheet module containing the
                        instruction where the error occurred; the empty sequence if the information
                        is not available.</td></tr><tr><td rowspan="1" colspan="1" align="left" valign="top">err:line-number</td><td rowspan="1" colspan="1" align="left" valign="top">xs:integer?</td><td rowspan="1" colspan="1" align="left" valign="top">The line number within the stylesheet module of the
                        instruction where the error occurred; the empty sequence if the information
                        is not available. The value <rfc2119>may</rfc2119> be approximate.</td></tr><tr><td rowspan="1" colspan="1" align="left" valign="top">err:column-number</td><td rowspan="1" colspan="1" align="left" valign="top">xs:integer?</td><td rowspan="1" colspan="1" align="left" valign="top">The column number within the stylesheet module of the
                        instruction where the error occurred; the empty sequence if the information
                        is not available. The value <rfc2119>may</rfc2119> be approximate.</td></tr><tr><td rowspan="1" colspan="1" align="left" valign="top">err:stack-trace</td><td rowspan="1" colspan="1" align="left" valign="top">xs:string?</td><td rowspan="1" colspan="1" align="left" valign="top">An <termref def="dt-implementation-dependent"/> 
                        string containing diagnostic
                        information about the state of execution at the point where the error occured, 
                        or the empty sequence if no stack trace is available.</td></tr><tr><td rowspan="1" colspan="1" align="left" valign="top">err:additional</td><td rowspan="1" colspan="1" align="left" valign="top">item()*</td><td rowspan="1" colspan="1" align="left" valign="top">Additional <termref def="dt-implementation-defined"/>
                        information about the error.</td></tr><tr><td rowspan="1" colspan="1" align="left" valign="top">err:map</td><td rowspan="1" colspan="1" align="left" valign="top">map(xs:string, item()*)</td><td rowspan="1" colspan="1" align="left" valign="top">A map with entries that are bound to the variables
                     above. The local names of the variables are assigned as keys. No map entries
                     are created for those values that are empty sequences. The variable can be
                     used to pass on all error information to another function.</td></tr></tbody></table><p>Variables declared within the sequence constructor of the <elcode>xsl:try</elcode>
               element (and not within an <elcode>xsl:catch</elcode>) are not visible within the
                  <elcode>xsl:catch</elcode> element.</p><note><p>Within an <elcode>xsl:catch</elcode> it is possible to re-raise the error using
                  the function call <code nobreak="false">error($err:code, $err:description, $err:value)</code>.</p></note><p>The following additional rules apply to the catching of errors:</p><olist><item><p>All dynamic errors occurring during the evaluation of the
                        <elcode>xsl:try</elcode> sequence constructor or <code nobreak="false">select</code>
                     expression are caught (provided they match one of the
                        <elcode>xsl:catch</elcode> elements). </p><note><ulist><item><p>This includes errors occurring in functions or templates invoked in
                              the course of this evaluation, unless already caught by a nested
                                 <elcode>xsl:try</elcode>.</p></item><item><p>It also includes (for
                                 example) errors caused by calling the
                                 <xfunction>error</xfunction> function, or the
                                 <elcode>xsl:message</elcode> instruction with
                                 <code nobreak="false">terminate="yes"</code>, or the 
                                 <elcode>xsl:assert</elcode> instruction, or the <code nobreak="false">xs:error</code> constructor
                                 function. </p></item><item><p>It does not include errors that occur while evaluating references to
                              variables whose declaration and initialization is outside the
                                 <elcode>xsl:try</elcode>.</p></item></ulist></note></item><item><p>The existence of an <elcode>xsl:try</elcode> instruction does not affect the
                     obligation of the processor to raise certain errors as static errors, or its
                     right to choose whether to raise some errors (such as <termref def="dt-type-error">type errors</termref>) statically or dynamically. Static
                     errors are never caught.</p></item><item><p>Some fatal errors arising in the processing environment, such as running out of
                     memory, may cause termination of the transformation despite the presence of an
                        <elcode>xsl:try</elcode> instruction. This is <termref def="dt-implementation-dependent">implementation-dependent</termref>.</p></item><item><p>If the sequence constructor or <code nobreak="false">select</code> expression of the
                        <elcode>xsl:try</elcode> causes execution of
                        <elcode>xsl:result-document</elcode>, <elcode>xsl:message</elcode>, or <elcode>xsl:assert</elcode> instructions and
                     fails with a dynamic error that is caught, it is implementation-dependent
                     whether these instructions have any externally visible effect. The processor is
                        <rfc2119>not required</rfc2119> to roll back any changes made by these
                     instructions. The same applies to any side effects caused by extension
                     functions or extension instructions.</p></item><item><p>A serialization error that occurs during the serialization of
                     a <termref def="dt-secondary-result"/> produced
                     using <elcode>xsl:result-document</elcode> is treated as a dynamic error in the
                     evaluation of the <elcode>xsl:result-document</elcode> instruction, and may be
                     caught (for example by an <elcode>xsl:try</elcode> instruction that contains
                     the <elcode>xsl:result-document</elcode> instruction). A serialization error
                     that occurs while serializing the <termref def="dt-principal-result"/>
                      is
                     treated as occurring after the transformation has finished, and cannot be
                     caught. </p></item><item><p>A validation error is treated as occurring in the instruction
                     that requested validation. For example, if the stylesheet is producing XHTML
                     output and requests validation of the entire result document by means of the
                     attribute <code nobreak="false">validation="strict"</code> on the instruction that creates the
                     outermost <code nobreak="false">html</code> element, then a validation failure can be caught
                     only at that level. Although the validation error might be detected, for
                     example, while writing a <code nobreak="false">p</code> element at a location where no
                        <code nobreak="false">p</code> element is allowed, it is not treated as an error in the
                     instruction that writes the <code nobreak="false">p</code> element and cannot be caught at that
                     level.</p></item><item><p>A type error may be caught if the processor raises it dynamically; this does
                     not affect the processor’s right to raise the error statically if it
                     chooses.</p><p>The following rules are provided to define which expression is considered to
                     fail when a type error occurs, and therefore where the error can be caught. The
                     general principle is that where the semantics of a construct <var>C</var> place
                     requirements on the type of some subexpression, a type error is an error in the
                     evaluation of <var>C</var>, not in the evaluation of the subexpression.</p><p>For example, consider the following construct:</p><eg role="xslt-declaration" xml:space="preserve">&lt;xsl:variable name="v" as="xs:integer"&gt;
  &lt;xsl:sequence select="$foo"/&gt;
&lt;/xsl:variable&gt;</eg><p>The expected type of the result of the sequence constructor is
                        <code nobreak="false">xs:integer</code>; if the value of variable <code nobreak="false">$foo</code> turns
                     out to be a string, then a type error will occur. It is not possible to catch
                     this by writing:</p><eg role="xslt-declaration" xml:space="preserve">&lt;xsl:variable name="v" as="xs:integer"&gt;
  &lt;xsl:try&gt;
    &lt;xsl:sequence select="$foo"/&gt;
    &lt;xsl:catch&gt;...&lt;/xsl:catch&gt;
  &lt;/xsl:try&gt;
&lt;/xsl:variable&gt;</eg><p>This fails to catch the error because the <elcode>xsl:sequence</elcode>
                     instruction is deemed to evaluate successfully; the failure only occurs when
                     the result of this instruction is bound to the variable.</p><p>A similar rule applies to functions: if the body of a function computes a
                     result which does not conform to the required type of the function result, it
                     is not possible to catch this error within the function body itself; it can
                     only be caught by the caller of the function. Similarly, if an expression used
                     to compute an argument to a function returns a value of the wrong type for the
                     function signature, this is not considered an error in this expression, but an
                     error in evaluating the function call as a whole.</p><p>A consequence of these rules is that when a type error occurs while
                     initializing a global variable (because the initializer returns a value of the
                     wrong type, given the declared type of the variable), then this error cannot be
                     caught.</p><note><p>Because processors are permitted to raise type errors during static
                        analysis, it is unwise to attempt to recover from type errors dynamically.
                        The best strategy is generally to prevent their occurrence. For example,
                        rather than writing <code nobreak="false">$p + 1</code> where <code nobreak="false">$p</code> is a parameter
                        of unknown type, and then catching the type error that occurs if
                           <code nobreak="false">$p</code> is not numeric, it is better first to test whether
                           <code nobreak="false">$p</code> is numeric, perhaps by means of an expression such as
                           <code nobreak="false">$p instance of my:numeric</code>, where <code nobreak="false">my:numeric</code> is
                        a union type with <code nobreak="false">xs:double</code>, <code nobreak="false">xs:float</code>, and
                           <code nobreak="false">xs:decimal</code> as its member types.</p></note></item><item><p>The fact that the application tries to catch errors does not prevent the
                     processor from organizing the evaluation in such a way as to prevent errors
                     occurring. For example <code nobreak="false">exists(//a[10 div . gt 5])</code> may still do an
                     “early exit”, rather than examining every item in the sequence just to see if
                     it triggers a divide-by-zero error.</p></item><item><p>Except as specified above, the optimizer must not rearrange the evaluation (at
                     compile time or at run time) so that expressions written to be subject to the
                     try/catch are evaluated outside its scope, or expressions written to be
                     external to the try/catch are evaluated within its scope. This does not prevent
                     expressions being rearranged, but any expression that is so rearranged must
                     carry its try/catch context with it.</p></item></olist><div3 id="recovery"><head>Recovery of Result Trees</head><p>The XSLT language is designed so that a processor that chooses to execute
                  instructions in document order will always append nodes to the result tree in
                  document order, and never needs to update a result tree in situ. As a result, it
                  is normal practice for XSLT processors to stream the result tree directly to its
                  final destination (for example, a serializer) without ever holding the tree in
                  memory. This applies whether or not the processor is streamable, and whether or
                  not source documents are streamed.</p><p>The language specification states (see <specref ref="errors"/>) that when a
                  transformation terminates with a dynamic error, the state of persistent resources
                  affected by the transformation (for example, serialized result documents) is
                     <termref def="dt-implementation-defined"/>, so processors are not required to
                  take any special steps to recover such resources to their pre-transformation
                  state; at the same time, there is no guarantee that secondary result documents
                  produced before the failure occurs will be in a usable state.</p><p>The situation becomes more complicated when dynamic errors occur while writing to
                  a result tree, and the dynamic error is caught by an
                     <elcode>xsl:try</elcode>/<elcode>xsl:catch</elcode> instruction. The semantics
                  of these instructions requires that when an error occurring during the evaluation
                  of <elcode>xsl:try</elcode> is caught, the result of the <elcode>xsl:try</elcode>
                  instruction is the result of the relevant <elcode>xsl:catch</elcode>. To achieve
                  this, any output written to the result tree during the execution of
                     <elcode>xsl:try</elcode> until the point where the error occurs must
                  effectively be undone. There are two basic strategies for achieving this: either
                  the updates are not committed to persistent storage until the
                     <elcode>xsl:try</elcode> instruction is completed, or the updates are written
                  in such a way that they can be rolled back in the event of a failure.</p><p>Both these strategies are potentially expensive, and both have an adverse effect
                  on streaming, in that they affect the amount of memory needed to transform large
                  amounts of data. XSLT 3.0 therefore provides an option to relax the requirement to
                  recover result trees when failures occur in the course of evaluating an
                     <elcode>xsl:try</elcode> instruction. This option is invoked by specifying
                     <code nobreak="false">rollback-output="no"</code> on the <elcode>xsl:try</elcode>
                  instruction.</p><p>The default value of the attribute is <code nobreak="false">rollback-output="yes"</code>.</p><p>The effect of specifying <code nobreak="false">rollback-output="no"</code> on
                     <elcode>xsl:try</elcode> is as follows: if a dynamic error occurs in the course
                  of evaluating the <elcode>xsl:try</elcode> instruction, and if the failing
                  construct is evaluated in <termref def="dt-final-output-state"/> while writing to
                  some result document, then it is <termref def="dt-implementation-dependent"/>
                  whether an attempt to catch this error using <elcode>xsl:catch</elcode> will be
                  successful. If the attempt is successful, then the <elcode>xsl:try</elcode>
                  instruction succeeds, delivering the result of evaluating the
                     <elcode>xsl:catch</elcode> clause, and the transformation proceeds as normal.
                  If the attempt is unsuccessful (typically, because non-recoverable updates have
                  already been made to the result tree), then the <elcode>xsl:try</elcode>
                  instruction as a whole fails with a dynamic error. The state of this result
                  document will then be undefined, but the transformation can ignore the failure and
                  continue to produce other result documents, for example by wrapping the
                     <elcode>xsl:result-document</elcode> instruction in an <elcode>xsl:try</elcode>
                  instruction that catches the relevant error.</p><p>
                  <error spec="XT" class="DE" code="3530" type="dynamic"><p>It is a <termref def="dt-dynamic-error"/> if an <elcode>xsl:try</elcode>
                        instruction is unable to recover the state of a final result tree because
                        recovery has been disabled by use of the attribute
                           <code nobreak="false">rollback-output="no"</code>.</p></error>
               </p><p>For example, consider the following:</p><eg role="xslt-instruction" xml:space="preserve">
&lt;xsl:result-document href="out.xml"&gt;     
  &lt;xsl:try rollback-output="no"&gt;
    &lt;xsl:source-document streamable="yes" href="in.xml"&gt;
      &lt;xsl:copy-of select="."/&gt;
    &lt;/xsl:source-document&gt;
    &lt;xsl:catch errors="*"&gt;
       &lt;error code="{ $err:code }" message="{ $err:description }" file="in.xml"/&gt;
    &lt;/xsl:catch&gt;
  &lt;/xsl:try&gt;
&lt;/xsl:result-document&gt;</eg><p>The most likely failure to occur here is a failure to read the streamed input file
                     <code nobreak="false">in.xml</code>. In the common case where this failure is detected
                  immediately, for example if the file does not exist or the network connection is
                  down, no output will have been written to the result document, and the attempt to
                  catch the error is likely to be successful. If however a failure is detected after
                  several megabytes of data have been copied to <code nobreak="false">out.xml</code>, for example an
                  XML well-formedness error in the input file, or a network failure that occurs
                  while reading the file, recovery of the output file may be impossible. In this
                  situation the <elcode>xsl:result-document</elcode> instruction will fail with a
                  dynamic error. It is possible to catch this error, but the state of the file
                     <code nobreak="false">out.xml</code> will be unpredictable.</p><p>Note that adding an <elcode>xsl:try</elcode> instruction as a child of
                     <elcode>xsl:source-document</elcode> does not help. Any error reading the input file
                  (such as a well-formedness error) is an error in the <elcode>xsl:source-document</elcode>
                  instruction and can only be caught at that level.</p><p>When <code nobreak="false">rollback-output="no"</code> is specified, it is still possible to
                  ensure recovery of errors happens predictably by evaluating the
                  potentially failing code in <termref def="dt-temporary-output-state"/>: typically,
                  within an <elcode>xsl:variable</elcode>. In effect the variable acts as an
                  explicit buffer for temporary results, which is only copied to the final output if
                  evaluation succeeds.</p><note><p>An application might wish to ensure that when a fatal error occurs while
                     reading an input stream, data written to persistent storage up to the point of
                     failure is available after the transformation terminates. Setting
                        <code nobreak="false">rollback-output="no"</code> does not guarantee this, but a processor
                     might choose to interpret this as the intent.</p></note><p>Changing the attribute to <code nobreak="false">rollback-output="yes"</code> makes the stylesheet
                  more robust and able to handle error conditions predictably, but the cost may be
                  substantial; for example it may be necessary to buffer the whole of the result
                  document in memory.</p></div3><div3 id="try-catch-examples"><head>Try/Catch Examples</head><example><head>Catching a Divide-by-Zero Error</head><p>The following example divides an employee’s salary by the number of
                     years they have served, catching the divide-by-zero error if the latter is
                     zero.</p><eg role="xslt-instruction xmlns:err='http://www.w3.org/2005/xqt-errors'" xml:space="preserve">&lt;xsl:try select="salary div length-of-service"&gt;
  &lt;xsl:catch errors="err:FOAR0001" select="()"/&gt;
&lt;/xsl:try&gt;</eg></example><example><head>Catching an Error during Result-tree Validation</head><p>The following example generates a result tree and performs schema validation,
                     outputting a warning message and serializing the invalid tree if validation
                     fails.</p><eg role="xslt-instruction xmlns:err='http://www.w3.org/2005/xqt-errors'" xml:space="preserve">&lt;xsl:result-document href="out.xml"&gt;
  &lt;xsl:variable name="result"&gt;
    &lt;xsl:call-template name="construct-output"/&gt;
  &lt;/xsl:variable&gt;
  &lt;xsl:try&gt;
    &lt;xsl:copy-of select="$result" validation="strict"/&gt;
    &lt;xsl:catch&gt;
      &lt;xsl:message&gt;Warning: validation of result document failed:
          Error code: &lt;xsl:value-of select="$err:code"/&gt;
          Reason: &lt;xsl:value-of select="$err:description"/&gt;
      &lt;/xsl:message&gt;
      &lt;xsl:sequence select="$result"/&gt;
    &lt;/xsl:catch&gt;
  &lt;/xsl:try&gt;
&lt;/xsl:result-document&gt;
</eg><p>The reason that the result tree is constructed in a variable in this example is
                     so that the unvalidated tree is available to be used within the
                        <elcode>xsl:catch</elcode> element. An alternative approach would be to
                     repeat the logic for constructing the tree:</p><eg role="xslt-instruction" xml:space="preserve">&lt;xsl:try&gt;
  &lt;xsl:result-document href="out.xml" validation="strict"&gt;  
    &lt;xsl:call-template name="construct-output"/&gt;
  &lt;/xsl:result-document&gt;
  &lt;xsl:catch&gt;
    &lt;xsl:message&gt;Warning: validation of result document failed:
          Error code: &lt;xsl:value-of select="$err:code"/&gt;
          Reason: &lt;xsl:value-of select="$err:description"/&gt;
    &lt;/xsl:message&gt;
    &lt;xsl:call-template name="construct-output"/&gt;
  &lt;/xsl:catch&gt;
&lt;/xsl:try&gt;</eg></example></div3></div2><div2 id="conditional-content-construction"><head>Conditional Content Construction</head><p>The facilities described in this section are designed to make it easier to generate
               result trees conditionally depending on what is found in the input, without violating
               the rules for streamability. Although these facilities were 
               introduced to the language specifically to make streaming
               easier, they are available whether or not streaming
               is in use, and users have often found them convenient in non-streaming applications.</p><p>The facilities are introduced first by example:</p><example><head>Generating a Wrapper Element for a non-Empty Sequence</head><p>The following example generates an <code nobreak="false">events</code> element if and only if
                  there are one or more <code nobreak="false">event</code> elements. The code could be written like
                  this:</p><eg role="xslt-instruction" xml:space="preserve">
&lt;xsl:if test="exists(event)"&gt;
  &lt;events&gt;
    &lt;xsl:copy-of select="event"/&gt;
  &lt;/events&gt;
&lt;/xsl:if&gt;</eg><p>However, the above code would not be <xtermref spec="SG40" ref="dt-guaranteed-streamable"/>,
                  because it processes the child <code nobreak="false">event</code> elements more than once. To make
                  it streamable, it can be rewritten as:</p><eg role="xslt-instruction" xml:space="preserve">
&lt;xsl:where-populated&gt;
  &lt;events&gt;
    &lt;xsl:copy-of select="event"/&gt;
  &lt;/events&gt;
&lt;/xsl:where-populated&gt;</eg><p>The effect of the <elcode>xsl:where-populated</elcode> instruction, as explained
                  later, is to avoid outputting the <code nobreak="false">events</code> element if it would have no
                  children. A streaming implementation will typically hold the start tag of the
                     <code nobreak="false">events</code> element in a buffer, to be sent to the output destination
                  only if and when a child node is generated.</p></example><example><head>Generating a Header and Footer only if there is Content</head><p>The following example generates an <code nobreak="false">h3</code> element and a summary paragraph
                  only if a list of items is non-empty. The code could be written like this:</p><eg role="xslt-instruction" xml:space="preserve">&lt;xsl:if test="exists(item-for-sale)"&gt;
  &lt;h1&gt;Items for Sale&lt;/h1&gt;
&lt;/xsl:if&gt;  
&lt;xsl:apply-templates select="item-for-sale"/&gt;
&lt;xsl:if test="exists(item-for-sale)"&gt;
  &lt;p&gt;Total value: {accumulator-before('total-value')}&lt;/p&gt;
&lt;/xsl:if&gt;</eg><p>However, the above code would not be <xtermref spec="SG40" ref="dt-guaranteed-streamable"/>,
                  because it processes the child <code nobreak="false">item-for-sale</code> elements more than once.
                  To make it streamable, it can be rewritten as:</p><eg role="xslt-instruction" xml:space="preserve">&lt;xsl:sequence&gt;
  &lt;xsl:on-non-empty&gt;
    &lt;h1&gt;Items for Sale&lt;/h1&gt;
  &lt;/xsl:on-non-empty&gt;  
  &lt;xsl:apply-templates select="item-for-sale"/&gt;
  &lt;xsl:on-non-empty&gt;
    &lt;p&gt;Total value: {accumulator-before('total-value')}&lt;/p&gt;
  &lt;/xsl:on-non-empty&gt;  
&lt;/xsl:sequence&gt;</eg><p>The effect of the <elcode>xsl:on-non-empty</elcode> instruction, as explained
                  later, is to output the enclosed content only if the containing sequence
                  constructor also generates “ordinary” content, that is, if there is content
                  generated by instructions other than <elcode>xsl:on-empty</elcode> and
                     <elcode>xsl:on-non-empty</elcode> instructions.</p></example><example><head>Generating Substitute Text when there is no Content</head><p>The following example generates a summary paragraph only if a list of items is
                  empty. The code could be written like this:</p><eg role="xslt-instruction" xml:space="preserve">&lt;xsl:apply-templates select="item-for-sale"/&gt;
&lt;xsl:if test="empty(item-for-sale)"&gt;
  &lt;p&gt;There are no items for sale.&lt;/p&gt;
&lt;/xsl:if&gt;</eg><p>However, the above code would not be <xtermref spec="SG40" ref="dt-guaranteed-streamable"/>,
                  because it processes the child <code nobreak="false">item-for-sale</code> elements more than once
                  (the fact that the list is empty is irrelevant, because streamability is
                  determined statically). To make the code streamable, it can be rewritten as:</p><eg role="xslt-instruction" xml:space="preserve">&lt;xsl:sequence&gt;
  &lt;xsl:apply-templates select="item-for-sale"/&gt;
  &lt;xsl:on-empty&gt;
    &lt;p&gt;There are no items for sale.&lt;/p&gt;
  &lt;/xsl:on-empty&gt;
&lt;/xsl:sequence&gt;</eg><p>The effect of the <elcode>xsl:on-empty</elcode> instruction, as explained later,
                  is to output the enclosed content only if the containing sequence constructor
                  generates no “ordinary” content, that is, if there is no content generated by
                  instructions other than <elcode>xsl:on-empty</elcode> and
                     <elcode>xsl:on-non-empty</elcode> instructions.</p></example><p>For further examples showing the use of these instructions when streaming,
            see <xspecref spec="SG40" ref="handling-empty-input"/>.</p><div3 id="where-populated"><head>The <code nobreak="false">xsl:where-populated</code> instruction</head><e:element-syntax xmlns:e="http://www.w3.org/1999/XSL/Spec/ElementSyntax" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" name="where-populated">
      <e:in-category name="instruction"/>
      <e:model name="sequence-constructor"/>
      <e:allowed-parents>
         <e:parent-category name="sequence-constructor"/>
      </e:allowed-parents>
   </e:element-syntax><p>The <elcode>xsl:where-populated</elcode> instruction encloses a <termref def="dt-sequence-constructor"/>. The result of the instruction is established
                  as follows:</p><olist><item><p>The sequence constructor is evaluated in the usual way (taking into account
                        any <elcode>xsl:on-empty</elcode> and <elcode>xsl:on-non-empty</elcode>
                        instructions) to produce a result <var>$R</var>.</p></item><item><p>The result of the instruction is the value of the expression
                           <code nobreak="false">$R[not(deemed-empty(.))]</code> where the function
                           <code nobreak="false">deemed-empty($item as item())</code> returns <code nobreak="false">true</code> if and only if
                           <code nobreak="false">$item</code> is one of the following:</p><ulist><item><p>A document or element node that has no children.</p><note><p>If an element has attributes or namespaces, these do not prevent
                                 the element being deemed empty.</p><p>If a document or element node has children, the node is not deemed
                                 empty, even if the children are empty. For example, a document node
                                 created using an <elcode>xsl:variable</elcode> instruction in the
                                 form
                                    <code nobreak="false">&lt;xsl:variable name="temp"&gt;&lt;a/&gt;&lt;/xsl:variable&gt;</code>
                                 is not deemed empty, even though the contained &lt;a/&gt;
                                 element is empty.</p></note></item><item><p>A node, other than a document or element node, whose string value is
                              zero-length.</p><note><p>A whitespace-only text node is not deemed empty.</p></note></item><item><p>An atomic item such that the result of casting the atomic item to a
                              string is zero-length.</p><note><p>This can happen only when the atomic item is of type
                                    <code nobreak="false">xs:string</code>, <code nobreak="false">xs:anyURI</code>,
                                    <code nobreak="false">xs:untypedAtomic</code>, <code nobreak="false">xs:hexBinary</code>, or
                                    <code nobreak="false">xs:base64Binary</code>.</p></note></item><item><p>A map whose size (number of key/value
                              pairs) is zero.</p></item><item><p>An array (see <specref ref="arrays"/>) where the result 
                              of flattening the array using the <xfunction spec="FO40">array:flatten</xfunction> function is 
                              either the empty sequence, or a sequence in which every item is deemed empty 
                              (applying these rules recursively).</p></item></ulist></item></olist><example><head>Generating an HTML list</head><p>The following example generates an HTML unnumbered list, if and only if the
                     list is non-empty. Note that the presence of the <code nobreak="false">class</code> attribute
                     does not make the list non-empty. The code is written to be streamable.</p><eg role="xslt-instruction" xml:space="preserve">&lt;xsl:where-populated expand-text="yes"&gt;
  &lt;ul class="my-list"&gt;
    &lt;xsl:for-each select="source-item"&gt;
       &lt;li&gt;{.}&lt;/li&gt;
    &lt;/xsl:for-each&gt;
  &lt;/ul&gt;
&lt;/xsl:where-populated&gt;</eg></example></div3><div3 id="on-empty"><head>The <code nobreak="false">xsl:on-empty</code> instruction</head><e:element-syntax xmlns:e="http://www.w3.org/1999/XSL/Spec/ElementSyntax" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" name="on-empty">
      <e:in-category name="instruction"/>
      <e:attribute name="select" required="no">
         <e:data-type name="expression"/>
      </e:attribute>
      <e:model name="sequence-constructor"/>
      <e:allowed-parents>
         <e:parent-category name="sequence-constructor"/>
      </e:allowed-parents>
   </e:element-syntax><p>The <elcode>xsl:on-empty</elcode> instruction has the same content model as
                     <elcode>xsl:sequence</elcode>, and when it is evaluated, the same rules apply.
                  In particular, the <code nobreak="false">select</code> attribute and the contained sequence
                  constructor are mutually exclusive <errorref spec="XT" class="SE" code="3185"/>.</p><p>When an <elcode>xsl:on-empty</elcode> instruction
                  appears in a sequence constructor, then:</p><olist><item><p>It must be the only <elcode>xsl:on-empty</elcode> instruction in the
                        sequence constructor, and</p></item><item><p>It must not be followed in the sequence constructor by any other <termref def="dt-instruction"/>, other than <elcode>xsl:fallback</elcode>, or by a
                        significant text node (that is, a text node that has not been discarded
                        under the provisions of <specref ref="stylesheet-stripping"/>), or by a
                           <termref def="dt-literal-result-element"/>. It may, however, be followed
                        by non-instructions such as <elcode>xsl:catch</elcode> where
                        appropriate.</p></item></olist><p><termdef id="dt-vacuous" term="vacuous">An item is <term>vacuous</term> if
               it is one of the following: a zero-length text node; a document node with no children; an atomic item which, 
               on casting to <code nobreak="false">xs:string</code>, produces a zero-length string; or <phrase diff="del" at="2022-01-01">(when XPath 3.1 is supported)</phrase> an array 
                  which on flattening using the <xfunction spec="FO40">array:flatten</xfunction> function produces either the empty sequence 
                  or a sequence consisting entirely of <termref def="dt-vacuous"/> items.</termdef></p><p>An <elcode>xsl:on-empty</elcode> instruction is triggered only if every 
                  preceding sibling instruction, text node, and literal result element in the same <termref def="dt-sequence-constructor"/> 
                  returns either the empty sequence, or a sequence consisting entirely of <termref def="dt-vacuous"/> items.
               </p><p>If an <elcode>xsl:on-empty</elcode> instruction is triggered, then the result 
                  of the containing <termref def="dt-sequence-constructor"/> is the result of the <elcode>xsl:on-empty</elcode> instruction.
               </p><note><p>This means that the (vacuous) results produced by other instructions in the 
                  sequence constructor are discarded. This is relevant mainly when the result of the sequence constructor 
                  is used for something other than constructing a node: for example if it forms the result of a function, 
                  or the value of a variable, and the function or variable specifies a required type.</p><p>When streaming, it may be necessary to buffer vacuous items in the result sequence until it is 
                     known whether the result will contain items that are non-vacuous. In many common situations, however
                     — in particular, when the sequence constructor is being used to create the content of a node — 
                     vacuous items can be discarded immediately because they do not affect the content of the node being constructed.
                  </p></note><note><p>In nearly all cases, the rules for <elcode>xsl:on-empty</elcode> are aligned 
                  with the rules for constructing complex content. If the sequence constructor within a literal result element 
                  or an <elcode>xsl:element</elcode> instruction includes an <elcode>xsl:on-empty</elcode> instruction, 
                  then the content of the element will be the value delivered by the <elcode>xsl:on-empty</elcode> instruction 
                  if and only if the content would otherwise be empty.</p><p>There is one minor exception to this rule: if the sequence constructor delivers multiple zero-length strings, 
                     then in the absence of the <elcode>xsl:on-empty</elcode> instruction the new element would contain whitespace, 
                     made up of the separators between these zero-length strings; but <elcode>xsl:on-empty</elcode> takes no account 
                     of these separators.</p></note><note><p>Attribute and namespace nodes created by the sequence constructor 
                  are significant; the <elcode>xsl:on-empty</elcode> instruction will not be triggered if such nodes are present. 
                  If this is not the desired effect, it is possible to partition the sequence constructor to change the scope of 
                  <elcode>xsl:on-empty</elcode>, for example:</p><eg role="xslt-instruction" xml:space="preserve">&lt;ol&gt;
  &lt;xsl:attribute name="class" select="numbered-list"/&gt;
  &lt;xsl:sequence&gt;
    &lt;xsl:value-of select="xyz"/&gt;
    &lt;xsl:on-empty select="'The list is empty'"/&gt;
  &lt;/xsl:sequence&gt;
&lt;/ol&gt;</eg></note><note><p>Where the sequence constructor is a child of an instruction with
               an <code nobreak="false">[xsl:]use-attribute-sets</code> attribute, any attribute nodes created by expanding the referenced
               attribute set(s) are not part of the result of the sequence constructor and therefore play no role in determining
               whether an <elcode>xsl:on-empty</elcode> or <elcode>xsl:on-non-empty</elcode> instruction is triggered. 
                  Equally, when the sequence constructor is a child
               of a <termref def="dt-literal-result-element"/>, attribute nodes generated by expanding the attributes
               of the literal result element are not taken into account.</p></note><note><p>If <elcode>xsl:on-empty</elcode> is the only instruction in a sequence
                     constructor then it is always evaluated.</p><p>If <elcode>xsl:on-empty</elcode> and <elcode>xsl:on-non-empty</elcode> appear
                     in the same sequence constructor, then the rules ensure that only one of them
                     will be evaluated.</p></note></div3><div3 id="on-non-empty"><head>The <elcode>xsl:on-non-empty</elcode> instruction</head><e:element-syntax xmlns:e="http://www.w3.org/1999/XSL/Spec/ElementSyntax" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" name="on-non-empty">
      <e:in-category name="instruction"/>
      <e:attribute name="select" required="no">
         <e:data-type name="expression"/>
      </e:attribute>
      <e:model name="sequence-constructor"/>
      <e:allowed-parents>
         <e:parent-category name="sequence-constructor"/>
      </e:allowed-parents>
   </e:element-syntax><p>The <elcode>xsl:on-non-empty</elcode> instruction has the same content model as
                     <elcode>xsl:sequence</elcode>, and when it is evaluated, the same rules apply.
                  In particular, the <code nobreak="false">select</code> attribute and the contained sequence
                  constructor are mutually exclusive <errorref spec="XT" class="SE" code="3185"/>.</p><p>An <elcode>xsl:on-non-empty</elcode> instruction is evaluated only 
                  if there is at least one sibling node in the same <termref def="dt-sequence-constructor"/>, 
                  excluding <elcode>xsl:on-empty</elcode> and <elcode>xsl:on-non-empty</elcode> instructions, 
                  whose evaluation yields a sequence containing an item that is not <termref def="dt-vacuous"/>. 
                  If this condition applies, then all <elcode>xsl:on-non-empty</elcode> instructions in the 
                  containing sequence constructor are evaluated, and their results are included in the result 
                  of the containing sequence constructor in their proper positions.
               </p><note><p>The <elcode>xsl:on-non-empty</elcode> instruction is typically used to generate headers or 
                     footers appearing before or after a list of items, where the header or footer is to be 
                     omitted if there are no items in the list.
              </p></note><note><p>Unlike <elcode>xsl:on-empty</elcode>, the <elcode>xsl:on-non-empty</elcode>
                     instruction can appear anywhere in a sequence constructor, and can appear more
                     than once.</p></note></div3></div2></div1><div1 id="variables-and-parameters"><head>Variables and Parameters</head><p>
            <termdef id="dt-variable-binding-element" term="variable-binding element">The two
               elements <elcode>xsl:variable</elcode> and <elcode>xsl:param</elcode> are referred to
               as <term>variable-binding elements</term>.</termdef></p><p>
            <termdef id="dt-variable" term="variable">The <elcode>xsl:variable</elcode> element
               declares a <term>variable</term>, which may be a <termref def="dt-global-variable">global variable</termref> or a <termref def="dt-local-variable">local
                  variable</termref>.</termdef>
         </p><p>
            <termdef id="dt-parameter" term="parameter">The <elcode>xsl:param</elcode> element
               declares a <term>parameter</term>, which may be a <termref def="dt-stylesheet-parameter">stylesheet parameter</termref>, a <termref def="dt-template-parameter">template parameter</termref>, a <termref def="dt-function-parameter">function parameter</termref>, or an <elcode>xsl:iterate</elcode> parameter. A parameter is a
                  <termref def="dt-variable">variable</termref> with the additional property that
               its value can be set by the caller.</termdef>
         </p><p>
            <termdef id="dt-value" term="value">A variable is a binding between a name and a value.
               The <term>value</term> of a variable is any sequence (of nodes, atomic items,
                  and/or function items), as defined in <bibref ref="xpath-datamodel-40"/>.</termdef>
         </p><div2 id="variables"><head>Variables</head><e:element-syntax xmlns:e="http://www.w3.org/1999/XSL/Spec/ElementSyntax" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" name="variable">
      <e:in-category name="declaration"/>
      <e:in-category name="instruction"/>
      <e:attribute name="name" required="yes">
         <e:data-type name="eqname"/>
      </e:attribute>
      <e:attribute name="select">
         <e:data-type name="expression"/>
      </e:attribute>
      <e:attribute name="as">
         <e:data-type name="sequence-type"/>
      </e:attribute>
      <e:attribute name="static" default="'no'">
         <e:data-type name="boolean"/>
      </e:attribute>
      <e:attribute name="visibility">
         <e:constant value="public"/>
         <e:constant value="private"/>
         <e:constant value="final"/>
         <e:constant value="abstract"/>
      </e:attribute>
      <e:model name="sequence-constructor"/>
      <e:allowed-parents>
         <e:parent name="package"/>
         <e:parent name="stylesheet"/>
         <e:parent name="transform"/>
         <e:parent name="override"/>
         <e:parent name="function"/>
         <e:parent-category name="sequence-constructor"/>
      </e:allowed-parents>
   </e:element-syntax><p>The <elcode>xsl:variable</elcode> element has a <rfc2119>required</rfc2119>
               <code nobreak="false">name</code> attribute, which specifies the name of the variable. The value of
               the <code nobreak="false">name</code> attribute is an <termref def="dt-eqname">EQName</termref>, which is expanded as described in
                  <specref ref="qname"/>.</p><p>The <elcode>xsl:variable</elcode> element has an optional <code nobreak="false">as</code> attribute,
               which specifies the <termref def="dt-required-type">required type</termref> of the
               variable. The value of the <code nobreak="false">as</code> attribute is a 
               <termref def="dt-sequence-type"/>.</p><p>
               <termdef id="dt-supplied-value" term="supplied value">The value of the variable is
                  computed using the <termref def="dt-expression">expression</termref> given in the
                     <code nobreak="false">select</code> attribute or the contained <termref def="dt-sequence-constructor">sequence constructor</termref>, as described in
                     <specref ref="variable-values"/>. This value is referred to as the
                     <term>supplied value</term> of the variable.</termdef> If the
                  <elcode>xsl:variable</elcode> element has a <code nobreak="false">select</code> attribute, then
               the sequence constructor <rfc2119>must</rfc2119> be empty.</p><p>If the <code nobreak="false">as</code> attribute is specified, then the <termref def="dt-supplied-value">supplied value</termref> of the variable is converted to
               the required type, using the <termref def="dt-coercion-rules"/>.</p><p>
               <error spec="XT" type="type" class="TE" code="0570"><p>It is a <termref def="dt-type-error">type error</termref> if the <termref def="dt-supplied-value">supplied value</termref> of a variable cannot be
                     converted to the required type.</p></error>
            </p><p>If the <code nobreak="false">as</code> attribute is omitted, the <termref def="dt-supplied-value">supplied value</termref> of the variable is used directly, and no conversion
               takes place.</p><p>For the effect of the <code nobreak="false">static</code> attribute, see <specref ref="static-params"/>.</p><p>The <code nobreak="false">visibility</code> attribute <rfc2119>must not</rfc2119>
               be specified for a <termref def="dt-local-variable"/>: that is, it is allowed only when the parent
               element is <elcode>xsl:stylesheet</elcode>, <elcode>xsl:transform</elcode>, 
               <elcode>xsl:package</elcode> or
                  <elcode>xsl:override</elcode>.</p><p>If the <code nobreak="false">visibility</code> attribute is present with the value
                  <code nobreak="false">abstract</code> then the <code nobreak="false">select</code> attribute
                  <rfc2119>must</rfc2119> be absent and the contained <termref def="dt-sequence-constructor"/>
               <rfc2119>must</rfc2119> be empty. In this situation there is no <termref def="dt-supplied-value">supplied value</termref>, and therefore the constraint
               that the supplied value is consistent with the required type does not apply.</p></div2><div2 id="parameters"><head>Parameters</head><e:element-syntax xmlns:e="http://www.w3.org/1999/XSL/Spec/ElementSyntax" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" name="param">
      <e:in-category name="declaration"/>
      <e:attribute name="name" required="yes">
         <e:data-type name="eqname"/>
      </e:attribute>
      <e:attribute name="select">
         <e:data-type name="expression"/>
      </e:attribute>
      <e:attribute name="as">
         <e:data-type name="sequence-type"/>
      </e:attribute>
      <e:attribute name="required">
         <e:data-type name="boolean"/>
      </e:attribute>
      <e:attribute name="tunnel" default="'no'">
         <e:data-type name="boolean"/>
      </e:attribute>
      <e:attribute name="static" default="'no'">
         <e:data-type name="boolean"/>
      </e:attribute>
      <e:model name="sequence-constructor"/>
      <e:allowed-parents>
         <e:parent name="package"/>
         <e:parent name="stylesheet"/>
         <e:parent name="transform"/>
         <e:parent name="override"/>
         <e:parent name="function"/>
         <e:parent name="template"/>
         <e:parent name="iterate"/>
      </e:allowed-parents>
   </e:element-syntax><p>The <elcode>xsl:param</elcode> element may be used:</p><ulist><item><p>As a child of <elcode>xsl:stylesheet</elcode>
                     or <elcode>xsl:package</elcode>, to
                     define a parameter to the transformation. <termref def="dt-stylesheet-parameter">Stylesheet parameters</termref> are set by the
                     calling application: see <specref ref="priming-stylesheet"/>. </p></item><item><p>As a child of <elcode>xsl:template</elcode> to define a parameter to a
                     template, which may be supplied when the template is invoked using
                        <elcode>xsl:call-template</elcode>, <elcode>xsl:apply-templates</elcode>,
                        <elcode>xsl:apply-imports</elcode> or <elcode>xsl:next-match</elcode>.
                        <termref def="dt-template-parameter">Template parameters</termref> are set
                     by means of an <elcode>xsl:with-param</elcode> child element of the invoking
                     instruction, as described in <specref ref="with-param"/>.</p></item><item><p>As a child of <elcode>xsl:function</elcode> to define a parameter to a
                     stylesheet function, which may be supplied when the function is called from an
                     XPath <termref def="dt-expression">expression</termref>. 
                     <termref def="dt-function-parameter">Function parameters</termref> are set
                     <phrase diff="chg" at="variadicity">either positionally or by keyword</phrase>
                     by means of the argument list in an XPath function call. </p></item><item><p>As a child of <elcode>xsl:iterate</elcode> to define a parameter that can vary
                     from one iteration to the next. Iteration parameters always take their default
                     values for the first iteration, and in subsequent iterations are set using an
                        <elcode>xsl:with-param</elcode> child of the
                        <elcode>xsl:next-iteration</elcode> instruction.</p></item></ulist><p>The attributes applicable to <elcode>xsl:param</elcode>
               depend on its parent element in the stylesheet, as defined by the following
               table:</p><table class="data" border="1" cellpadding="5" width="100%"><caption>Attributes of the <code nobreak="false">xsl:param</code> Element</caption><thead><tr><th rowspan="1" colspan="1" align="left" valign="top">Parent Element</th><th rowspan="1" colspan="1" align="left" valign="top">name</th><th rowspan="1" colspan="1" align="left" valign="top">select</th><th rowspan="1" colspan="1" align="left" valign="top">as</th><th rowspan="1" colspan="1" align="left" valign="top">required</th><th rowspan="1" colspan="1" align="left" valign="top">tunnel</th><th rowspan="1" colspan="1" align="left" valign="top">static</th></tr></thead><tbody><tr><th rowspan="1" colspan="1" align="left" valign="top"><elcode>xsl:package</elcode></th><td rowspan="1" colspan="1" align="left" valign="top">mandatory</td><td rowspan="1" colspan="1" align="left" valign="top">optional</td><td rowspan="1" colspan="1" align="left" valign="top">optional</td><td rowspan="1" colspan="1" align="left" valign="top">yes|<term>no</term></td><td rowspan="1" colspan="1" align="left" valign="top"><term>no</term></td><td rowspan="1" colspan="1" align="left" valign="top">yes|<term>no</term></td></tr><tr><th rowspan="1" colspan="1" align="left" valign="top"><elcode>xsl:stylesheet</elcode></th><td rowspan="1" colspan="1" align="left" valign="top">mandatory</td><td rowspan="1" colspan="1" align="left" valign="top">optional</td><td rowspan="1" colspan="1" align="left" valign="top">optional</td><td rowspan="1" colspan="1" align="left" valign="top">yes|<term>no</term></td><td rowspan="1" colspan="1" align="left" valign="top"><term>no</term></td><td rowspan="1" colspan="1" align="left" valign="top">yes|<term>no</term></td></tr><tr><th rowspan="1" colspan="1" align="left" valign="top"><elcode>xsl:template</elcode></th><td rowspan="1" colspan="1" align="left" valign="top">mandatory</td><td rowspan="1" colspan="1" align="left" valign="top">optional</td><td rowspan="1" colspan="1" align="left" valign="top">optional</td><td rowspan="1" colspan="1" align="left" valign="top">yes|<term>no</term></td><td rowspan="1" colspan="1" align="left" valign="top">yes|<term>no</term></td><td rowspan="1" colspan="1" align="left" valign="top"><term>no</term></td></tr><tr><th rowspan="1" colspan="1" align="left" valign="top"><elcode>xsl:function</elcode></th><td rowspan="1" colspan="1" align="left" valign="top">mandatory</td><td rowspan="1" colspan="1" align="left" valign="top">optional</td><td rowspan="1" colspan="1" align="left" valign="top">optional</td><td rowspan="1" colspan="1" diff="chg" at="variadicity" align="left" valign="top"><term>yes</term>|no</td><td rowspan="1" colspan="1" align="left" valign="top"><term>no</term></td><td rowspan="1" colspan="1" align="left" valign="top"><term>no</term></td></tr><tr><th rowspan="1" colspan="1" align="left" valign="top"><elcode>xsl:iterate</elcode></th><td rowspan="1" colspan="1" align="left" valign="top">mandatory</td><td rowspan="1" colspan="1" align="left" valign="top">mandatory</td><td rowspan="1" colspan="1" align="left" valign="top">optional</td><td rowspan="1" colspan="1" align="left" valign="top"><term>no</term></td><td rowspan="1" colspan="1" align="left" valign="top"><term>no</term></td><td rowspan="1" colspan="1" align="left" valign="top"><term>no</term></td></tr></tbody></table><p>In the table, the entries for the <code nobreak="false">name</code>,
                  <code nobreak="false">select</code>, and <code nobreak="false">as</code> attributes indicate whether the attribute
               must appear, is optional, or must be absent; the entries for the
                  <code nobreak="false">required</code>, <code nobreak="false">tunnel</code>, and <code nobreak="false">static</code> attributes
               indicate the values that are permitted if the attribute is present, with the default
               value shown in bold. (The value <code nobreak="false">yes</code> can also be written
                  <code nobreak="false">true</code> or <code nobreak="false">1</code>, while <code nobreak="false">no</code> can also be written
                  <code nobreak="false">false</code> or <code nobreak="false">0</code>.)</p><p>The <code nobreak="false">name</code> attribute is mandatory: it specifies the name of the parameter.
               The value of the <code nobreak="false">name</code> attribute is an <termref def="dt-eqname">EQName</termref>, which is expanded as described in
                  <specref ref="qname"/>.</p><p>
               <error spec="XT" type="static" class="SE" code="0580"><p>It is a <termref def="dt-static-error">static error</termref> if the values of
                     the <code nobreak="false">name</code> attribute of two sibling
                           <elcode>xsl:param</elcode> elements represent the same <termref def="dt-expanded-qname">expanded QName</termref>.</p></error>
            </p><p>If the <elcode>xsl:param</elcode> element has a <code nobreak="false">select</code> attribute, then
               the sequence constructor <rfc2119>must</rfc2119> be empty.</p><p>The <code nobreak="false">static</code> attribute can take the value <code nobreak="false">yes</code> only on <termref def="dt-stylesheet-parameter">stylesheet parameters</termref>, and is explained in
                  <specref ref="global-variables"/>.</p><note><p>Local variables may <termref def="dt-shadows">shadow</termref> template parameters
                  and function parameters: see <specref ref="scope-of-variables"/>.</p></note><p>The optional <code nobreak="false">tunnel</code> attribute may be used to indicate that a parameter
               is a <termref def="dt-tunnel-parameter">tunnel parameter</termref>. The default is
                  <code nobreak="false">no</code>; the value <code nobreak="false">yes</code> may be specified only for <termref def="dt-template-parameter">template parameters</termref>. Tunnel parameters are
               described in <specref ref="tunnel-params"/>
            </p><div3 id="parameter-type"><head>The Required Type of a Parameter</head><p>The <elcode>xsl:param</elcode> element has an optional <code nobreak="false">as</code> attribute,
                  which specifies the <termref def="dt-required-type"/> of the parameter. The value
                  of the <code nobreak="false">as</code> attribute is a 
                  <termref def="dt-sequence-type"/>. 
                  If the <code nobreak="false">as</code> attribute is omitted, then the
                  required type is <code nobreak="false">item()*</code>.</p><p>The <termref def="dt-supplied-value">supplied value</termref> of the parameter is
                  the value supplied by the caller. If no value was supplied by the caller, and if
                  the parameter is not mandatory, then the default value is used as the supplied
                  value as described in <specref ref="default-values-of-parameters"/>.</p><p>The <termref def="dt-supplied-value">supplied value</termref> of the parameter is
                  converted to the <termref def="dt-required-type"/> using the <termref def="dt-coercion-rules"/>.</p><p diff="chg" at="2022-01-01">
                  <error spec="XT" type="type" class="TE" code="0590"><p>It is a <termref def="dt-type-error">type error</termref> if the conversion
                        of the <termref def="dt-supplied-value">supplied value</termref> of a
                        parameter, or of the context item, does not match the <termref def="dt-required-type"/>,
                        after applying any permitted conversions.</p></error>
               </p><p>For example, the following declares a parameter that requires the supplied
               value (after atomization) to be either a QName, or the string <code nobreak="false">"*"</code>, 
                  or the empty sequence:</p><eg xml:space="preserve">&lt;xsl:param name="n" as="(xs:QName | enum('*'))?"/&gt;</eg></div3><div3 id="default-values-of-parameters"><head>Default Values of Parameters</head><changes><change issue="155" PR="159" date="2022-09-30">Parameters on functions
                     declared using <elcode>xsl:function</elcode> can now be defined as optional,
                     with a default value supplied.</change></changes><p>The optional <code nobreak="false">required</code> attribute of
                     <elcode>xsl:param</elcode> may be used to indicate whether a <termref def="dt-stylesheet-parameter"/>, 
                  <termref def="dt-template-parameter"/><phrase diff="add" at="2022-01-01">, or <termref def="dt-function-parameter"/></phrase> is
                  mandatory or optional. The only value <phrase diff="del" at="2022-01-01">permitted for a <termref def="dt-function-parameter"/>
                  is <code nobreak="false">yes</code> (these are always mandatory), and the only value</phrase> permitted for
                  a parameter to <elcode>xsl:iterate</elcode> is <code nobreak="false">no</code> (these are always
                  initialized to a default value).</p><p diff="add" at="2022-01-01">The default value for a <termref def="dt-function-parameter"/> is <code nobreak="false">required="yes"</code>; in all
               other cases it is <code nobreak="false">required="no"</code>.</p><p><termdef id="dt-explicitly-mandatory" term="explicitly mandatory">A parameter is
                        <term>explicitly mandatory</term> if it is a 
                  <termref def="dt-function-parameter">function parameter</termref> 
                  <phrase diff="add" at="2022-01-01">with no <code nobreak="false">required</code> attribute</phrase>, or if the
                        <code nobreak="false">required</code> attribute is present and has the value
                        <code nobreak="false">yes</code>.</termdef> If a parameter is explicitly mandatory, then the
                     <elcode>xsl:param</elcode> element <rfc2119>must</rfc2119> be empty and
                     <rfc2119>must not</rfc2119> have a <code nobreak="false">select</code> attribute.</p><p diff="add" at="2022-01-01">The static context for evaluating the default value depends on where the
               relevant expression appears in the stylesheet, in the usual way. Note however that
               for <elcode>xsl:param</elcode> elements defining <termref def="dt-function-parameter">function parameters</termref>,
                  the static context does not include variables bound in preceding-sibling <elcode>xsl:param</elcode> elements.</p><p diff="add" at="2022-01-01">The dynamic context is different for different kinds of parameter:</p><ulist diff="add" at="2022-01-01"><item><p>For <termref def="dt-stylesheet-parameter">stylesheet parameters</termref>, the 
                  context is the same as the context for evaluating global variables.</p></item><item><p>For <termref def="dt-template-parameter">template parameters</termref>, the 
                     context is that of the called template. This means that the evaluation of the
                  default has access to the other parameters supplied in the call, provided they are declared
                  earlier. It also means, for example, that if the evaluation of the default value invokes
                  <elcode>xsl:next-match</elcode>, the <termref def="dt-current-template-rule"/> is the called
                  template rather than the calling template.</p></item><item><p>For <termref def="dt-function-parameter">function parameters</termref>, the dynamic
                     context for evaluating defaults is the dynamic context of the caller, except that no
                     local variables are in scope. This means that it is possible to declare a parameter
                     with <code nobreak="false">&lt;xsl:param name="dot" required="no" select="."/&gt;</code> to take its
                     default value from the context item of the caller.
                     
              </p></item></ulist><p>If a parameter is not <termref def="dt-explicitly-mandatory"/>, then it may have a
                  default value. The default value is obtained by evaluating the <termref def="dt-expression">expression</termref> given in the <code nobreak="false">select</code>
                  attribute or the contained <termref def="dt-sequence-constructor">sequence
                     constructor</termref>, as described in <specref ref="variable-values"/>.</p><note><p>This specification does not dictate whether and when the default value of a
                     parameter is evaluated. For example, if the default is specified as
                        <code nobreak="false">&lt;xsl:param name="p"&gt;&lt;foo/&gt;&lt;/xsl:param&gt;</code>, then
                     it is not specified whether a distinct <code nobreak="false">foo</code> element node will be
                     created on each invocation of the template, or whether the same
                        <code nobreak="false">foo</code> element node will be used for each invocation. However, it
                     is permissible for the default value to depend on the values of other
                     parameters, or on the evaluation context, in which case the default must
                     effectively be evaluated on each invocation.</p></note><p><termdef id="dt-explicit-default" term="explicit default">An <term>explicit
                        default</term> for a parameter is indicated by the presence of either a
                        <code nobreak="false">select</code> attribute or a non-empty sequence
                  constructor.</termdef></p><p><termdef id="dt-implicit-default" term="implicit default">If a parameter that is
                     not <termref def="dt-explicitly-mandatory"/> has no <termref def="dt-explicit-default"/> value, then it has an <term>implicit
                        default</term> value, which is the empty sequence if there is an
                        <code nobreak="false">as</code> attribute, or a zero-length string if not.</termdef></p><p><termdef id="dt-implicitly-mandatory" term="implicitly mandatory">If a parameter
                     has an <termref def="dt-implicit-default"/> value which cannot be converted to
                     the <termref def="dt-required-type"/> (that is, if it has an <code nobreak="false">as</code>
                     attribute which does not permit the empty sequence), then the parameter is
                        <term>implicitly mandatory</term>.</termdef></p><note><p>The effect of these rules is that specifying <code nobreak="false">&lt;xsl:param name="p"
                        as="xs:date" select="2"/&gt;</code> is an error, but if the default value of
                     the parameter is never used, then the processor has discretion whether or not
                     to raise the error. By contrast, <code nobreak="false">&lt;xsl:param name="p"
                        as="xs:date"/&gt;</code> is treated as if <code nobreak="false">required="yes"</code> had
                     been specified: the empty sequence is not a valid instance of
                        <code nobreak="false">xs:date</code>, so in effect there is no default value and the
                     parameter is therefore treated as being mandatory.</p></note><p>Various errors can arise with regard to mandatory parameters when no value is
                  supplied. In the rules below, <term>non-tunnel</term> means: not having a
                     <code nobreak="false">tunnel</code> attribute with the value <code nobreak="false">yes</code>.</p><ulist><item><p>
                        <error spec="XT" type="static" class="SE" code="3520"><p>It is a static error if a parameter to <elcode>xsl:iterate</elcode> is
                                 <termref def="dt-implicitly-mandatory"/>.</p></error>
                     </p></item><item><p>
                        <error spec="XT" type="static" class="SE" code="0690"><p>It is a <termref def="dt-static-error">static error</termref> if a
                                 <termref def="dt-package">package</termref> contains both (a) a
                              named template named <var>T</var> that is not overridden by another
                              named template of higher import precedence and that has an <termref def="dt-explicitly-mandatory"/> non-tunnel parameter named
                                 <var>P</var>, and (b) an <elcode>xsl:call-template</elcode>
                              instruction whose <code nobreak="false">name</code> attribute equals <var>T</var> and
                              that has no non-tunnel <elcode>xsl:with-param</elcode> child element
                              whose <code nobreak="false">name</code> attribute equals <var>P</var>. (All names are
                              compared as QNames.)</p></error>
                     </p></item><item><p>
                        <error spec="XT" type="dynamic" class="DE" code="0700"><p>It is a <termref def="dt-dynamic-error"> dynamic error</termref> if a template
                              that has an <termref def="dt-explicitly-mandatory"/> or <termref def="dt-implicitly-mandatory"/> parameter is invoked without
                              supplying a value for that parameter.</p></error>
                     </p><p>This includes the following cases:</p><ulist><item><p>The template is invoked using <elcode>xsl:apply-templates</elcode>,
                                 <elcode>xsl:apply-imports</elcode>, or
                                 <elcode>xsl:next-match</elcode> and there is no
                                 <elcode>xsl:with-param</elcode> child whose <code nobreak="false">name</code> and
                                 <code nobreak="false">tunnel</code> attributes match the corresponding attributes
                              of the mandatory parameter.</p></item><item><p>The mandatory parameter is a tunnel parameter, and the template is
                              invoked using <elcode>xsl:call-template</elcode>, and there is no
                                 <elcode>xsl:with-param</elcode> child whose <code nobreak="false">name</code> and
                                 <code nobreak="false">tunnel</code> attributes match the corresponding attributes
                              of the mandatory parameter.</p></item><item><p>The template is invoked as the entry point to the transformation,
                              either by invoking an initial mode (<specref ref="invoking-initial-mode"/>) or by invoking an initial template
                                 (<specref ref="invoking-initial-template"/>) and no value is
                              supplied for the mandatory parameter by the calling application.</p></item></ulist></item></ulist></div3></div2><div2 id="variable-values"><head>Values of Variables and Parameters</head><changes><change issue="2009 2288" PR="2015 2296" date="2025-05-20">
                  A variable-binding with no <code nobreak="false">as</code> or <code nobreak="false">select</code> attribute no longer
                  attempts to create an implicit document node if the sequence constructor contains
                  certain instructions (such as <elcode>xsl:map</elcode>, <elcode>xsl:array</elcode>, 
                  <elcode>xsl:record</elcode>, and <elcode>xsl:select</elcode>).
               </change></changes><p>A <termref def="dt-variable-binding-element">variable-binding element</termref> may
               specify the <termref def="dt-supplied-value">supplied value</termref> of a <termref def="dt-variable">variable</termref>
               or the default value of a
               <termref def="dt-parameter">parameter</termref> in four different ways.</p><ulist><item><p>If the <termref def="dt-variable-binding-element">variable-binding
                        element</termref> has a <code nobreak="false">select</code> attribute, then the value of the
                     attribute <rfc2119>must</rfc2119> be an <termref def="dt-expression">expression</termref> and the <termref def="dt-supplied-value">supplied
                        value</termref> of the variable is the value that results from evaluating
                     the expression. In this case, the content of the variable-binding element
                        <rfc2119>must</rfc2119> be empty.</p></item><item><p>If the <termref def="dt-variable-binding-element">variable-binding
                        element</termref> has empty content and has neither a <code nobreak="false">select</code>
                     attribute nor an <code nobreak="false">as</code> attribute, then the <termref def="dt-supplied-value">supplied value</termref> of the variable is a
                     zero-length string. Thus</p><eg xml:space="preserve" role="xslt-declaration">&lt;xsl:variable name="x"/&gt;</eg><p>is equivalent to</p><eg xml:space="preserve" role="xslt-declaration">&lt;xsl:variable name="x" select="''"/&gt;</eg></item><item><p>If a <termref def="dt-variable-binding-element">variable-binding
                        element</termref> satisfies all the following conditions:</p><ulist><item><p>The element has no <code nobreak="false">select</code> attribute</p></item><item><p>The element has no <code nobreak="false">as</code> attribute</p></item><item><p>The element has non-empty content (that is, the variable-binding element 
                           has one or more child nodes)</p></item><item><p>There is no <termref def="dt-disqualifying-element"/> among the element's 
                           children.</p></item></ulist><p>then the content of the variable-binding
                     element specifies the <termref def="dt-supplied-value">supplied
                     value</termref>. The content of the variable-binding element is a 
                     <termref def="dt-sequence-constructor">sequence constructor</termref>; a new document
                     is constructed with a document node having as its children the sequence of
                     nodes that results from evaluating the sequence constructor and then applying
                     the rules given in <specref ref="constructing-complex-content"/>. The value of
                     the variable is then a singleton sequence containing this document node. For
                     further details, see <specref ref="temporary-trees"/>. </p></item><item><p>Otherwise, the <termref def="dt-supplied-value">supplied value</termref> 
                     is the sequence that results from evaluating the
                     (possibly empty) <termref def="dt-sequence-constructor">sequence
                        constructor</termref> contained within the variable-binding element (see
                        <specref ref="sequence-constructors"/>). </p></item></ulist><p>These combinations are summarized in the table below.</p><table class="data" border="1" cellpadding="5" width="100%"><caption>Effect of Different Attribute Combinations on <code nobreak="false">xsl:variable</code></caption><col width="12%" span="1"/><col width="12%" span="1"/><col width="12%" span="1"/><col span="1"/><thead><tr><th align="left" rowspan="1" colspan="1" valign="top">select attribute</th><th align="left" rowspan="1" colspan="1" valign="top">as attribute</th><th align="left" rowspan="1" colspan="1" valign="top">content</th><th align="left" rowspan="1" colspan="1" valign="top">Effect</th></tr></thead><tbody><tr><td rowspan="1" colspan="1" align="left" valign="top">present</td><td rowspan="1" colspan="1" align="left" valign="top">absent</td><td rowspan="1" colspan="1" align="left" valign="top">empty</td><td rowspan="1" colspan="1" align="left" valign="top">Value is obtained by evaluating the <code nobreak="false">select</code>
                        attribute</td></tr><tr><td rowspan="1" colspan="1" align="left" valign="top">present</td><td rowspan="1" colspan="1" align="left" valign="top">present</td><td rowspan="1" colspan="1" align="left" valign="top">empty</td><td rowspan="1" colspan="1" align="left" valign="top">Value is obtained by evaluating the <code nobreak="false">select</code>
                        attribute, coerced to the type required by the <code nobreak="false">as</code>
                        attribute</td></tr><tr><td rowspan="1" colspan="1" align="left" valign="top">present</td><td rowspan="1" colspan="1" align="left" valign="top">absent</td><td rowspan="1" colspan="1" align="left" valign="top">present</td><td rowspan="1" colspan="1" align="left" valign="top">Static error</td></tr><tr><td rowspan="1" colspan="1" align="left" valign="top">present</td><td rowspan="1" colspan="1" align="left" valign="top">present</td><td rowspan="1" colspan="1" align="left" valign="top">present</td><td rowspan="1" colspan="1" align="left" valign="top">Static error</td></tr><tr><td rowspan="1" colspan="1" align="left" valign="top">absent</td><td rowspan="1" colspan="1" align="left" valign="top">absent</td><td rowspan="1" colspan="1" align="left" valign="top">empty</td><td rowspan="1" colspan="1" align="left" valign="top">Value is a zero-length string</td></tr><tr><td rowspan="1" colspan="1" align="left" valign="top">absent</td><td rowspan="1" colspan="1" align="left" valign="top">present</td><td rowspan="1" colspan="1" align="left" valign="top">empty</td><td rowspan="1" colspan="1" align="left" valign="top">Value is the empty sequence, provided the <code nobreak="false">as</code>
                        attribute permits the empty sequence</td></tr><tr><td rowspan="1" colspan="1" align="left" valign="top">absent</td><td rowspan="1" colspan="1" align="left" valign="top">absent</td><td rowspan="1" colspan="1" align="left" valign="top">includes a <termref def="dt-disqualifying-element"/></td><td rowspan="1" colspan="1" align="left" valign="top">Value is obtained by evaluating the sequence constructor</td></tr><tr><td rowspan="1" colspan="1" align="left" valign="top">absent</td><td rowspan="1" colspan="1" align="left" valign="top">absent</td><td rowspan="1" colspan="1" align="left" valign="top">present and does not include a <termref def="dt-disqualifying-element"/></td><td rowspan="1" colspan="1" align="left" valign="top">Value is a document node whose content is obtained by
                        evaluating the sequence constructor</td></tr><tr><td rowspan="1" colspan="1" align="left" valign="top">absent</td><td rowspan="1" colspan="1" align="left" valign="top">present</td><td rowspan="1" colspan="1" align="left" valign="top">present</td><td rowspan="1" colspan="1" align="left" valign="top">Value is obtained by evaluating the sequence constructor,
                        coerced to the type required by the <code nobreak="false">as</code> attribute</td></tr></tbody></table><p>
               <error spec="XT" type="static" class="SE" code="0620"><p>It is a <termref def="dt-static-error">static error</termref> 
                     if a <termref def="dt-variable-binding-element">variable-binding element</termref> has a
                        <code nobreak="false">select</code> attribute and has non-empty content.</p></error>
            </p><example><head>Values of Variables</head><p>The value of the following variable is the sequence of integers (1, 2, 3):</p><eg xml:space="preserve" role="xslt-declaration">&lt;xsl:variable name="i" as="xs:integer*" select="1 to 3"/&gt;</eg><p>The value of the following variable is an integer, assuming that the attribute
                     <code nobreak="false">@size</code> exists, and is annotated either as an integer, or as
                     <code nobreak="false">xs:untypedAtomic</code>:</p><eg xml:space="preserve" role="xslt-declaration">&lt;xsl:variable name="i" as="xs:integer" select="@size"/&gt;</eg><p>The value of the following variable is a zero-length string:</p><eg xml:space="preserve" role="xslt-declaration">&lt;xsl:variable name="z"/&gt;</eg><p>The value of the following variable is a document node containing an empty element
                  as a child:</p><eg xml:space="preserve" role="xslt-declaration">&lt;xsl:variable name="doc"&gt;&lt;c/&gt;&lt;/xsl:variable&gt;</eg><p>The value of the following variable is a sequence of integers (2, 4, 6):</p><eg xml:space="preserve" role="xslt-declaration">&lt;xsl:variable name="seq" as="xs:integer*"&gt;
  &lt;xsl:for-each select="1 to 3"&gt;
    &lt;xsl:sequence select=".*2"/&gt;
  &lt;/xsl:for-each&gt;
&lt;/xsl:variable&gt;</eg><p>The value of the following variable is a sequence of parentless attribute
                  nodes:</p><eg xml:space="preserve" role="xslt-declaration">&lt;xsl:variable name="attset" as="attribute()+"&gt;
  &lt;xsl:attribute name="x"&gt;2&lt;/xsl:attribute&gt;
  &lt;xsl:attribute name="y"&gt;3&lt;/xsl:attribute&gt;
  &lt;xsl:attribute name="z"&gt;4&lt;/xsl:attribute&gt;    
&lt;/xsl:variable&gt;</eg><p>The value of the following variable is the empty sequence:</p><eg xml:space="preserve" role="xslt-declaration">&lt;xsl:variable name="empty" as="empty-sequence()"/&gt;</eg></example><p>The actual value of the variable depends on the <termref def="dt-supplied-value">supplied value</termref>, as described above, and the required type, which is
               determined by the value of the <code nobreak="false">as</code> attribute.</p><example><head>Pitfalls with Numeric Predicates</head><p>When a variable is used to select nodes by position, be careful not to do:</p><eg xml:space="preserve" role="xslt-instruction">&lt;xsl:variable name="n"&gt;2&lt;/xsl:variable&gt;
...
&lt;xsl:value-of select="td[$n]"/&gt;</eg><p>This will output the values of all the <code nobreak="false">td</code> elements, space-separated
                  (or with <termref def="dt-xslt-10-behavior">XSLT 1.0
                        behavior</termref>, the value of the first <code nobreak="false">td</code>
                  element), because the variable <code nobreak="false">n</code> will be bound to a node, not a
                  number. Instead, do one of the following:</p><eg xml:space="preserve" role="xslt-instruction">&lt;xsl:variable name="n" select="2"/&gt;
...
&lt;xsl:value-of select="td[$n]"/&gt;</eg><p>or</p><eg xml:space="preserve" role="xslt-instruction">&lt;xsl:variable name="n"&gt;2&lt;/xsl:variable&gt;
...
&lt;xsl:value-of select="td[position()=$n]"/&gt;</eg><p>or</p><eg xml:space="preserve" role="xslt-instruction">&lt;xsl:variable name="n" as="xs:integer"&gt;2&lt;/xsl:variable&gt;
...
&lt;xsl:value-of select="td[$n]"/&gt;</eg></example></div2><div2 id="temporary-trees"><head>Creating Implicit Document Nodes</head><p>A document node is created implicitly when evaluating an
                  <elcode>xsl:variable</elcode>, <elcode>xsl:param</elcode>, or
                  <elcode>xsl:with-param</elcode> element that has non-empty content and that has no
                  <code nobreak="false">as</code> attribute, unless the children of this element include
               a <termref def="dt-disqualifying-element"/>. 
               The value of the <termref def="dt-variable">variable</termref> is this newly constructed
                  document node.
                The content of the
               document node is formed from the result of evaluating the <termref def="dt-sequence-constructor">sequence constructor</termref> contained within the
               variable-binding element, as described in <specref ref="constructing-complex-content"/>. </p><p><termdef id="dt-disqualifying-element" term="disqualifying element">The <term>disqualifying elements</term>
            are <elcode>xsl:map</elcode>, <elcode>xsl:map-entry</elcode>, <elcode>xsl:array</elcode>, 
            <elcode>xsl:array-member</elcode>, <elcode>xsl:record</elcode>, and <elcode>xsl:select</elcode>. If a sequence
            constructor includes one of these elements, then construction of the implicit document node does
            not take place.</termdef></p><note><p>Most of the disqualifying elements return maps or arrays, and wrapping a map or array
            in a document node makes no sense. For <elcode>xsl:select</elcode>, the justification is that
            this instruction should be as closely as possible an equivalent to the <code nobreak="false">select</code>
            attribute on the containing <elcode>xsl:variable</elcode> or <elcode>xsl:param</elcode> element.</p></note><note><p>The construct:</p><eg xml:space="preserve" role="xslt-declaration">&lt;xsl:variable name="tree"&gt;
  &lt;a/&gt;
&lt;/xsl:variable&gt;</eg><p>can be regarded as a shorthand for:</p><eg xml:space="preserve" role="xslt-declaration">&lt;xsl:variable name="tree" as="document-node()"&gt;
  &lt;xsl:document validation="preserve"&gt;
    &lt;a/&gt;
  &lt;/xsl:document&gt;  
&lt;/xsl:variable&gt;</eg></note><p>The base URI of the document node is taken from the base URI of the variable binding
               element in the stylesheet. (See <xspecref spec="DM40" ref="dm-base-uri"/>)</p><p>No document-level validation takes place (which means, for example, that there is no
               checking that ID values are unique). However, <termref def="dt-type-annotation">type
                  annotations</termref> on nodes within the new tree are copied unchanged.</p><note><p>The base URI of other nodes in the tree is determined by the rules for
                  constructing complex content (see <specref ref="constructing-complex-content"/>).
                  The effect of these rules is that the base URI of a node in the temporary tree is
                  determined as if all the nodes in the temporary tree came from a single entity
                  whose URI was the base URI of the <termref def="dt-variable-binding-element">variable-binding element</termref>. Thus, the base URI of the document node
                  will be equal to the base URI of the variable-binding element, while an
                     <code nobreak="false">xml:base</code> attribute within the temporary tree will change the base
                  URI for its parent element and that element’s descendants, just as it would
                  within a document constructed by parsing.</p></note><p>The <code nobreak="false">document-uri</code> and <code nobreak="false">unparsed-entities</code> properties of the
               new document node are set to empty.</p><p>A <termref def="dt-temporary-tree">temporary tree</termref> is available for
               processing in exactly the same way as any source document. For example, its nodes are
               accessible using path expressions, and they can be processed using instructions such
               as <elcode>xsl:apply-templates</elcode> and <elcode>xsl:for-each</elcode>. Also, the
                  <function>key</function> and <xfunction>id</xfunction> functions can be used to
               find nodes within a temporary tree,  by supplying the
                  document node at the root of the tree as an argument to the function or by making
                  it the context node.</p><example><head>Two-Phase Transformation</head><p>The following stylesheet uses a temporary tree as the intermediate
                  result of a two-phase transformation, using different <termref def="dt-mode">modes</termref> for the two phases (see <specref ref="modes"/>). Typically,
                  the template rules in module <code nobreak="false">phase1.xsl</code> will be declared with
                     <code nobreak="false">mode="phase1"</code>, while those in module <code nobreak="false">phase2.xsl</code> will
                  be declared with <code nobreak="false">mode="phase2"</code>: </p><eg xml:space="preserve" role="xslt-document">&lt;xsl:stylesheet
  version="3.0"
  xmlns:xsl="http://www.w3.org/1999/XSL/Transform"&gt;

&lt;xsl:import href="phase1.xsl"/&gt;
&lt;xsl:import href="phase2.xsl"/&gt;

&lt;xsl:variable name="intermediate"&gt;
  &lt;xsl:apply-templates select="/" mode="phase1"/&gt;
&lt;/xsl:variable&gt;

&lt;xsl:template match="/"&gt;
  &lt;xsl:apply-templates select="$intermediate" mode="phase2"/&gt;
&lt;/xsl:template&gt;

&lt;/xsl:stylesheet&gt;</eg></example><note><p>The algorithm for matching nodes against template rules is exactly the same
                  regardless which tree the nodes come from. If different template rules are to be
                  used when processing different trees, then unless nodes from different trees can
                  be distinguished by means of <termref def="dt-pattern">patterns</termref>, it is a
                  good idea to use <termref def="dt-mode">modes</termref> to ensure that each tree
                  is processed using the appropriate set of template rules.</p></note></div2><div2 id="global-variables"><head>Global Variables and Parameters</head><changes><change issue="1540" PR="1544" date="2024-11-12">
                  It is no longer an intrinsic error for a global variable to refer to itself; this
                  is now permitted, for example in cases where the value of the global variable is
                  a recursive inline function. Cases where self-reference would not make sense are
                  covered by the existing rules on circularities: see <specref ref="circularity"/>.
               </change></changes><p>Both <elcode>xsl:variable</elcode> and <elcode>xsl:param</elcode> are allowed as
                  <termref def="dt-declaration">declaration</termref> elements: that is, they may
               appear as children of the <elcode>xsl:package</elcode> or
               <elcode>xsl:stylesheet</elcode> element.</p><p>
               <termdef id="dt-global-variable" term="global variable">A <termref def="dt-top-level"/> <termref def="dt-variable-binding-element">variable-binding element</termref> declares a
                     <term>global variable</term> that is visible everywhere 
                  except within any region where it is <termref def="dt-shadows">shadowed</termref> 
                     by another variable binding.</termdef>
            </p><p>
               <termdef id="dt-stylesheet-parameter" term="stylesheet parameter">A <termref def="dt-top-level"/>
                     <elcode>xsl:param</elcode> element declares a <term>stylesheet
                  parameter</term>. A stylesheet parameter is a global variable with the additional
                  property that its value can be supplied by the caller when a transformation is
                  initiated.</termdef> As described in <specref ref="parameters"/>, a stylesheet
               parameter may be declared as being mandatory, or may have a default value specified
               for use when no value is supplied by the caller. The mechanism by which the caller
               supplies a value for a stylesheet parameter is <termref def="dt-implementation-defined">implementation-defined</termref>. An XSLT <termref def="dt-processor">processor</termref>
               <rfc2119>must</rfc2119> provide such a mechanism.</p><imp-def-feature id="idf-api-params">The mechanism by which the caller supplies a value
               for a <termref def="dt-stylesheet-parameter"/> is <termref def="dt-implementation-defined">implementation-defined</termref>.</imp-def-feature><p>It is an error if no value is supplied for a mandatory stylesheet parameter <errorref spec="XT" class="DE" code="0050"/>.</p><p>If a <termref def="dt-stylesheet">stylesheet</termref> contains more than one binding
               for a global variable of a particular name, then the binding with the highest
                  <termref def="dt-import-precedence">import precedence</termref> is used.</p><p>
               <error spec="XT" type="static" class="SE" code="0630"><p>It is a <termref def="dt-static-error">static error</termref> if a <termref def="dt-package">package</termref> contains more
                     than one non-hidden binding of a global
                     variable with the same name and same <termref def="dt-import-precedence">import
                        precedence</termref>, unless it also contains another binding with the same
                     name and higher import precedence.</p></error>
            </p><p>For a global variable or the default value of a stylesheet parameter, the <termref def="dt-expression">expression</termref> or <termref def="dt-sequence-constructor">sequence constructor</termref> specifying the variable value is evaluated with a
                  <termref def="dt-singleton-focus">singleton focus</termref> as follows:</p><ulist><item><p>If the declaration appears within the <termref def="dt-top-level-package"/>
                     (including within an <elcode>xsl:override</elcode> element in the top-level
                     package), then the focus is based on the <termref def="dt-global-context-item"/> if supplied, or <termref def="dt-absent"/> otherwise.</p></item><item><p>If the declaration appears within a <termref def="dt-library-package"/>, then the focus is <termref def="dt-absent"/>.</p></item></ulist><p>An XPath error will be raised if the evaluation of a global variable or parameter
               references the context item, context position, or context size when the <termref def="dt-focus"/> is <termref def="dt-absent"/>. The values of other components of
               the dynamic context are the initial values as defined in <specref ref="xpath-dynamic-context"/> and <specref ref="additional-dynamic-context"/>.</p><p>The <termref def="dt-visibility"/> of a <termref def="dt-stylesheet-parameter"/> 
               is always (implicitly) <code nobreak="false">private</code>.</p><note><p>This rule has the effect that the names of <termref def="dt-stylesheet-parameter">stylesheet parameters</termref>
                  defined in different packages within a single <termref def="dt-stylesheet"/> do not necessarily have
                  distinct names. The design of an API for invoking the transformation must take this into account.</p></note><p>For the effect of the <code nobreak="false">static</code> attribute, see <specref ref="static-params"/>.</p><p>The <code nobreak="false">visibility</code> attribute <rfc2119>must
                  not</rfc2119> be specified for a local variable: that is, it is allowed only when
               the parent element is <elcode>xsl:package</elcode>, <elcode>xsl:stylesheet</elcode>,
                  <elcode>xsl:transform</elcode>, or <elcode>xsl:override</elcode>.</p><p>If the <code nobreak="false">visibility</code> attribute is present with the value
                  <code nobreak="false">abstract</code> then the <code nobreak="false">select</code> attribute
                  <rfc2119>must</rfc2119> be absent and the contained <termref def="dt-sequence-constructor"/>
               <rfc2119>must</rfc2119> be empty. In this situation there is no <termref def="dt-supplied-value">supplied value</termref>, and therefore the constraint
               that the supplied value is consistent with the required type does not apply.</p><example><head>A Stylesheet Parameter</head><p>The following example declares a global parameter <code nobreak="false">para-font-size</code>,
                  which is referenced in an <termref def="dt-attribute-value-template">attribute
                     value template</termref>.</p><eg xml:space="preserve" role="xslt-declaration xmlns:fo='fo'">&lt;xsl:param name="para-font-size" as="xs:string"&gt;12pt&lt;/xsl:param&gt;

&lt;xsl:template match="para"&gt;
 &lt;fo:block font-size="{ $para-font-size }"&gt;
   &lt;xsl:apply-templates/&gt;
 &lt;/fo:block&gt;
&lt;/xsl:template&gt;
</eg><p>The implementation must provide a mechanism allowing the user to supply a value
                  for the parameter <code nobreak="false">para-font-size</code> when invoking the stylesheet; the
                  value <code nobreak="false">12pt</code> acts as a default.</p></example><note><p>In XSLT 4.0, a global variable is in scope within its own definition. Trivial
               self-references such as <code nobreak="false">&lt;xsl:variable name="x" select="$x+1"/&gt;</code> are
               prevented by the general rules on circularities: see <specref ref="circularity"/>.
               However, there are other cases where self-reference makes perfect sense. The obvious
               example is where the value of the variable is a recursive inline function, such as:</p><eg xml:space="preserve">
 &lt;xsl:variable name="max-depth" 
    select="fn($node as node()) {
              if (has-children($node)) 
              then 1 + max($node/* ! $max-depth(.))
              else 0}"/&gt;                 
</eg></note></div2><div2 id="static-params"><head>Static Variables and Parameters</head><p>Static variables and parameters are global variables and can be used in the same way
               as other global variables. In addition, they can be used in
                  <code nobreak="false">[xsl:]use-when</code> expressions and in shadow attributes.</p><p>
               <termdef id="dt-static-variable" term="static variable">A <termref def="dt-top-level"/>
                  <termref def="dt-variable-binding-element">variable-binding element</termref>
                  having the attribute <code nobreak="false">static="yes"</code> declares a <term>static
                     variable</term>: that is, a <termref def="dt-global-variable"/> whose value is
                  known during static analysis of the stylesheet.</termdef>
            </p><p>
               <termdef id="dt-static-parameter" term="static parameter">A <termref def="dt-static-variable"/> declared using an <elcode>xsl:param</elcode> element
                  is referred to as a <term>static parameter</term>.</termdef>
            </p><p>The <code nobreak="false">static</code> attribute <rfc2119>must not</rfc2119>
               take the value <code nobreak="false">yes</code> on an
                  <elcode>xsl:variable</elcode> or <elcode>xsl:param</elcode> element unless it is a
                  <termref def="dt-top-level"/> element.</p><p>When the <code nobreak="false">static</code> attribute is present with the value
                  <code nobreak="false">yes</code>, the <code nobreak="false">visibility</code> attribute <rfc2119>must
                  not</rfc2119> have a value other than <code nobreak="false">private</code>.</p><note><p>This rule prevents static variables being overridden in another package. Since the
                  values of such variables may be used at compile time (for example, during
                  processing of <code nobreak="false">[xsl:]use-when</code> expressions), the rule is necessary to
                  ensure that packages can be independently compiled.</p><p>It is possible to make the value of a static variable
                  or parameter available in a using package by binding a non-static public variable
                  to its value, for example:</p><eg role="xslt-declaration" xml:space="preserve">
     &lt;xsl:param name="DEBUG" static="yes" select="true()"/&gt;
     &lt;xsl:variable name="tracing" static="no" visibility="public" select="$DEBUG"/&gt;</eg></note><p>When the attribute <code nobreak="false">static="yes"</code> is specified, the
                  <elcode>xsl:variable</elcode> or <elcode>xsl:param</elcode> element
                  <rfc2119>must</rfc2119> have empty content. In the case of
                  <elcode>xsl:variable</elcode> the <code nobreak="false">select</code> attribute must be present to
               define the value of the variable <errorref spec="XT" class="SE" code="0010"/>.</p><p>If the <code nobreak="false">select</code> attribute is present, then it is evaluated using the rules
               for <termref def="dt-static-expression">static expressions</termref>.</p><p>The rules for the scope of static variables, and the
               handling of duplicate declarations, are similar to the rules for non-static
               variables, but with additional constraints designed to disallow forwards references.
               The reason for disallowing forwards references is to ensure that
                  <code nobreak="false">use-when</code> attributes can always be evaluated as early as possible, and
               in particular to ensure that the value of a <code nobreak="false">use-when</code> attribute never has
               circular dependencies. The additional constraints are as follows:</p><olist><item><p>The static context for evaluation of a <termref def="dt-static-expression"/>
                     only contains those <termref def="dt-static-variable">static
                        variables</termref> visible within the containing package whose declarations
                     occur prior to the element containing the static expression in stylesheet tree
                     order. Stylesheet tree order is the order that results when all
                        <elcode>xsl:import</elcode> and <elcode>xsl:include</elcode> declarations
                     are replaced by the declarations in the imported or included stylesheet module.
                     A static variable is not in scope within its own declaration.</p></item><item><p>If two static variables declared within the same package have the same name,
                     the one that has higher <termref def="dt-import-precedence"/> is used (it is a
                     consequence of rules defined elsewhere that there cannot be more than one
                     declaration with highest import precedence). However, if the declaration with
                     higher import precedence occurs after the one with lower import precedence in
                     stylesheet tree order, then the two declarations must be consistent. For this
                     purpose two declarations are consistent if (a) they are either both
                        <elcode>xsl:variable</elcode> elements, or both <elcode>xsl:param</elcode>
                     elements, and (b) if the variables are initialized (that is, if the elements
                     are <elcode>xsl:variable</elcode> elements, or if they are
                        <elcode>xsl:param</elcode> elements and no value for the parameter is
                     externally supplied) then the values of both variables must be <xtermref spec="FO40" ref="dt-identical">identical</xtermref>, and must not contain
                     function items.</p><note><p>This rule ensures that when a static variable reference is encountered, the
                        value of the most recently declared static variable with that name can be
                        used, knowing that this value cannot be overridden by a subsequent
                        declaration having higher import precedence.</p></note><p><error spec="XT" type="static" class="SE" code="3450"><p>It is a <termref def="dt-static-error">static error</termref> if a
                           variable declared with <code nobreak="false">static="yes"</code> is inconsistent with
                           another static variable of the same name that is declared earlier in
                           stylesheet tree order and that has lower <termref def="dt-import-precedence"/>.</p></error></p></item></olist><note diff="add" at="2022-01-01"><p>It is not an error to have two global variables or parameters with the same name, 
                  one static and one non-static, provided that they have different import precedence. 
                  If the static variable has higher precedence, then it will be used as the selected 
                  binding for all global variable references with this name, whether or not they appear 
                  in static expressions. If the non-static variable has higher precedence, then the 
                  static variable will be used as the selected binding for variable references appearing 
                  in static expressions, while the non-static variable will be used for variable 
                  references in non-static expressions. The two variables may have different values. 
                  In the case of global parameters, however, a transformation API may restrict 
                  them to have the same value.</p><p>If the two variable declarations have the same import precedence, and there is 
                     no declaration with higher import precedence, then error condition 
                     <errorref class="SE" code="0630"/> applies.
                  </p></note></div2><div2 id="static-expression"><head>Static Expressions</head><p><termdef id="dt-static-expression" term="static expression">A <term>static
                     expression</term> is an XPath <termref def="dt-expression"/> whose value must
                  be computed during static analysis of the stylesheet.</termdef></p><p>Static expressions appear in a number of contexts, in particular:</p><ulist><item><p>In <code nobreak="false">[xsl:]use-when</code> attributes (see <specref ref="conditional-inclusion"/>);</p></item><item><p>In the <code nobreak="false">select</code> attribute of <termref def="dt-static-variable"/>
                     declarations (<elcode>xsl:variable</elcode> or <elcode>xsl:param</elcode> with
                        <code nobreak="false">static="yes"</code>);</p></item><item><p>In shadow attributes (see <specref ref="shadow-attributes"/>).</p></item></ulist><p>There are no syntactic constraints on the XPath expression that can be used as a
                  <termref def="dt-static-expression"/>. However, there are severe constraints on
               the information provided in its evaluation context. These constraints are designed to
               ensure that the expression can be evaluated at the earliest possible stage of
               stylesheet processing, without any dependency on information contained in the
               stylesheet itself or in any source document.</p><p>Specifically, the components of the static and dynamic context are defined by the
               following two tables:</p><table class="def" border="1" cellpadding="5" width="100%"><caption>Static Context Components for Static Expressions</caption><col align="left" width="30%" span="1"/><col align="left" span="1"/><thead><tr><th rowspan="1" colspan="1" align="left" valign="top">Component</th><th rowspan="1" colspan="1" align="left" valign="top">Value</th></tr></thead><tbody><tr><td rowspan="1" colspan="1" align="left" valign="top">XPath 1.0 compatibility mode</td><td rowspan="1" colspan="1" align="left" valign="top">false</td></tr><tr><td rowspan="1" colspan="1" align="left" valign="top">Statically known namespaces</td><td rowspan="1" colspan="1" align="left" valign="top">the 
                        <phrase diff="chg" at="2023-05-04"><termref def="dt-applicable-static-namespaces"/></phrase> for the containing element in the
                        stylesheet</td></tr><tr diff="chg" at="2024-04-30"><td rowspan="1" colspan="1" align="left" valign="top">Default namespace for elements and types</td><td rowspan="1" colspan="1" align="left" valign="top">determined by the <code nobreak="false">xpath-default-namespace</code> attribute if present
                        (see <specref ref="unprefixed-qnames"/>); otherwise absent</td></tr><tr diff="chg" at="2023-05-04"><td rowspan="1" colspan="1" align="left" valign="top">Default function namespace</td><td rowspan="1" colspan="1" align="left" valign="top">the <termref def="dt-standard-function-namespace"/>.
                     </td></tr><tr><td rowspan="1" colspan="1" align="left" valign="top">In-scope schema types</td><td rowspan="1" colspan="1" align="left" valign="top">The type definitions that would be available in the absence of any
                           <elcode>xsl:import-schema</elcode> declaration</td></tr><tr><td rowspan="1" colspan="1" align="left" valign="top">In-scope element declarations</td><td rowspan="1" colspan="1" align="left" valign="top">None</td></tr><tr><td rowspan="1" colspan="1" align="left" valign="top">In-scope attribute declarations</td><td rowspan="1" colspan="1" align="left" valign="top">None</td></tr><tr><td rowspan="1" colspan="1" align="left" valign="top">In-scope variables</td><td rowspan="1" colspan="1" align="left" valign="top">The <termref def="dt-static-variable">static
                           variables</termref> visible within the containing package whose
                        declarations occur prior to the element containing the static expression in
                        stylesheet tree order. Stylesheet tree order is the order that results when
                        all <elcode>xsl:import</elcode> and <elcode>xsl:include</elcode>
                        declarations are replaced by the declarations in the imported or included
                        stylesheet module. A static variable is not in scope within its own
                        declaration, and it is in scope only within its
                           declaring package, not in any using packages. If two static
                        variables satisfying this rule have the same name and are both in scope, the
                        one that appears most recently in stylesheet tree order is used; as a
                        consequence of rules defined elsewhere this will always be consistent with
                        the declaration having highest import precedence.</td></tr><tr><td rowspan="1" colspan="1" align="left" valign="top">Context item static type</td><td rowspan="1" colspan="1" align="left" valign="top"><termref def="dt-absent">Absent</termref></td></tr><tr><td rowspan="1" colspan="1" align="left" valign="top">In-scope named item types</td><td rowspan="1" colspan="1" align="left" valign="top">None</td></tr><tr><td rowspan="1" colspan="1" align="left" valign="top">Statically known function
                        definitions</td><td rowspan="1" colspan="1" align="left" valign="top">The functions defined in <bibref ref="xpath-functions-40"/> in the <code nobreak="false">fn</code>
                        <code nobreak="false">math</code>, <phrase diff="add" at="2022-01-01"><code nobreak="false">map</code>, and <code nobreak="false">array</code></phrase>  namespaces, together with:
                        <olist><item><p>the functions
                              <function>element-available</function>,
                              <function>function-available</function>,
                              <function>type-available</function>,
                              <function>available-system-properties</function>,
                              and
                              <function>system-property</function> defined in this specification;</p></item><item><p>functions that appear in both this specification and in <bibref ref="xpath-functions-40"/>
                           (for example, the functions in the <code nobreak="false">map</code> namespaces, and a few others such as <code nobreak="false">collation-key</code>
                           and <code nobreak="false">json-to-xml</code>);</p></item><item><p>constructor functions for built-in types;</p></item><item><p>the set of extension functions that are present in the static context of
                              every XPath expression (other than a static expression) within the content
                              of the element that contains the static expression. </p></item></olist>
                        
                        Note that <termref def="dt-stylesheet-function">stylesheet functions</termref> are
                           <emph>not</emph> included in the context, which means that the function
                           <function>function-available</function> will return <code nobreak="false">false</code> in
                        respect of such functions, and <xfunction>function-lookup</xfunction> will
                        fail to find them. The effect of this rule is to ensure that
                           <function>function-available</function> returns <code nobreak="false">true</code> in respect of
                        functions that can be called within the static expression. It also has the
                        effect that these extension functions will be recognized within the static
                        expression itself; however, the fact that a function is available in this
                        sense gives no guarantee that a call on the function will succeed.</td></tr><tr><td rowspan="1" colspan="1" align="left" valign="top">Statically known collations</td><td rowspan="1" colspan="1" align="left" valign="top">Implementation-defined</td></tr><tr><td rowspan="1" colspan="1" align="left" valign="top">Default collation</td><td rowspan="1" colspan="1" align="left" valign="top">The Unicode Codepoint Collation</td></tr><tr><td rowspan="1" colspan="1" align="left" valign="top">Static Base URI</td><td rowspan="1" colspan="1" align="left" valign="top">The base URI of the containing element in the stylesheet document (see <xspecref spec="DM40" ref="dm-base-uri"/>)</td></tr><tr><td rowspan="1" colspan="1" align="left" valign="top">Statically known documents</td><td rowspan="1" colspan="1" align="left" valign="top">Implementation-defined</td></tr><tr><td rowspan="1" colspan="1" align="left" valign="top">Statically known collections</td><td rowspan="1" colspan="1" align="left" valign="top">Implementation-defined</td></tr><tr><td rowspan="1" colspan="1" align="left" valign="top">Statically known default collection type</td><td rowspan="1" colspan="1" align="left" valign="top">Implementation-defined</td></tr><tr><td rowspan="1" colspan="1" align="left" valign="top">Statically known decimal formats</td><td rowspan="1" colspan="1" align="left" valign="top">A single unnamed <termref def="dt-decimal-format">decimal format</termref>
                        equivalent to the decimal format that is created by an
                           <elcode>xsl:decimal-format</elcode> declaration with no attributes.</td></tr></tbody></table><p> </p><table class="def" border="1" cellpadding="5" width="100%"><caption>Dynamic Context Components for Static Expressions</caption><col align="left" width="30%" span="1"/><col align="left" span="1"/><thead><tr><th rowspan="1" colspan="1" align="left" valign="top">Component</th><th rowspan="1" colspan="1" align="left" valign="top">Value</th></tr></thead><tbody><tr><td rowspan="1" colspan="1" align="left" valign="top">Context item, position, and size</td><td rowspan="1" colspan="1" align="left" valign="top"><termref def="dt-absent">Absent</termref></td></tr><tr><td rowspan="1" colspan="1" align="left" valign="top">Variable values</td><td rowspan="1" colspan="1" align="left" valign="top">A value for every variable present in the in-scope variables. For <termref def="dt-static-parameter">static parameters</termref> where an external
                        value is supplied: the externally supplied value of the parameter. In all
                        other cases: the value of the variable as defined in <specref ref="variable-values"/>.</td></tr><tr><td rowspan="1" colspan="1" align="left" valign="top">Dynamically known function definitions</td><td rowspan="1" colspan="1" align="left" valign="top">The same as the statically known function definitions</td></tr><tr><td rowspan="1" colspan="1" align="left" valign="top">Current dateTime</td><td rowspan="1" colspan="1" align="left" valign="top">Implementation-defined</td></tr><tr><td rowspan="1" colspan="1" align="left" valign="top">Implicit timezone</td><td rowspan="1" colspan="1" align="left" valign="top">Implementation-defined</td></tr><tr><td rowspan="1" colspan="1" align="left" valign="top">Executable Base URI</td><td rowspan="1" colspan="1" align="left" valign="top">The same as the Static Base URI</td></tr><tr><td rowspan="1" colspan="1" align="left" valign="top">Default collation</td><td rowspan="1" colspan="1" align="left" valign="top">The Unicode Codepoint Collation</td></tr><tr><td rowspan="1" colspan="1" align="left" valign="top">Default language</td><td rowspan="1" colspan="1" align="left" valign="top">Implementation-defined</td></tr><tr><td rowspan="1" colspan="1" align="left" valign="top">Default calendar</td><td rowspan="1" colspan="1" align="left" valign="top">Implementation-defined</td></tr><tr><td rowspan="1" colspan="1" align="left" valign="top">Default place</td><td rowspan="1" colspan="1" align="left" valign="top">Implementation-defined</td></tr><tr><td rowspan="1" colspan="1" align="left" valign="top">Available documents</td><td rowspan="1" colspan="1" align="left" valign="top">Implementation-defined</td></tr><tr><td rowspan="1" colspan="1" align="left" valign="top">Available text resources</td><td rowspan="1" colspan="1" align="left" valign="top">Implementation-defined</td></tr><tr><td rowspan="1" colspan="1" align="left" valign="top">Available collections</td><td rowspan="1" colspan="1" align="left" valign="top">Implementation-defined</td></tr><tr><td rowspan="1" colspan="1" align="left" valign="top">Default collection</td><td rowspan="1" colspan="1" align="left" valign="top">Implementation-defined</td></tr><tr><td rowspan="1" colspan="1" align="left" valign="top">Available URI collections</td><td rowspan="1" colspan="1" align="left" valign="top">Implementation-defined</td></tr><tr><td rowspan="1" colspan="1" align="left" valign="top">Default URI collection</td><td rowspan="1" colspan="1" align="left" valign="top">Implementation-defined</td></tr><tr><td rowspan="1" colspan="1" align="left" valign="top">Environment variables</td><td rowspan="1" colspan="1" align="left" valign="top">Implementation-defined</td></tr></tbody></table><p>Within a <termref def="dt-stylesheet-module">stylesheet module</termref>, all static
               expressions are evaluated in a single <xtermref spec="FO40" ref="execution-scope">execution scope</xtermref>. This need not be the same execution scope as that
               used for static expressions in other stylesheet modules, or as that used when
               evaluating XPath expressions appearing elsewhere in the stylesheet module. This means
               that a function such as <xfunction>current-date</xfunction> will return the same
               result when called in different <code nobreak="false">[xsl:]use-when</code> expressions within the
               same stylesheet module, but will not necessarily return the same result as the same
               call in an <code nobreak="false">[xsl:]use-when</code> expression within a different stylesheet
               module, or as a call on the same function executed during the transformation
               proper.</p><p>If a <termref def="dt-static-error"/> is present in a
                  <termref def="dt-static-expression"/>, it is treated in the same way as any other
               static error in the stylesheet module. If a <termref def="dt-dynamic-error"/> occurs
               during evaluation of a static expression, it is treated as a static error in the
               analysis of the stylesheet, while retaining its original error code.</p></div2><div2 id="local-variables"><head>Local Variables and Parameters</head><p>
               <termdef id="dt-local-variable" term="local variable">As well as being allowed as a
                     <termref def="dt-declaration">declaration</termref>, the
                     <elcode>xsl:variable</elcode> element is also allowed in <termref def="dt-sequence-constructor">sequence constructors</termref>. Such a variable
                  is known as a <term>local variable</term>.</termdef>
            </p><p>An <elcode>xsl:param</elcode> element may also be used to create a variable binding
               with local scope:</p><ulist><item><p>
                     <termdef id="dt-template-parameter" term="template parameter"> An
                           <elcode>xsl:param</elcode> element may appear as a child of an
                           <elcode>xsl:template</elcode> element, before any
                           non-<elcode>xsl:param</elcode> children of that element. Such a parameter
                        is known as a <term>template parameter</term>. A template parameter is a
                           <termref def="dt-local-variable">local variable</termref> with the
                        additional property that its value can be set when the template is called,
                        using any of the instructions <elcode>xsl:call-template</elcode>,
                           <elcode>xsl:apply-templates</elcode>, <elcode>xsl:apply-imports</elcode>,
                        or <elcode>xsl:next-match</elcode>.</termdef>
                  </p></item><item><p>
                     <termdef id="dt-function-parameter" term="function parameter"> An
                           <elcode>xsl:param</elcode> element may appear as a child of an
                           <elcode>xsl:function</elcode> element, before any
                           non-<elcode>xsl:param</elcode> children of that element. Such a parameter
                        is known as a <term>function parameter</term>. A function parameter is a
                           <termref def="dt-local-variable">local variable</termref> with the
                        additional property that its value can be set when the function is called,
                        using a function call in an XPath <termref def="dt-expression">expression</termref>.</termdef>
                  </p></item><item><p>An <elcode>xsl:param</elcode> element may appear as a child
                     of an <elcode>xsl:iterate</elcode> instruction, before any
                        non-<elcode>xsl:param</elcode> children of that element. This defines a
                     parameter whose value may be initialized on entry to the iteration, and which
                     may be varied each time round the iteration by use of an
                        <elcode>xsl:with-param</elcode> element in the
                        <elcode>xsl:next-iteration</elcode> instruction. </p></item></ulist><p>The result of evaluating a local <elcode>xsl:variable</elcode> or
                  <elcode>xsl:param</elcode> element (that is, the contribution it makes to the
               result of the <termref def="dt-sequence-constructor"/> it is part of) is the empty
               sequence.</p></div2><div2 id="scope-of-variables"><head>Scope of Variables</head><p>For any <termref def="dt-variable-binding-element">variable-binding
               element</termref>, there is a region (more specifically, a set of  nodes) of the <termref def="dt-stylesheet">stylesheet</termref> within which the binding is visible. The set of variable
               bindings in scope for an XPath <termref def="dt-expression">expression</termref>
               consists of those bindings that are visible at the point in the stylesheet where the
               expression occurs.</p><p>A global <termref def="dt-variable-binding-element">variable binding
                  element</termref> is visible everywhere in the containing <termref def="dt-package"/>
                   (including other <termref def="dt-stylesheet-module">stylesheet modules</termref>) except within the <elcode>xsl:variable</elcode> or
                  <elcode>xsl:param</elcode> element itself and any region where it is <termref def="dt-shadows">shadowed</termref> by another variable binding.
               (For rules regarding the visibility of the variable
               in other packages, see <specref ref="visibility"/>.)
            </p><p>A local <termref def="dt-variable-binding-element">variable binding element</termref>
               is visible for all following siblings and their descendants, with the following exceptions:</p><olist><item><p>It is not visible in any region where it is <termref def="dt-shadows">shadowed</termref> by another variable binding.</p></item><item><p>It is not visible within the subtree rooted at an <elcode>xsl:fallback</elcode>
                     instruction that is a sibling of the variable binding element.</p></item><item><p>It is not visible within the subtree rooted at an
                        <elcode>xsl:catch</elcode> instruction that is a sibling of the variable
                     binding element.</p></item><item diff="add" at="2022-01-01"><p>Within an <elcode>xsl:function</elcode> declaration, a <termref def="dt-function-parameter"/>
                     is not visible within sibling <elcode>xsl:param</elcode> elements.</p></item></olist><p>The binding is not visible for the <elcode>xsl:variable</elcode> or
                  <elcode>xsl:param</elcode> element itself.</p><p>If a binding is visible for an element then it is visible for every
               attribute of that element and for every text node child of that element.</p><p diff="add" at="2022-01-01">An <elcode>xsl:param</elcode> element specifying <code nobreak="false">tunnel="yes"</code>
            is also visible in the <code nobreak="false">test</code> attribute of the containing <elcode>xsl:template</elcode>
            element.</p><p diff="del" at="2022-01-01">
               A binding <term>shadows</term> another
                  binding if the binding occurs at a point where the other binding is visible, and
                  the bindings have the same name. It is not an error if a binding
               established by a local <elcode>xsl:variable</elcode> or <elcode>xsl:param</elcode>
               <termref def="dt-shadows">shadows</termref> a global binding. In this case, the
               global binding will not be visible in the region of the 
               <termref def="dt-stylesheet">stylesheet</termref> where it is shadowed by the other binding.</p><p diff="add" at="2022-01-01"><termdef id="dt-shadows" term="shadows">Within a region of the 
               stylesheet where a binding <var>B</var>1 is visible, <var>B1</var> shadows another 
               binding <var>B2</var> having the same name as <var>B1</var> if <var>B1</var> occurs at 
               a point where <var>B2</var> is visible.</termdef> </p><example><head>Local Variable Shadowing a Global Variable</head><p>The following is allowed:</p><eg xml:space="preserve" role="xslt-declaration">&lt;xsl:param name="x" select="1"/&gt;
&lt;xsl:template name="foo"&gt;
  &lt;xsl:variable name="x" select="2"/&gt;
&lt;/xsl:template&gt;</eg></example><p>It is also not an error if a binding established by a local
                  <elcode>xsl:variable</elcode> element <termref def="dt-shadows">shadows</termref>
               a binding established by another local <elcode>xsl:variable</elcode> or
                  <elcode>xsl:param</elcode>.</p><example><head>Misuse of Variable Shadowing</head><p>The following is not an error, but the effect is probably not what was intended.
                  The template outputs <code nobreak="false">&lt;x value="1"/&gt;</code>, because the declaration of
                  the inner variable named <code nobreak="false">$x</code> has no effect on the value of the outer
                  variable named <code nobreak="false">$x</code>.</p><eg xml:space="preserve" role="xslt-declaration">&lt;xsl:variable name="x" select="1"/&gt;
&lt;xsl:template name="foo"&gt;
  &lt;xsl:for-each select="1 to 5"&gt;
    &lt;xsl:variable name="x" select="$x+1"/&gt;
  &lt;/xsl:for-each&gt;
  &lt;x value="{ $x }"/&gt;
&lt;/xsl:template&gt;</eg></example><note><p>Once a variable has been given a value, the value cannot subsequently be changed.
                  XSLT does not provide an equivalent to the assignment operator available in many
                  procedural programming languages. </p><p>This is because an assignment operator would make it harder to create an
                  implementation that processes a document other than in a batch-like way, starting
                  at the beginning and continuing through to the end.</p></note><p>As well as global variables and local variables, an XPath <termref def="dt-expression">expression</termref> may also declare range variables for use
               locally within an expression. For details, see <bibref ref="xpath-40"/>.</p><p>Where a reference to a variable occurs in an XPath expression, it is resolved first
               by reference to range variables that are in scope, then by reference to local
               variables and parameters, and finally by reference to global variables and
               parameters. A range variable may shadow a local variable or a global variable. XPath
               also allows a range variable to shadow another range variable.</p></div2><div2 id="with-param"><head>Setting Parameter Values</head><e:element-syntax xmlns:e="http://www.w3.org/1999/XSL/Spec/ElementSyntax" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" name="with-param">
      <e:attribute name="name" required="yes">
         <e:data-type name="eqname"/>
      </e:attribute>
      <e:attribute name="select">
         <e:data-type name="expression"/>
      </e:attribute>
      <e:attribute name="as">
         <e:data-type name="sequence-type"/>
      </e:attribute>
      <e:attribute name="tunnel" default="'no'">
         <e:data-type name="boolean"/>
      </e:attribute>
      <e:model name="sequence-constructor"/>
      <e:allowed-parents>
         <e:parent name="apply-templates"/>
         <e:parent name="apply-imports"/>
         <e:parent name="call-template"/>
         <e:parent name="evaluate"/>
         <e:parent name="next-match"/>
         <e:parent name="next-iteration"/>
      </e:allowed-parents>
   </e:element-syntax><p>Parameters are passed to templates using the <elcode>xsl:with-param</elcode> element.
               The <rfc2119>required</rfc2119>
               <code nobreak="false">name</code> attribute specifies the name of the <termref def="dt-template-parameter">template parameter</termref> (the variable the value
               of whose binding is to be replaced). The value of the <code nobreak="false">name</code> attribute is
               an <termref def="dt-eqname">EQName</termref>,
               which is expanded as described in <specref ref="qname"/>.</p><p>The <elcode>xsl:with-param</elcode> element is also used
                  when:</p><ulist><item><p>passing parameters to an iteration of the <elcode>xsl:iterate</elcode>
                           instruction</p></item><item><p>passing parameters to a dynamic invocation of an XPath expression using
                           <elcode>xsl:evaluate</elcode></p></item><item><p>supplying the values of <termref def="dt-stylesheet-parameter">stylesheet parameters</termref>
                     in a <termref def="dt-library-package"/> invoked using an <elcode>xsl:use-package</elcode> declaration.</p></item></ulist><p>In consequence, 
               <elcode>xsl:with-param</elcode> may appear within
                  <elcode>xsl:apply-templates</elcode>, <elcode>xsl:apply-imports</elcode>,
                  <elcode>xsl:call-template</elcode>, <elcode>xsl:evaluate</elcode>, <elcode>xsl:next-iteration</elcode>, <elcode>xsl:use-package</elcode>,
               and <elcode>xsl:next-match</elcode>. (Arguments to <termref def="dt-stylesheet-function">stylesheet functions</termref>, however, are supplied
               as part of an XPath function call: see <specref ref="stylesheet-functions"/>.) </p><p>
               <error spec="XT" type="static" class="SE" code="0670"><p>It is a <termref def="dt-static-error">static error</termref>
                     if two or more sibling <elcode>xsl:with-param</elcode> elements have
                        <code nobreak="false">name</code> attributes that represent the same <termref def="dt-expanded-qname">expanded QName</termref>.</p></error>
            </p><p>The value of the parameter is specified in the same way as for
                  <elcode>xsl:variable</elcode> and <elcode>xsl:param</elcode> (see <specref ref="variable-values"/>), taking account of the values of the <code nobreak="false">select</code>
               and <code nobreak="false">as</code> attributes and the content of the <elcode>xsl:with-param</elcode>
               element, if any.</p><note><p>It is possible to have an <code nobreak="false">as</code> attribute on the
                     <elcode>xsl:with-param</elcode> element that differs from the <code nobreak="false">as</code>
                  attribute on the corresponding <elcode>xsl:param</elcode> element.</p><p>In this situation, the supplied value of the parameter will first be processed
                  according to the rules of the <code nobreak="false">as</code> attribute on the
                     <elcode>xsl:with-param</elcode> element, and the resulting value will then be
                  further processed according to the rules of the <code nobreak="false">as</code> attribute on the
                     <elcode>xsl:param</elcode> element.</p><p>For example, suppose the supplied value is a node with <termref def="dt-type-annotation"/>
                  <code nobreak="false">xs:untypedAtomic</code>, and the <elcode>xsl:with-param</elcode> element
                  specifies <code nobreak="false">as="xs:integer"</code>, while the <elcode>xsl:param</elcode>
                  element specifies <code nobreak="false">as="xs:double"</code>. Then the node will first be
                  atomized and the resulting untyped atomic item will be cast to
                     <code nobreak="false">xs:integer</code>. If this succeeds, the <code nobreak="false">xs:integer</code> will
                  then be promoted to an <code nobreak="false">xs:double</code>.</p></note><p>The <termref def="dt-focus">focus</termref> used for computing the value specified by
               the <elcode>xsl:with-param</elcode> element is the same as that used for its parent 
               <termref def="dt-instruction">instruction</termref>.</p><p>The optional <code nobreak="false">tunnel</code> attribute may be used to indicate that a parameter
               is a <termref def="dt-tunnel-parameter">tunnel parameter</termref>. The default is
                  <code nobreak="false">no</code>. Tunnel parameters are described in <specref ref="tunnel-params"/>. They are used only when passing parameters to templates: for an
                  <elcode>xsl:with-param</elcode> element that is a child of
                  <elcode>xsl:evaluate</elcode> or <elcode>xsl:next-iteration</elcode> the
                  <code nobreak="false">tunnel</code> attribute <rfc2119>must</rfc2119> either be omitted or take
               the value <code nobreak="false">no</code>. </p><p> In other cases it is a <termref def="dt-dynamic-error"> dynamic error</termref> if the template that is
               invoked declares a <termref def="dt-template-parameter">template parameter</termref>
               with <code nobreak="false">required="yes"</code> and no value for this parameter is supplied by the
               calling instruction. <errorref spec="XT" class="DE" code="0700"/>
            </p></div2><div2 id="circularity"><head>Circular Definitions</head><p>
               <termdef id="dt-circularity" term="circularity">A <term>circularity</term> is said to
                  exist if a construct such as a <termref def="dt-global-variable">global
                     variable</termref>, an <termref def="dt-attribute-set">attribute set</termref>,
                  or a <termref def="dt-key">key</termref>, cannot be evaluated without reference to its own value. For
                  example, if the <termref def="dt-expression">expression</termref> or <termref def="dt-sequence-constructor">sequence constructor</termref> specifying the
                  value of a <termref def="dt-global-variable">global variable</termref>
                  <var>X</var> references a global variable <var>Y</var>, then the value for
                     <var>Y</var>
                  <rfc2119>must</rfc2119> be computed before the value of <var>X</var>. A
                  circularity exists if it is impossible to do this for all global variable
                  definitions.</termdef>
            </p><example><head>Circular Variable Definitions</head><p>The following two declarations create a circularity:</p><eg role="error" xml:space="preserve">&lt;xsl:variable name="x" select="$y+1"/&gt;
&lt;xsl:variable name="y" select="$x+1"/&gt;</eg></example><example><head>Circularity involving Variables and Functions</head><p>The definition of a global variable can be circular even if no other variable is
                  involved. For example the following two declarations (see <specref ref="stylesheet-functions"/> for an explanation of the
                     <elcode>xsl:function</elcode> element) also create a circularity:</p><eg role="error" xml:space="preserve">&lt;xsl:variable name="x" select="my:f()"/&gt;

&lt;xsl:function name="my:f"&gt;
  &lt;xsl:sequence select="$x"/&gt;
&lt;/xsl:function&gt;
</eg></example><example><head>Circularity involving Variables and Templates</head><p>The definition of a variable is also circular if the evaluation of the variable
                  invokes an <elcode>xsl:apply-templates</elcode> instruction and the variable is
                  referenced in the pattern used in the <code nobreak="false">match</code> attribute of any template
                  rule in the <termref def="dt-stylesheet">stylesheet</termref>. For example the
                  following definition is circular:</p><eg role="error" xml:space="preserve">&lt;xsl:variable name="x"&gt;
  &lt;xsl:apply-templates select="//param[1]"/&gt;
&lt;/xsl:variable&gt;

&lt;xsl:template match="param[$x]"&gt;1&lt;/xsl:template&gt;
</eg></example><example><head>Circularity involving Variables and Keys</head><p>Similarly, a variable definition is circular if it causes a call on the
                     <function>key</function> function, and the definition of that <termref def="dt-key">key</termref> refers to that variable in its <code nobreak="false">match</code> or
                     <code nobreak="false">use</code> attributes. So the following definition is circular:</p><eg role="error" xml:space="preserve">&lt;xsl:variable name="x" select="my:f(10, /)"/&gt;

&lt;xsl:function name="my:f"&gt;
  &lt;xsl:param name="arg1"/&gt;
  &lt;xsl:param name="top"/&gt;
  &lt;xsl:sequence select="key('k', $arg1, $top)"/&gt;
&lt;/xsl:function&gt;

&lt;xsl:key name="k" match="item[@code=$x]" use="@desc"/&gt;
</eg></example><example><head>Circularity involving Attribute Sets</head><p>An attribute set is circular if its <code nobreak="false">use-attribute-sets</code> attribute
                  references itself, directly or indirectly. So the following definitions establish
                  a circularity:</p><eg role="error" xml:space="preserve">&lt;xsl:attribute-set name="a" use-attribute-sets="b"/&gt;
&lt;xsl:attribute-set name="b" use-attribute-sets="a"/&gt;                  
</eg><p>Because attribute sets can invoke functions, global variables, or templates, and
                  can also include instructions such as literal result elements that themselves
                  invoke attribute sets, examples of circularity involving attribute sets can be
                  more complex than this simple example illustrates. It is also possible to
                  construct examples in which self-reference among attribute sets could be regarded
                  as (terminating or non-terminating) recursion. However, because such
                  self-references have no practical utility, any requirement to evaluate an
                  attribute set in the course of its own evaluation is considered an error.</p><note><p>In previous versions of this specification, self-reference among attribute sets
                     was defined as a static error. In XSLT 3.0 it is not always detectable
                     statically, because attribute sets can bind to each other across package
                     boundaries. Nevertheless, in cases where a processor can detect a static
                     circularity, it can raise this error during the analysis phase, under the
                     general provision for raising dynamic errors during stylesheet analysis if
                     execution can never succeed.</p></note></example><p>
               <error spec="XT" type="dynamic" class="DE" code="0640"><p>In general, a <termref def="dt-circularity">circularity</termref> in a <termref def="dt-stylesheet">stylesheet</termref> is a <termref def="dt-dynamic-error">
                        dynamic error</termref>.</p></error> However, as with all other dynamic errors, an implementation will raise the
               error only if it actually executes the instructions and expressions that participate
               in the circularity. Because different implementations may optimize the execution of a
               stylesheet in different ways, it is <termref def="dt-implementation-dependent">implementation-dependent</termref> whether a particular circularity will actually
               be raised.</p><p>For example, in the following declarations, the function declares a local variable
                  <code nobreak="false">$b</code>, but it returns a result that does not require the variable to be
               evaluated. It is <termref def="dt-implementation-dependent">implementation-dependent</termref> whether the value is actually evaluated, and
               it is therefore implementation-dependent whether the circularity is raised as an
               error:</p><eg role="error" xml:space="preserve">&lt;xsl:variable name="x" select="my:f(1)"/&gt;

&lt;xsl:function name="my:f"&gt;
  &lt;xsl:param name="a"/&gt;
  &lt;xsl:variable name="b" select="$x"/&gt;  
  &lt;xsl:sequence select="$a + 2"/&gt;
&lt;/xsl:function&gt;
</eg><p>Although a circularity is detected as a dynamic error,
               there is no unique instruction whose evaluation triggers the error condition, and the
               result of any attempt to catch the error using an <elcode>xsl:try</elcode>
               instruction is therefore <termref def="dt-implementation-dependent"/>.</p><p>Circularities usually involve global variables or parameters, but they can also exist
               between <termref def="dt-key">key</termref> definitions (see <specref ref="key"/>),
               between named <termref def="dt-attribute-set">attribute sets</termref> (see <specref ref="attribute-sets"/>), or between any combination of these constructs. For
               example, a circularity exists if a key definition invokes a function that references
               an attribute set that calls the <function>key</function> function, supplying the name
               of the original key definition as an argument.</p><p>Circularity is not the same as recursion. Stylesheet functions (see <specref ref="stylesheet-functions"/>) and named templates (see <specref ref="named-templates"/>) may call other functions and named templates without
               restriction. With careless coding, recursion may be non-terminating. Implementations
               are <rfc2119>required</rfc2119> to raise circularity as a <termref def="dt-dynamic-error">dynamic error</termref>, but they are not
                  <rfc2119>required</rfc2119> to detect non-terminating recursion.</p><p>Recursive functions can also be defined using global variable declarations. For example, the variable
            declaration <code nobreak="false">&lt;xsl:variable name="f" select="fn($n){if ($n=0) then 0 else $f($n - 1)}"/&gt;</code> does
            not constitute a circularity, because the variable can be evaluated (delivering a function) without knowing its
            own value.</p><p>The requirement to report a circularity as a dynamic error
               overrides the rule that dynamic errors in evaluating <termref def="dt-pattern">patterns</termref> are normally masked (by treating the pattern as not
               matching).</p></div2></div1><div1 id="callable-components"><head>Callable Components</head><p>This section describes three constructs that can be used to provide subroutine-like
            functionality that can be invoked from anywhere in the stylesheet: named templates (see
               <specref ref="named-templates"/>), named attribute sets (see <specref ref="attribute-sets"/>), and <termref def="dt-stylesheet-function">stylesheet
               functions</termref> (see <specref ref="stylesheet-functions"/>).</p><p><termdef id="dt-invocation-construct" term="invocation construct">The following 
               constructs are classified as <term>invocation constructs</term>: the
               instructions <elcode>xsl:call-template</elcode>,
               <elcode>xsl:apply-templates</elcode>, <elcode>xsl:apply-imports</elcode>, and
                  <elcode>xsl:next-match</elcode>; XPath function calls that bind to <termref def="dt-stylesheet-function">stylesheet functions</termref>; XPath dynamic
               function calls; the functions <function>accumulator-before</function> and
                  <function>accumulator-after</function>; the <code nobreak="false">[xsl:]use-attribute-sets</code>
               attribute. These all have the characteristic that they can cause evaluation of
               constructs that are not lexically contained within the calling
            construct.</termdef></p><div2 id="named-templates"><head>Named Templates</head><div3 id="declaring-named-templates"><head>Declaring Named Templates</head><p>
               <termdef id="dt-named-template" term="named template">Templates can be invoked by
                  name. An <elcode>xsl:template</elcode> element with a <code nobreak="false">name</code> attribute
                  defines a <term>named template</term>.</termdef> The value of the
                  <code nobreak="false">name</code> attribute is an <termref def="dt-eqname">EQName</termref>, which is expanded as described in
                  <specref ref="qname"/>. If an <elcode>xsl:template</elcode> element has a
                  <code nobreak="false">name</code> attribute, it may, but need not, also have a <code nobreak="false">match</code>
               attribute. </p><p>The <code nobreak="false">match</code>, <code nobreak="false">mode</code> and <code nobreak="false">priority</code> attributes on an
                  <elcode>xsl:template</elcode> element have no effect when the <termref def="dt-template">template</termref> is invoked by an
                  <elcode>xsl:call-template</elcode> instruction. Similarly, the <code nobreak="false">name</code>
                and <code nobreak="false">visibility</code> attributes on an
                  <elcode>xsl:template</elcode> element have no effect when the template is invoked
               by an <elcode>xsl:apply-templates</elcode> instruction.</p><p>
               <error spec="XT" type="static" class="SE" code="0660"><p>It is a <termref def="dt-static-error">static error</termref> if a 
                     
                        <termref def="dt-package">package</termref> contains more than one
                        non-hidden
                     <termref def="dt-template">template</termref> with the same name and the same
                        <termref def="dt-import-precedence">import precedence</termref>, unless it
                     also contains a <termref def="dt-template">template</termref> with the same
                     name and higher <termref def="dt-import-precedence">import
                     precedence</termref>.</p></error>
            </p><p>The template name <code nobreak="false">xsl:initial-template</code> is specially
               recognized in that it provides a default entry point for stylesheet execution (see
                  <specref ref="initiating"/>.) </p></div3><div3 id="invoking-named-templates"><head>Invoking Named Templates</head><e:element-syntax xmlns:e="http://www.w3.org/1999/XSL/Spec/ElementSyntax" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" name="call-template">
      <e:in-category name="instruction"/>
      <e:attribute name="name" required="yes">
         <e:data-type name="eqname"/>
      </e:attribute>
      <e:element repeat="zero-or-more" name="with-param"/>
      <e:allowed-parents>
         <e:parent-category name="sequence-constructor"/>
      </e:allowed-parents>
   </e:element-syntax><p>An <elcode>xsl:call-template</elcode> instruction invokes a template by
                  name; it has a <rfc2119>required</rfc2119>
                  <code nobreak="false">name</code> attribute that identifies the template to be invoked. Unlike
                  <elcode>xsl:apply-templates</elcode>, the <elcode>xsl:call-template</elcode>
                  instruction does not change the <termref def="dt-focus">focus</termref>.</p><p>
                  <error spec="XT" type="static" class="SE" code="0650"><p>It is a <termref def="dt-static-error">static error</termref> if a <termref def="dt-package">package</termref> contains an
                        <elcode>xsl:call-template</elcode> instruction whose <code nobreak="false">name</code>
                        attribute does not match the <code nobreak="false">name</code> attribute of any <termref def="dt-named-template">named template</termref>
                        visible in the containing <termref def="dt-package">package</termref> (this
                        includes any template defined in this package, as well as templates accepted
                        from used packages whose visibility in this package is not
                        <code nobreak="false">hidden</code>). For more details of the process of binding the
                        called template, see <specref ref="component-references"/>.</p></error>
               </p><p>The target <termref def="dt-template">template</termref>
                  for an <elcode>xsl:call-template</elcode> instruction is established using the
                  binding rules described in <specref ref="component-references"/>. This will always
                  be a template whose <code nobreak="false">name</code> attribute matches the <code nobreak="false">name</code>
                  attribute of the <elcode>xsl:call-template</elcode> instruction. It may be a
                  template defined in the same package that has higher <termref def="dt-import-precedence">import precedence</termref> than any other template
                  with this name, or it may be a template accepted from a used package, or (if the
                  template is not defined as <code nobreak="false">private</code> or <code nobreak="false">final</code>) it may be
                  an overriding template in a package that uses the containing package. 
                  The result of evaluating an <elcode>xsl:call-template</elcode> instruction is the
                  sequence produced by evaluating the <termref def="dt-sequence-constructor">sequence
                     constructor</termref> contained in its target <termref def="dt-template">template</termref> (see <specref ref="sequence-constructors"/>).</p><p>Parameters for a named template can be supplied using <elcode>xsl:with-param</elcode> elements as children
              of the <elcode>xsl:call-template</elcode> instruction: see <specref ref="with-param"/>.</p></div3><div3 id="invoking-templates-with-extension-instructions" diff="add" at="2022-01-01"><head>Invoking Named Templates using Extension Instructions</head><changes><change issue="168" date="2022-09-30">
                     It is possible to invoke a named template using an extension instruction, specifically,
                     an element whose name matches the name of the named template.
                  </change></changes><p>As an alternative to the use of <elcode>xsl:call-template</elcode>, it is
               possible to invoke a named template using an instruction. For example, given
               the named template:</p><eg xml:space="preserve">&lt;xsl:template name="log:message"&gt;
    &lt;xsl:param name="message" as="xs:string"/&gt;
    &lt;message&gt;{ $message }&lt;/message&gt;
&lt;/xsl:template&gt;</eg><p>a call on the template written as:</p><eg xml:space="preserve">&lt;xsl:call-template name="log:message"&gt;
    &lt;xsl:with-param name="message" select="'Good morning'"/&gt;
&lt;/xsl:call-template&gt;</eg><p>can be replaced with the instruction:</p><eg xml:space="preserve">&lt;log:message message="Good morning"/&gt;</eg><p>For this to work, the name of the template must be in a non-null namespace, and
               this namespace must be designated as an extension element namespace using the
               attribute <code nobreak="false">[xsl:]extension-element-prefixes</code> on the instruction itself,
               or on some containing element (see <specref ref="standard-attributes"/>).</p><p>The name of the instruction must match the name of the called template, and the
               names of its attributes (other than <termref def="dt-standard-attributes"/>)
                  are matched against the names of the template’s parameters. 
                  <termref def="dt-standard-attributes">Standard attributes</termref> are recognized
               (they must be in the <termref def="dt-xslt-namespace"/>) and have their standard meaning;
               for example <code nobreak="false">xsl:default-collation</code> affects the evaluation of any XPath expression
               used to compute a parameter value.</p><p>The way in which attribute values are handled depends on the type declaration
               of the template parameter:</p><olist><item><p>If the declared type is <code nobreak="false">xs:boolean</code>, with no occurrence indicator,
                     then the attribute is treated
                     as an <termref def="dt-attribute-value-template"/> whose <termref def="dt-effective-value"/>
                     (after whitespace trimming) must be one of <code nobreak="false">yes</code>, <code nobreak="false">true</code>, or <code nobreak="false">1</code>,
                     or <code nobreak="false">no</code>, <code nobreak="false">false</code>, or <code nobreak="false">0</code>, in the same way as boolean
                     attributes on XSLT instructions. 
                  </p></item><item><p>If the declared type is any other atomic or union type, with no occurrence indicator, 
                     then the attribute is treated as an <termref def="dt-attribute-value-template"/>,
                     and its <termref def="dt-effective-value"/> is treated as an <code nobreak="false">xs:untypedAtomic</code> item,
                     which forces conversion to the required type by applying the casting rules.</p></item><item><p>In all other cases (that is, if the type of the parameter is not declared, 
                     or if it is not atomic, or if there is an occurrence
                  indicator) the attribute is treated as an XPath expression and its value is converted
                  to the required type using the <termref def="dt-coercion-rules"/>.</p></item></olist><p>If an instruction is recognized as an implicit call on a named template, then the static
                  and dynamic rules that apply are the same as if it were expanded into an 
                  <elcode>xsl:call-template</elcode> instruction. The instruction</p><eg xml:space="preserve">&lt;N A1="E1" A2="E2" A3="E3"/&gt;</eg><p>is essentially equivalent to:</p><eg xml:space="preserve">&lt;xsl:call-template name="N"&gt;
  &lt;xsl:with-param name="A1" select="E1"/&gt;
  &lt;xsl:with-param name="A2" select="E2"/&gt;
  &lt;xsl:with-param name="A3" select="E3"/&gt;
&lt;/xsl:call-template&gt;</eg><p>except that the interpretation of the parameter values <code nobreak="false">E1</code>, <code nobreak="false">E2</code>, and <code nobreak="false">E3</code>
               depends on the declared type as explained above.</p><p>Some of the implications of this equivalence are:</p><ulist><item><p>The binding of the instruction to a specific named template (for example, if there
                     are overriding declarations in multiple packages) follows the binding rules in
                     <specref ref="component-references"/>.</p></item><item><p>A value must be supplied for any parameter declared with <code nobreak="false">required="yes"</code>.</p></item><item><p>The context item for the evaluation of the extension instruction must satisfy any constraints
                  defined in an <elcode>xsl:context-item</elcode> declaration in the called template.</p></item><item><p>It is an error if the instruction has attributes that do not correspond to the names
                  of parameters declared on the named template.</p></item></ulist><p>It is not possible to supply values for 
                  <termref def="dt-tunnel-parameter">tunnel parameters</termref>, but existing
               tunnel parameters are passed through unchanged.</p><p>For backwards compatibility, if an external implementation of an extension instruction
               is available to the implementation, then that takes precedence over the existence of 
               a named template with a matching name.</p><p>The XSLT namespace cannot be designated as an extension element namespace, so the template
               names <code nobreak="false">xsl:initial-template</code> and <code nobreak="false">xsl:original</code> cannot be used as
               extension instructions.</p></div3><div3 id="declaring-context-item"><head>Declaring the Context Item for a Template</head><p>The <elcode>xsl:context-item</elcode> element is used as a child of
                     <elcode>xsl:template</elcode>, to declare the required type of the context
                  item. It is intended particularly for use when the containing template is called
                  using an <elcode>xsl:call-template</elcode> instruction, but it also constrains
                  the context item if the same template is invoked using
                     <elcode>xsl:apply-templates</elcode>, <elcode>xsl:apply-imports</elcode>, or
                     <elcode>xsl:next-match</elcode>. </p><note diff="add" at="2023-10-30"><p>The context item for a template must be either a single
               item, or absent. It cannot be an arbitrary value.</p></note><e:element-syntax xmlns:e="http://www.w3.org/1999/XSL/Spec/ElementSyntax" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" name="context-item">
      <e:attribute name="as">
         <e:data-type name="item-type" default="'item()'"/>
      </e:attribute>
      <e:attribute name="use" default="'optional'">
         <e:constant value="required"/>
         <e:constant value="optional"/>
         <e:constant value="absent"/>
      </e:attribute>
      <e:empty/>
      <e:allowed-parents>
         <e:parent name="template"/>
      </e:allowed-parents>
   </e:element-syntax><p>If the <code nobreak="false">as</code> attribute is present then its value must be an <xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="XP40" ref="prod-xpath40-ItemType" xlink:type="simple">ItemType</xnt>. If the attribute is
                  omitted this is equivalent to specifying <code nobreak="false">as="item()"</code>.</p><p><error spec="XT" type="static" class="SE" code="3088"><p>It is a <termref def="dt-static-error"/> if the <code nobreak="false">as</code> attribute is
                        present <error.extra>on the <elcode>xsl:context-item</elcode>
                           element</error.extra> when <code nobreak="false">use="absent"</code> is specified.</p></error></p><p>A <termref def="dt-type-error"/> is raised if the supplied
                  context item does not match its required type. No attempt is made to convert the
                  context item to the required type (using the coercion rules or
                  otherwise). The error code is the same as for <elcode>xsl:param</elcode>:
                     <errorref spec="XT" class="TE" code="0590"/>.</p><p>If an <elcode>xsl:context-item</elcode> element is present as
                  the first child element of <elcode>xsl:template</elcode>, it defines whether the
                  template requires a context item to be supplied, and if so, what the type of the
                  context item must be. If this template is the <termref def="dt-initial-named-template"/>, then this has the effect of placing
                  constraints on the <termref def="dt-global-context-item">global context
                     item</termref> for the transformation as a whole.</p><p>The <code nobreak="false">use</code> attribute of
                     <elcode>xsl:context-item</elcode> takes the value <code nobreak="false">required</code>,
                     <code nobreak="false">optional</code>, or <code nobreak="false">absent</code>.
                     The default is
                     <code nobreak="false">optional</code>.</p><p>If the containing <elcode>xsl:template</elcode> element has no <code nobreak="false">name</code>
                  attribute then the only permitted value is <code nobreak="false">required</code>.</p><ulist><item><p>If the value <code nobreak="false">required</code> is specified, then there must be a
                        context item. (This will automatically be the case if the template is
                        invoked using <elcode>xsl:apply-templates</elcode>,
                           <elcode>xsl:apply-imports</elcode>, or <elcode>xsl:next-match</elcode>,
                        but not if it is invoked using <elcode>xsl:call-template</elcode>.) </p></item><item><p>If the value <code nobreak="false">optional</code> is specified, or if the attribute is
                        omitted, or if the <elcode>xsl:context-item</elcode> element is omitted,
                        then there may or may not be a context item when the template is
                        invoked.</p></item><item><p>If the value <code nobreak="false">absent</code> is specified, then the contained sequence
                        constructor, and any <elcode>xsl:param</elcode> elements, are evaluated with
                        an absent focus.</p><note><p>It is not an error to call such a template with a non-absent focus; the
                           context item is simply treated as absent. This option is useful when
                           streaming, since an <elcode>xsl:call-template</elcode> instruction may
                           become streamable if the referenced template is declared to make no use
                           of the context item.</p></note></item></ulist><p> The processor <rfc2119>may</rfc2119>
                  raise a <termref def="dt-type-error">type error</termref> statically if the
                  required context item type is incompatible with the <code nobreak="false">match</code> pattern,
                  that is, if no item that satisfies the match pattern can also satisfy the required
                  context item type.</p><p>The <elcode>xsl:context-item</elcode> element plays no part in
                  deciding whether and when the template rule is invoked in response to an
                     <elcode>xsl:apply-templates</elcode> instruction. </p><p>
                  <error spec="XT" type="type" class="TE" code="3090"><p>It is a <termref def="dt-type-error">type error</termref> if the
                           <elcode>xsl:context-item</elcode> child of <elcode>xsl:template</elcode>
                        specifies that a context item is required and none is supplied by the
                        caller, that is, if the context item is absent at the point where
                           <elcode>xsl:call-template</elcode> is evaluated.</p></error>
               </p></div3><div3 id="call-template-params"><head>Passing Parameters to Named Templates</head><p>Parameters are passed to named templates using the <elcode>xsl:with-param</elcode>
                  element as a child of the <elcode>xsl:call-template</elcode> instruction.</p><p>
                  <error spec="XT" type="static" class="SE" code="0680"><p>In the case of <elcode>xsl:call-template</elcode>, it is a <termref def="dt-static-error">static error</termref> to pass a non-tunnel
                        parameter named <var>x</var> to a template that does not have a non-tunnel
                        <termref def="dt-template-parameter">template
                           parameter</termref> named <var>x</var>, unless the <elcode>xsl:call-template</elcode> instruction is processed with
                              <termref def="dt-xslt-10-behavior">XSLT 1.0
                           behavior</termref>.</p></error> This is not an error in the case of <elcode>xsl:apply-templates</elcode>,
                     <elcode>xsl:apply-imports</elcode>, and <elcode>xsl:next-match</elcode>; in
                  these cases the parameter is simply ignored.</p><p>The optional <code nobreak="false">tunnel</code> attribute may be used to indicate that a
                  parameter is a <termref def="dt-tunnel-parameter">tunnel parameter</termref>. The
                  default is <code nobreak="false">no</code>. Tunnel parameters are described in <specref ref="tunnel-params"/>.
               </p><example><head>Calling a Named Template with a Parameter</head><p>This example defines a named template for a <code nobreak="false">numbered-block</code> with a
                     parameter to control the format of the number.</p><eg xml:space="preserve" role="xslt-declaration xmlns:fo='fo'">&lt;xsl:template name="numbered-block"&gt;
  &lt;xsl:param name="format"&gt;1. &lt;/xsl:param&gt;
  &lt;fo:block&gt;
    &lt;xsl:number format="{ $format }"/&gt;
    &lt;xsl:apply-templates/&gt;
  &lt;/fo:block&gt;
&lt;/xsl:template&gt;

&lt;xsl:template match="ol//ol/li"&gt;
  &lt;xsl:call-template name="numbered-block"&gt;
    &lt;xsl:with-param name="format"&gt;a. &lt;/xsl:with-param&gt;
  &lt;/xsl:call-template&gt;
&lt;/xsl:template&gt;</eg></example></div3><div3 id="tunnel-params"><head>Tunnel Parameters</head><p>
                  <termdef id="dt-tunnel-parameter" term="tunnel parameter">A parameter passed to a
                     template may be defined as a <term>tunnel parameter</term>. Tunnel parameters
                     have the property that they are automatically passed on by the called template
                     to any further templates that it calls, and so on recursively.</termdef> Tunnel
                  parameters thus allow values to be set that are accessible during an entire phase
                  of stylesheet processing, without the need for each template that is used during
                  that phase to be aware of the parameter.</p><note><p>Tunnel parameters are conceptually similar to the dynamically scoped variables found in
                     some functional programming languages (for example, early versions of LISP), where 
                     evaluating a variable reference involves searching down the dynamic call stack for
                     a matching variable name. There are two main use cases for the feature:</p><olist><item><p>They provide a way to supply context information that might be needed by many
                     templates (for example, the fact that the output is to be localized for a particular language),
                     but which cannot be placed in a global variable because it might vary from one phase of processing
                     to another. Passing such information using conventional parameters is error-prone, because
                     a single <elcode>xsl:apply-templates</elcode> or <elcode>xsl:call-template</elcode> instruction
                     that neglects to pass the information on will lead to failures that are difficult to diagnose.</p><p diff="add" at="2022-01-01">This style of processing is even more useful when handling JSON input,
                     because with maps and arrays, there is no ancestor axis to examine properties of nodes further
                     up the tree; with a recursive descent of the tree, all context information needs to be passed down
                     explicitly. One way of handling this is for each level of processing in the tree to bind a tunnel
                     parameter to the map or array encountered at that level, which then becomes available to all
                     template rules processing data further down the tree.</p></item><item><p>They are particularly useful when writing a customization layer for an existing stylesheet. For
                     example, if you want to override a template rule that displays chemical formulae, you might want the
                     new rule to be parameterized so you can apply the house-style of a particular scientific journal.
                     Tunnel parameters allow you to pass this information to the overriding template rule without
                     requiring modifications to all the intermediate template rules. Again, a global variable could be used,
                     but only if the same house-style is to be used for all chemical formulae processed during a single
                     transformation.</p></item></olist></note><p>A <termref def="dt-tunnel-parameter">tunnel parameter</termref> is created by
                  using an <elcode>xsl:with-param</elcode> element that specifies
                     <code nobreak="false">tunnel="yes"</code>. A template that requires access to the value of a
                  tunnel parameter must declare it using an <elcode>xsl:param</elcode> element that
                  also specifies <code nobreak="false">tunnel="yes"</code>.</p><p>On any template call using an <elcode>xsl:apply-templates</elcode>,
                     <elcode>xsl:call-template</elcode>, <elcode>xsl:apply-imports</elcode> or
                     <elcode>xsl:next-match</elcode> instruction, a set of <termref def="dt-tunnel-parameter">tunnel parameters</termref> is passed from the
                  calling template to the called template. This set consists of any parameters
                  explicitly created using <code nobreak="false">&lt;xsl:with-param tunnel="yes"&gt;</code>,
                  overlaid on a base set of tunnel parameters. If the
                     <elcode>xsl:apply-templates</elcode>, <elcode>xsl:call-template</elcode>,
                     <elcode>xsl:apply-imports</elcode> or <elcode>xsl:next-match</elcode>
                  instruction has an <elcode>xsl:template</elcode> declaration as an ancestor
                  element in the stylesheet, then the base set consists of the tunnel parameters
                  that were passed to that template; otherwise (for example, if the instruction is
                  within a global variable declaration, an <termref def="dt-attribute-set">attribute
                     set</termref> declaration, or a <termref def="dt-stylesheet-function">stylesheet function</termref>), the base set is empty. If a parameter created
                  using <code nobreak="false">&lt;xsl:with-param tunnel="yes"&gt;</code> has the same <termref def="dt-expanded-qname">expanded QName</termref> as a parameter in the base
                  set, then the parameter created using <elcode>xsl:with-param</elcode> overrides
                  the parameter in the base set; otherwise, the parameter created using
                     <elcode>xsl:with-param</elcode> is added to the base set.</p><p diff="chg" at="2022-01-01">When a template specifies <code nobreak="false">&lt;xsl:param tunnel="yes"&gt;</code>,
                  this declares the intention to make use of a <termref def="dt-tunnel-parameter">tunnel
                     parameter</termref>; it does not remove the parameter from the base set
                  of tunnel parameters that is passed on to any templates called by this
                  template.</p><p>Two sibling <elcode>xsl:with-param</elcode> elements <rfc2119>must</rfc2119> have
                  distinct parameter names, even if one is a <termref def="dt-tunnel-parameter">tunnel parameter</termref> and the other is not. Equally, two sibling
                     <elcode>xsl:param</elcode> elements representing <termref def="dt-template-parameter">template parameters</termref>
                  <rfc2119>must</rfc2119> have distinct parameter names, even if one is a <termref def="dt-tunnel-parameter">tunnel parameter</termref> and the other is not.
                  However, the tunnel parameters that are implicitly passed in a template call
                     <rfc2119>may</rfc2119> have names that duplicate the names of non-tunnel
                  parameters that are explicitly passed on the same call.</p><p>
                  <termref def="dt-tunnel-parameter">Tunnel parameters</termref> are not passed in
                  calls to <termref def="dt-stylesheet-function">stylesheet functions</termref>.</p><p>All other options of <elcode>xsl:with-param</elcode> and
                     <elcode>xsl:param</elcode> are available with <termref def="dt-tunnel-parameter">tunnel parameters</termref> just as with non-tunnel
                  parameters. For example, parameters may be declared as mandatory or optional, a
                  default value may be specified, and a required type may be specified. If any
                  conversion is required from the supplied value of a tunnel parameter to the
                  required type specified in <elcode>xsl:param</elcode>, then the converted value is
                  used within the receiving template, but the value that is passed on in any further
                  template calls is the original supplied value before conversion. Equally, any
                  default value is local to the template: specifying a default value for a tunnel
                  parameter does not change the set of tunnel parameters that is passed on in
                  further template calls.</p><p>
                  <termref def="dt-tunnel-parameter">Tunnel parameters</termref> are passed
                  unchanged through a built-in template rule (see <specref ref="built-in-rule"/>).</p><p>If a tunnel parameter is declared in an
                     <elcode>xsl:param</elcode> element with the attribute
                  <code nobreak="false">tunnel="yes"</code>, and if the
                  parameter is <termref def="dt-explicitly-mandatory">explicitly</termref>
                  or <termref def="dt-implicitly-mandatory">implicitly</termref> mandatory,
                  then a  dynamic error occurs <errorref spec="XT" class="DE" code="0700"/> if the set of tunnel parameters passed to the template does not
                  include a parameter with a matching <termref def="dt-expanded-qname">expanded
                     QName</termref>.</p><example><head>Using Tunnel Parameters</head><p>Suppose that the equations in a scientific paper are to be sequentially
                     numbered, but that the format of the number depends on the context in which the
                     equations appear. It is possible to reflect this using a rule of the form:</p><eg xml:space="preserve" role="xslt-declaration">&lt;xsl:template match="equation"&gt;
  &lt;xsl:param name="equation-format" select="'(1)'" tunnel="yes"/&gt;
  &lt;xsl:number level="any" format="{ $equation-format }"/&gt;
&lt;/xsl:template&gt;</eg><p>At any level of processing above this level, it is possible to determine how
                     the equations will be numbered, for example:</p><eg xml:space="preserve" role="non-xml">&lt;xsl:template match="appendix"&gt;
  ...
  &lt;xsl:apply-templates&gt;
    &lt;xsl:with-param name="equation-format" select="'[i]'" tunnel="yes"/&gt;
  &lt;/xsl:apply-templates&gt;
  ...
&lt;/xsl:template&gt;</eg><p>The parameter value is passed transparently through all the intermediate layers
                     of template rules until it reaches the rule with <code nobreak="false">match="equation"</code>.
                     The effect is similar to using a global variable, except that the parameter can
                     take different values during different phases of the transformation.</p></example></div3></div2><div2 id="attribute-sets"><head>Named Attribute Sets</head><e:element-syntax xmlns:e="http://www.w3.org/1999/XSL/Spec/ElementSyntax" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" name="attribute-set">
      <e:in-category name="declaration"/>
      <e:attribute name="name" required="yes">
         <e:data-type name="eqname"/>
      </e:attribute>
      <e:attribute name="use-attribute-sets" default="''">
         <e:data-type name="eqnames"/>
      </e:attribute>
      <e:attribute name="visibility" default="'private'">
         <e:constant value="public"/>
         <e:constant value="private"/>
         <e:constant value="final"/>
         <e:constant value="abstract"/>
      </e:attribute>
      <e:attribute name="streamable" default="'no'">
         <e:data-type name="boolean"/>
      </e:attribute>
      <e:element repeat="zero-or-more" name="attribute"/>
      <e:allowed-parents>
         <e:parent name="package"/>
         <e:parent name="stylesheet"/>
         <e:parent name="transform"/>
         <e:parent name="override"/>
      </e:allowed-parents>
   </e:element-syntax><p>Attribute sets generate named collections of attributes that can be used repeatedly on
               different constructed elements. The <elcode>xsl:attribute-set</elcode> declaration is
               used to declare attribute sets. The <rfc2119>required</rfc2119>
               <code nobreak="false">name</code> attribute specifies the name of the attribute set. The value of the
                  <code nobreak="false">name</code> attribute is an <code nobreak="false">EQName</code>, which is expanded as
               described in <specref ref="qname"/>.</p><p>
               <termdef id="dt-attribute-set" term="attribute set">An <term>attribute set</term> is
                  defined as a set of <elcode>xsl:attribute-set</elcode> declarations in the same
                     <termref def="dt-package"/> that share the same <termref def="dt-expanded-qname"/>.</termdef>
            </p><p>The content of the <elcode>xsl:attribute-set</elcode> element consists of zero or
               more <elcode>xsl:attribute</elcode> instructions that are evaluated to produce the
               attributes in the set.</p><p>The effect of the <code nobreak="false">streamable</code> attribute is explained in 
            <xspecref spec="SG40" ref="streamability-of-attribute-sets"/>.</p><div3 id="using-attribute-sets"><head>Using Attribute Sets</head><p>
                  <termref def="dt-attribute-set">Attribute sets</termref> are used by specifying a
                     <code nobreak="false">use-attribute-sets</code> attribute on the <elcode>xsl:element</elcode>
                  or <elcode>xsl:copy</elcode> instruction, or by specifying an
                     <code nobreak="false">xsl:use-attribute-sets</code> attribute on a literal result element. An
                  attribute set may be defined in terms of other attribute sets by using the
                     <code nobreak="false">use-attribute-sets</code> attribute on the
                     <elcode>xsl:attribute-set</elcode> element itself. The value of the
                     <code nobreak="false">[xsl:]use-attribute-sets</code> attribute is in each case a
                  whitespace-separated list of names of attribute sets. Each name is specified as an
                     <termref def="dt-eqname">EQName</termref>,
                  which is expanded as described in <specref ref="qname"/>.</p><p>
                  <error spec="XT" type="static" class="SE" code="0710"><p>It is a <termref def="dt-static-error">static error</termref> if the value
                        of the <code nobreak="false">use-attribute-sets</code> attribute of an
                           <elcode>xsl:copy</elcode>, <elcode>xsl:element</elcode>, or
                           <elcode>xsl:attribute-set</elcode> element, or the
                           <code nobreak="false">xsl:use-attribute-sets</code> attribute of a <termref def="dt-literal-result-element">literal result element</termref>, is not
                        a whitespace-separated sequence of <termref def="dt-eqname">EQNames</termref>, or if it contains an
                        EQName that does not match the <code nobreak="false">name</code> attribute of any
                           <elcode>xsl:attribute-set</elcode> declaration in the containing <termref def="dt-package">package</termref>.</p></error>
               </p><p>An <termref def="dt-attribute-set"/> may be considered
                  as comprising a sequence of instructions, each of which is either an
                     <elcode>xsl:attribute</elcode> instruction or an <termref def="dt-attribute-set-invocation"/>. Starting with the declarations making up
                  an attribute set, this sequence of instructions can be generated by the following
                  rules: </p><olist><item><p>The relevant attribute set <termref def="dt-declaration">declarations</termref> (that is, all declarations of attribute sets
                        within a package sharing the same <termref def="dt-expanded-qname"/>) are
                        considered in order: first in increasing order of <termref def="dt-import-precedence"/>, and within each precedence, in <termref def="dt-declaration-order"/>. </p></item><item><p>Each declaration is expanded to a sequence of instructions as follows.
                        First, one <termref def="dt-attribute-set-invocation"/> is generated for
                        each EQName present in the <code nobreak="false">use-attribute-sets</code> attribute, if
                        present, retaining the order in which the EQNames appear. This is followed
                        by the sequence of contained <elcode>xsl:attribute</elcode> instructions, in
                        order. </p><p><termdef id="dt-attribute-set-invocation" term="attribute set invocation">An
                              <term>attribute set invocation</term> is a pseudo-instruction
                           corresponding to a single EQName appearing within an
                              <code nobreak="false">[xsl:]use-attribute-sets</code> attribute; the effect of the
                           pseudo-instruction is to cause the referenced <termref def="dt-attribute-set"/> to be evaluated.</termdef></p></item></olist><p>Similarly, an <code nobreak="false">[xsl:]use-attribute-sets</code>
                  attribute of an <elcode>xsl:copy</elcode>, <elcode>xsl:element</elcode>, or
                     <elcode>xsl:attribute-set</elcode> element, or of a literal result element, is
                  expanded to a sequence of <termref def="dt-attribute-set-invocation">attribute set
                     invocations</termref>, one for each EQName in order. </p><p>An <termref def="dt-attribute-set"/> is a named
                     <termref def="dt-component"/>, and the binding of QNames appearing in an
                     <termref def="dt-attribute-set-invocation"/> to attribute set components
                  follows the rules in <specref ref="component-references"/>. </p><p>The following two (mutually recursive) rules define how
                  an <code nobreak="false">[xsl:]use-attribute-set</code> attribute is expanded:</p><olist><item><p>An <termref def="dt-attribute-set"/> is evaluated by evaluating each of the
                        contained <termref def="dt-attribute-set-invocation">attribute set
                           invocations</termref> and <elcode>xsl:attribute</elcode> instructions in
                        order, to deliver a sequence of attribute nodes. </p></item><item><p>An <termref def="dt-attribute-set-invocation"/> is evaluated by evaluating
                        the <termref def="dt-attribute-set"/> to which it is bound, as determined by
                        the rules in <specref ref="component-references"/>. </p></item></olist><p>For rules regarding cycles in attribute set
                  declarations, see <specref ref="circularity"/>.</p><note><p>The effect of an <termref def="dt-attribute-set-invocation"/> on the dynamic
                     context is the same as the effect of an <elcode>xsl:call-template</elcode>
                     instruction. In particular, it does not change the <termref def="dt-focus"/>.
                     Although attribute sets are often defined with fixed values, or with values
                     that depend only on global variables, it is possible to define an attribute set
                     in such a way that the values of the constructed attributes are dependent on
                     the context item.</p></note><note><p>In all cases the result of evaluating an <termref def="dt-attribute-set"/> is
                     subsequently used to create the attributes of an element node, using the rules
                     in <specref ref="constructing-complex-content"/>. The effect of those rules is
                     that when the result of evaluating the attribute set contains attributes with
                     duplicate names, the last duplicate wins. The optimization rules allow a
                     processor to avoid evaluating or validating an attribute if it is able to
                     determine that the attribute will subsequently be discarded as a duplicate.
                  </p></note></div3><div3 id="visibility-of-attribute-sets"><head>Visibility of Attribute Sets</head><p>The <code nobreak="false">visibility</code> attribute determines the
                  visibility of the attribute set in packages other than the containing
                  package. If the <code nobreak="false">visibility</code> attribute is present on any of the
                     <elcode>xsl:attribute-set</elcode> declarations making up the definition of an
                     <termref def="dt-attribute-set"/> (that is, all declarations within the same
                  package sharing the same name), then it <rfc2119>must</rfc2119> be present, with
                  the same value, on every <elcode>xsl:attribute-set</elcode> declaration making up
                  the definition of that <termref def="dt-attribute-set"/>.</p><p>If the <code nobreak="false">visibility</code> attribute is present with the
                  value <code nobreak="false">abstract</code> then there must be no <elcode>xsl:attribute</elcode>
                  children and no <code nobreak="false">use-attribute-sets</code>
                     attribute.</p></div3><div3 id="evaluating-attribute-sets"><head>Evaluating Attribute Sets</head><p>Attribute sets are evaluated as follows:</p><ulist><item><p>The <elcode>xsl:copy</elcode> and <elcode>xsl:element</elcode> instructions
                        have a <code nobreak="false">use-attribute-sets</code> attribute. The sequence of attribute
                        nodes produced by evaluating this attribute is prepended to the sequence
                        produced by evaluating the <termref def="dt-sequence-constructor">sequence
                           constructor</termref> contained within the instruction.</p></item><item><p>
                        <termref def="dt-literal-result-element">Literal result elements</termref>
                        allow an <code nobreak="false">xsl:use-attribute-sets</code> attribute, which is evaluated
                        in the same way as the <code nobreak="false">use-attribute-sets</code> attribute of
                           <elcode>xsl:element</elcode> and <elcode>xsl:copy</elcode>. The sequence
                        of attribute nodes produced by evaluating this attribute is prepended to the
                        sequence of attribute nodes produced by evaluating the attributes of the
                        literal result element, which in turn is prepended to the sequence produced
                        by evaluating the <termref def="dt-sequence-constructor">sequence
                           constructor</termref> contained with the literal result element.</p></item></ulist><p>The <elcode>xsl:attribute</elcode> instructions are evaluated using the same
                     <termref def="dt-focus">focus</termref> as is used for evaluating the 
                  <termref def="dt-sequence-constructor"/> contained by the
                  element that is the parent of the <code nobreak="false">[xsl:]use-attribute-sets</code> attribute forming
                  the initial input to the algorithm. However, the static context for the evaluation
                  depends on the position of the <elcode>xsl:attribute</elcode> instruction in the
                  stylesheet: thus, only local variables declared within an
                     <elcode>xsl:attribute</elcode> instruction, and global variables, are
                  visible.</p><note><p>The above rule means that for an <elcode>xsl:copy</elcode>
               element with a <code nobreak="false">select</code> attribute, the focus for evaluating any referenced attribute
               sets is the node selected by the <code nobreak="false">select</code> attribute, rather than the context item of 
                  the <elcode>xsl:copy</elcode> instruction.</p></note><p>The set of attribute nodes produced by expanding
                     <code nobreak="false">xsl:use-attribute-sets</code> may include several attributes with the
                  same name. When the attributes are added to an element node, only the last of the
                  duplicates will take effect.</p><p>The way in which each instruction uses the results of expanding the
                     <code nobreak="false">[xsl:]use-attribute-sets</code> attribute is described in the
                  specification for the relevant instruction: see <specref ref="literal-result-element"/>, <specref ref="xsl-element"/>, and <specref ref="copying"/>.</p><p>The result of evaluating an attribute set is a sequence of attribute nodes.
                  Evaluating the same attribute set more than once can produce different results,
                  because although an attribute set does not have parameters, it may contain
                  expressions or instructions whose value depends on the evaluation context.</p><p>Each attribute node produced by expanding an attribute set has a <termref def="dt-type-annotation"/> determined by the rules for the
                     <elcode>xsl:attribute</elcode> instruction that created the attribute node: see
                     <specref ref="annotation-for-constructed-attribute"/>. These type annotations
                  may be preserved, stripped, or replaced as determined by the rules for the
                  instruction that creates the element in which the attributes are used.</p></div3><div3 id="attribute-sets-examples"><head>Attribute Sets: Examples</head><example><head>A Simple Attribute Set</head><p>The following example creates a named <termref def="dt-attribute-set">attribute
                        set</termref>
                     <code nobreak="false">title-style</code> and uses it in a <termref def="dt-template-rule">template rule</termref>.</p><eg xml:space="preserve" role="xslt-declaration xmlns:fo='fo'">&lt;xsl:template match="chapter/heading"&gt;
  &lt;fo:block font-stretch="condensed" xsl:use-attribute-sets="title-style"&gt;
    &lt;xsl:apply-templates/&gt;
  &lt;/fo:block&gt;
&lt;/xsl:template&gt;

&lt;xsl:attribute-set name="title-style"&gt;
  &lt;xsl:attribute name="font-size"&gt;12pt&lt;/xsl:attribute&gt;
  &lt;xsl:attribute name="font-weight"&gt;bold&lt;/xsl:attribute&gt;
&lt;/xsl:attribute-set&gt;</eg></example><example><head>Overriding Attributes in an Attribute Set</head><p>The following example creates a named attribute set <code nobreak="false">base-style</code> and
                     uses it in a template rule with multiple specifications of the attributes:</p><glist><gitem><label>font-family</label><def><p>is specified only in the attribute set</p></def></gitem><gitem><label>font-size</label><def><p>is specified in the attribute set, is specified on the literal result
                              element, and in an <elcode>xsl:attribute</elcode> instruction</p></def></gitem><gitem><label>font-style</label><def><p>is specified in the attribute set, and on the literal result
                              element</p></def></gitem><gitem><label>font-weight</label><def><p>is specified in the attribute set, and in an
                                 <elcode>xsl:attribute</elcode> instruction</p></def></gitem></glist><p>Stylesheet fragment:</p><eg xml:space="preserve" role="xslt-declaration xmlns:fo='fo'">&lt;xsl:attribute-set name="base-style"&gt;
  &lt;xsl:attribute name="font-family"&gt;Univers&lt;/xsl:attribute&gt;
  &lt;xsl:attribute name="font-size"&gt;10pt&lt;/xsl:attribute&gt;
  &lt;xsl:attribute name="font-style"&gt;normal&lt;/xsl:attribute&gt;
  &lt;xsl:attribute name="font-weight"&gt;normal&lt;/xsl:attribute&gt;
&lt;/xsl:attribute-set&gt;

&lt;xsl:template match="o"&gt;
  &lt;fo:block xsl:use-attribute-sets="base-style"
            font-size="12pt"
            font-style="italic"&gt;
    &lt;xsl:attribute name="font-size"&gt;14pt&lt;/xsl:attribute&gt;
    &lt;xsl:attribute name="font-weight"&gt;bold&lt;/xsl:attribute&gt;
    &lt;xsl:apply-templates/&gt;
  &lt;/fo:block&gt;
&lt;/xsl:template&gt;</eg><p>Result:</p><eg xml:space="preserve" role="non-xml">&lt;fo:block font-family="Univers"
          font-size="14pt"
          font-style="italic"
          font-weight="bold"&gt;
...
&lt;/fo:block&gt;
</eg></example></div3></div2><div2 id="stylesheet-functions"><head>Stylesheet Functions</head><changes><change issue="155" PR="159" date="2022-09-30">Parameters on functions
               declared using <elcode>xsl:function</elcode> can now be defined as optional,
               with a default value supplied.</change><change issue="657" PR="2200" date="2025-09-23">User-defined functions can now have names that are in
               no namespace. An unprefixed name appearing in a function call is resolved
               to a no-namespace function with matching local name in preference to
               a function in the standard <code nobreak="false">fn</code> namespace.</change></changes><p diff="add" at="variadicity">
               <termdef id="dt-stylesheet-function" term="stylesheet function">An
                     <elcode>xsl:function</elcode> declaration declares the name, parameters, and
                  implementation of a family of <term>stylesheet functions</term> that can be called from any
                  XPath <termref def="dt-expression">expression</termref> within the <termref def="dt-stylesheet">stylesheet</termref>
                  (subject to visibility rules).</termdef>
            </p><e:element-syntax xmlns:e="http://www.w3.org/1999/XSL/Spec/ElementSyntax" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" name="function">
      <e:in-category name="declaration"/>
      <e:attribute name="name" required="yes">
         <e:data-type name="eqname"/>
      </e:attribute>
      <e:attribute name="as" required="no" default="'item()*'">
         <e:data-type name="sequence-type"/>
      </e:attribute>
      <e:attribute name="visibility" required="no" default="'private'">
         <e:constant value="public"/>
         <e:constant value="private"/>
         <e:constant value="final"/>
         <e:constant value="abstract"/>
      </e:attribute>
      <e:attribute name="streamability" required="no" default="'unclassified'">
         <e:constant value="unclassified"/>
         <e:constant value="absorbing"/>
         <e:constant value="inspection"/>
         <e:constant value="filter"/>
         <e:constant value="shallow-descent"/>
         <e:constant value="deep-descent"/>
         <e:constant value="ascent"/>
         <e:data-type name="eqname"/>
      </e:attribute>
      <e:attribute name="override-extension-function" required="no" default="'yes'">
         <e:data-type name="boolean"/>
      </e:attribute>
      <e:attribute name="override" required="no" deprecated="yes" default="'yes'">
         <e:data-type name="boolean"/>
      </e:attribute>
      <e:attribute name="new-each-time" required="no">
         <e:constant value="yes"/>
         <e:constant value="true"/>
         <e:constant value="1"/>
         <e:constant value="no"/>
         <e:constant value="false"/>
         <e:constant value="0"/>
         <e:constant value="maybe"/>
      </e:attribute>
      <e:attribute name="cache" required="no" default="'no'">
         <e:data-type name="boolean"/>
      </e:attribute>
      <e:sequence>
         <e:element repeat="zero-or-more" name="param"/>
         <e:model name="sequence-constructor"/>
      </e:sequence>
      <e:allowed-parents>
         <e:parent name="package"/>
         <e:parent name="stylesheet"/>
         <e:parent name="transform"/>
         <e:parent name="override"/>
      </e:allowed-parents>
   </e:element-syntax><p diff="add" at="variadicity">The effect of an <elcode>xsl:function</elcode> declaration is to add a 
               <termref def="dt-function-definition"/>
               to the static context for all XPath <termref def="dt-expression">expressions</termref> 
               used in the <termref def="dt-stylesheet">stylesheet</termref> (including an XPath expression used
               within a predicate in a <termref def="dt-pattern">pattern</termref>).</p><p>The content of the <elcode>xsl:function</elcode> element consists of zero or more
               <elcode>xsl:param</elcode> elements that specify the formal parameters of the
               function, followed by a <termref def="dt-sequence-constructor">sequence
                  constructor</termref> that defines the value to be returned by the function.</p><p>The children and attributes of the <elcode>xsl:function</elcode> declaration translate directly
               into properties of the <termref def="dt-function-definition"/>:</p><ulist><item><p>The <code nobreak="false">xsl:function/@name</code> attribute defines the function’s name.</p></item><item><p>The <code nobreak="false">xsl:param</code> children define the function’s parameters:</p><ulist><item><p>The <code nobreak="false">xsl:param/@name</code> attribute defines the name of the parameter.</p></item><item><p>The <code nobreak="false">xsl:param/@required</code> attribute determines whether the parameter is mandatory or optional.</p></item><item><p>The <code nobreak="false">xsl:param/@as</code> attribute determines the required type of the parameter.</p></item><item><p>The <code nobreak="false">xsl:param/@select</code> attribute determines a default value for an optional parameter.</p></item></ulist></item><item><p>The <code nobreak="false">xsl:function/@as</code> attribute defines the return type of the function.</p></item><item><p>The implementation of the function is defined by the <termref def="dt-sequence-constructor"/> content
               of the <elcode>xsl:function</elcode> element.</p></item></ulist><p>An <elcode>xsl:function</elcode> declaration can only appear as a <termref def="dt-top-level"/> element in a stylesheet module.</p><div3 id="xsl-function-name" diff="chg" at="variadicity"><head>Function Name and Arity</head><changes><change issue="657 2235" PR="2200 2236" date="2025-10-07">
                     Stylesheet functions may now be in no namespace, and may be invoked without
                     use of a namespace prefix, provided they are private to a package.
                  </change></changes><p>The name of the function is given by the <code nobreak="false">name</code>
                  attribute.</p><p>
                  <error spec="XT" type="static" class="SE" code="0740"><p>It is a <termref def="dt-static-error">static error</termref> if a <termref def="dt-stylesheet-function">stylesheet function</termref> has a name
                        that is in no namespace, unless the <termref def="dt-visibility"/>
                     of the function is <code nobreak="false">private</code>.</p></error></p><note><p>XSLT 4.0 allows the function name to be unprefixed, provided that its
                  <termref def="dt-visibility"/> is <code nobreak="false">private</code>. This represents a QName
               in no namespace. A function call using an unprefixed function name is resolved to
               a no-namespace function name in preference to a function in the default function namespace,
               which for XSLT is always the <code nobreak="false">fn</code> namespace.</p></note><note><p>To prevent the namespace URI used for the function name appearing in
                     the result document, use the <code nobreak="false">exclude-result-prefixes</code> attribute on
                     the <elcode>xsl:stylesheet</elcode> element: see <specref ref="lre-namespaces"/>.</p><p>The name of the function must not be in a <termref def="dt-reserved-namespace">reserved namespace</termref>: <errorref spec="XT" class="SE" code="0080"/>
                  </p></note><p>The function parameters are defined by child <elcode>xsl:param</elcode> elements. The parameters must have distinct names.
                  The list of parameters must contain zero or more required parameters, followed by zero or more optional parameters.
                  A parameter is optional if it has the attribute <code nobreak="false">required="no"</code>; otherwise, it is required.</p><p>The default value for an optional parameter can be defined using the <code nobreak="false">select</code> attribute or the 
               contained <termref def="dt-sequence-constructor"/> of the <elcode>xsl:param</elcode> element. These must be absent
               for a required parameter. If an optional parameter has no <code nobreak="false">select</code> attribute and the contained sequence
               constructor is empty, then the default value will be the empty sequence. This will lead to a type error if the
               required type of the parameter does not permit the empty sequence.</p><note diff="add" at="2022-01-01"><p>When considering function overriding, dynamic function calls,
                  and details such as the <code nobreak="false">function-lookup</code> function, it is useful to think
                  of an <elcode>xsl:function</elcode> declaration with optional parameters as a syntactic 
                  short-cut for a set of <elcode>xsl:function</elcode> declarations of varying arity, each
                  of which calls the function with next-higher arity, supplying the default value of the parameter
                  explicitly in the function call.</p><p diff="chg" at="2023-05-19">This is not an exact equivalence, however, because of the rules allowing default values
                     of function parameters to be context-dependent.</p></note><p>The <termref def="dt-function-definition"/> derived from the 
                  <elcode>xsl:function</elcode> declaration has an <termref def="dt-arity-range"/>
                  from <var>M</var> to <var>M</var>+<var>N</var>, where <var>M</var> is the number of required parameters
                  and <var>N</var> is the number of optional parameters. The arity range constrains the number of arguments
               that may appear in a call to this function.</p><p diff="add" at="2022-01-01">For example, the following <elcode>xsl:function</elcode> declaration
               declares a function, named <code nobreak="false">f:compare</code>, with an arity range of (2 to 3). 
                  The effect of calling <code nobreak="false">f:compare($a, $b)</code> is the same as the effect
               of calling <code nobreak="false">f:compare($a, $b, { "order": "ascending" })</code>.</p><eg xml:space="preserve">
&lt;xsl:function name="f:compare" as="xs:boolean"&gt;
  &lt;xsl:param name="arg1" as="xs:double"/&gt;
  &lt;xsl:param name="arg2" as="xs:double"/&gt;
  &lt;xsl:param name="options" as="map(*)" 
             required="no" 
             select="{ 'order': 'ascending' }"/&gt;
  &lt;xsl:if test="$options?order = 'descending'" 
          then="$arg1 gt $arg2" 
          else="$arg2 gt $arg1"/&gt;
&lt;/xsl:function&gt;</eg><note><p>Functions are not polymorphic. Although the XPath function call mechanism
                     allows two functions to have the same name and 
                     <phrase diff="chg" at="2022-11-26">non-overlapping <termref def="dt-arity-range">arity ranges</termref></phrase>, 
                     it does not allow them to be distinguished
                     by the types of their arguments.</p></note></div3><div3 id="function-arguments"><head>Parameters</head><p diff="chg" at="variadicity">The <elcode>xsl:param</elcode> elements define the formal parameters to the
                  function. In a static function call, these are referenced either positionally or by name.
                  The rules for associating arguments in a static function call with parameter definitions
                  in the function declaration are given in <xspecref spec="XP40" ref="id-eval-static-function-call"/>.</p><p>
                  <error spec="XT" type="static" class="SE" code="0760"><p>It is a static error if an <elcode>xsl:param</elcode> child of
                        an <elcode>xsl:function</elcode> element has either a <code nobreak="false">select</code>
                        attribute or non-empty content<phrase diff="add" at="2022-01-01">, unless it
                        specifies <code nobreak="false">required="no"</code>.</phrase></p></error>
               </p><p diff="add" at="2022-01-01">
                  <error spec="XT" type="static" class="SE" code="0761"><p>It is a static error if an <elcode>xsl:param</elcode> child of
                        an <elcode>xsl:function</elcode> element specifies
                     <code nobreak="false">required="no"</code>, unless all following-sibling
                        <elcode>xsl:param</elcode> elements also specify <code nobreak="false">required="no"</code>.</p></error>
               </p><p>The <code nobreak="false">as</code> attribute of the <elcode>xsl:param</elcode> element defines
                  the required type of the parameter. The rules for converting the values of the
                  actual arguments supplied in the function call to the types required by each
                     <elcode>xsl:param</elcode> element, and the
                     errors that can occur, are defined in <bibref ref="xpath-40"/>. The
                  rules that apply are those for the case where <termref def="dt-xpath-compat-mode">XPath 1.0 compatibility mode</termref> is set to <code nobreak="false">false</code>.</p><p>If the <code nobreak="false">as</code> attribute is omitted, no conversion takes place and any
                  value is accepted.</p><p diff="add" at="2023-05-19">The default value for an optional parameter 
                  (one with <code nobreak="false">required="no"</code>) will often be supplied using a 
                  simple literal or constant expression, for example
                  <code nobreak="false">&lt;xsl:param name="married" as="xs:boolean" select="false()"/&gt;</code>,
                  or <code nobreak="false">&lt;xsl:param name="options" as="map(*)" select="{}"/&gt;</code>. 
                  However, to allow greater flexibility,
                  the default value can also be context-dependent. For example, 
                  <code nobreak="false">&lt;xsl:param name="node" as="node()" select="."/&gt;</code> declares a parameter whose
                  default value is the context item from the dynamic context of the caller, while 
                  <code nobreak="false">&lt;xsl:param name="collation" as="xs:string" select="default-collation()"/&gt;</code>
                  declares a parameter whose default value is the default collation from the dynamic context of the caller.
                  The detailed rules are as follows. In these rules, the term <term>caller</term> means the function call or function reference
                  that invokes the function being defined.</p><p diff="add" at="2023-05-19">The <xtermref spec="XP40" ref="dt-static-context"/> for the 
                  initializing expression of an optional parameter of an <elcode>xsl:function</elcode> declaration
                  is the same as the static context for a <termref def="dt-static-expression"/>.</p><p diff="add" at="2023-05-19">The <xtermref spec="XP40" ref="dt-dynamic-context"/> for the initializing 
                  expression of an optional parameter 
                  is the same as the dynamic context for the evaluation of a <termref def="dt-static-expression"/>, 
                  with the following exceptions:</p><ulist diff="add" at="2023-05-19"><item><p>The <xtermref spec="XP40" ref="dt-context-value"/>, <xtermref spec="XP40" ref="dt-context-position"/>,
                     and <xtermref spec="XP40" ref="dt-context-size"/> are taken from the dynamic context of the caller.</p></item><item><p>The <xtermref spec="XP40" ref="dt-def-collation"/> and <xtermref spec="XP40" ref="dt-executable-base-uri"/>
                  are taken from the dynamic context of the caller.</p></item></ulist><note><p>The effect of these rules is that the <code nobreak="false">select</code> expression for an optional parameter
               is evaluated in the same way as a static expression, except that it may contain context-dependent
               subexpressions such as <code nobreak="false">.</code>, <code nobreak="false">position()</code>, <code nobreak="false">last()</code>,
               <code nobreak="false">static-base-uri()</code>, and <code nobreak="false">default-collation()</code> to access the
               dynamic context of the caller. It may also contain expressions such as <code nobreak="false">name()</code>
               or <code nobreak="false">@x = "abc"</code> that have an implicit dependency on the dynamic context of the caller.</p></note></div3><div3 id="function-result"><head>Function Result</head><p>The result of the function<phrase diff="add" at="2022-01-01">, if all arguments are supplied,</phrase> 
                  is the result of evaluating the contained <termref def="dt-sequence-constructor"/>.</p><p diff="add" at="2022-01-01">If a reduced-arity form of the function is invoked by omitting optional arguments, then
               the result of the function is obtained by evaluating the sequence constructor after binding the
               omitted arguments to their default values, which are obtained by evaluating the <code nobreak="false">select</code>
               attribute or sequence constructor of the relevant <elcode>xsl:param</elcode> element, as
               described in <specref ref="default-values-of-parameters"/>.</p><p>Within the sequence constructor, the <termref def="dt-focus">focus</termref> is
                  initially <termref def="dt-absent">absent</termref>; this means that any attempt
                  to reference the context item, context position, or context size is a 
                  <termref def="dt-type-error"/>. (See <xerrorref spec="XP40" class="DY" code="0002"/>.)</p><p>It is not possible within the body of the <termref def="dt-stylesheet-function">stylesheet function</termref> to access the values of local variables that
                  were in scope in the place where the function call was written. Global variables,
                  however, remain available.</p><p>The optional <code nobreak="false">as</code> attribute indicates the <termref def="dt-required-type">required type</termref> of the result of the function.
                  The value of the <code nobreak="false">as</code> attribute is a
                  <termref def="dt-sequence-type"/>.</p><p>
                  <error spec="XT" type="type" class="TE" code="0780"><p>If the <code nobreak="false">as</code> attribute <error.extra>of
                              <elcode>xsl:function</elcode>
                        </error.extra> is specified, then the result evaluated by the <termref def="dt-sequence-constructor">sequence constructor</termref> (see
                           <specref ref="sequence-constructors"/>) is converted to the required
                        type, using the <termref def="dt-coercion-rules"/>. It is a <termref def="dt-type-error">type
                           error</termref> if this conversion fails.</p></error> If the <code nobreak="false">as</code> attribute is omitted, the calculated result is
                  used as supplied, and no conversion takes place.</p><note><p>Using the <elcode>xsl:value-of</elcode> instruction to deliver the function
               result is generally a mistake, except in the rare case where the function is actually
               intended to return a text node. For functions that return atomic items such as strings,
               numbers, or booleans, using <elcode>xsl:sequence</elcode> or <elcode>xsl:select</elcode>
               is generally better because it avoids wrapping the value in a text node and then immediately
               unwrapping it again, with possible loss of type information.</p></note></div3><div3 id="function-visibility-and-overriding"><head>Visibility and Overriding of Functions</head><p>It is possible to have multiple function declarations sharing the same function name and arity:</p><ulist><item><p>Multiple <elcode>xsl:function</elcode> declarations 
                     are allowed within a single <termref def="dt-package"/> if they have different
                     <termref def="dt-import-precedence"/>.</p></item><item><p>A function declared using <elcode>xsl:function</elcode>
                  may have the same name and arity as an <termref def="dt-extension-function"/>.</p></item><item><p>A function declared within one package may be overridden
                  (using <elcode>xsl:override</elcode>) in another package.</p></item></ulist><p>The rules governing these three scenarios are given in the sections that follow.</p><div4 id="function-overriding-within-package"><head>Overriding Functions within a Package</head><p>Two stylesheet functions with the same name may appear in a package if their
                  <termref def="dt-arity-range">arity ranges</termref> do not overlap. Neither overrides the other;
                  the function that is selected is determined by the arity of the function call or function reference.</p><p>In addition, a stylesheet function may be overridden by another stylesheet function with the same name that
                     has higher <termref def="dt-import-precedence"/>. Such overriding is only allowed, however, if the 
                     <termref def="dt-arity-range"/> of the overriding function
                     includes the totality of the arity range of the overridden function.</p><p><termdef id="dt-eclipsed" term="eclipsed">An <elcode>xsl:function</elcode> declaration
                     <var>F</var> is said to be <term>eclipsed</term> if the containing package includes 
                     an <elcode>xsl:function</elcode> declaration
                     <var>G</var> such that <var>F</var> and <var>G</var> have the same name, <var>F</var> has lower
                     <termref def="dt-import-precedence"/> than <var>G</var>, and the <termref def="dt-arity-range"/>
                     of <var>G</var> includes the totality of the arity range of <var>F</var>.</termdef></p><p>
                     <error spec="XT" type="static" class="SE" code="0769"><p>It is a <termref def="dt-static-error">static error</termref> for a <termref def="dt-package">package</termref> to
                           contain an <elcode>xsl:function</elcode>
                           declaration <var>F</var> and an <elcode>xsl:function</elcode> declaration
                           <var>G</var> such that <var>F</var> and <var>G</var> have the same 
                           <termref def="dt-expanded-qname"/>, <var>F</var> has lower
                           <termref def="dt-import-precedence"/> than <var>G</var>, and the 
                           <termref def="dt-arity-range"/>
                           of <var>G</var> includes part but not all of the arity range of <var>F</var>,
                           unless <var>G</var> is itself <termref def="dt-eclipsed"/> by another 
                           <elcode>xsl:function</elcode> declaration.</p></error>
                  </p><p>
                     <error spec="XT" type="static" class="SE" code="0770"><p>It is a <termref def="dt-static-error">static error</termref> for a <termref def="dt-package">package</termref> to
                           contain an <elcode>xsl:function</elcode>
                           declaration <var>F</var> and an <elcode>xsl:function</elcode> declaration
                           <var>G</var> such that <var>F</var> and <var>G</var> have the same 
                           <termref def="dt-expanded-qname"/> and the same
                           <termref def="dt-import-precedence"/>, if the 
                           <termref def="dt-arity-range">arity ranges</termref>
                           of <var>F</var> and <var>G</var> overlap in whole or in part, 
                           unless <var>F</var> and <var>G</var> are both <termref def="dt-eclipsed"/> by another 
                           <elcode>xsl:function</elcode> declaration.</p></error>
                  </p><p diff="add" at="2023-03-24">Similarly it is a static error
                     <errorref spec="XT" class="DE" code="0770"/> for 
                           a <termref def="dt-package">package</termref> to
                           contain an <elcode>xsl:function</elcode>
                     declaration <var>F</var> that is not <termref def="dt-eclipsed"/> by another 
                     <elcode>xsl:function</elcode> declaration, if its name and arity range conflict
                           with a constructor function in the static context. There will be a constructor
                  function (with arity 1) in the static context for every atomic type or plain union type
                  in the <termref def="dt-in-scope-schema-component">in-scope schema components</termref>.
                  </p></div4><div4 id="overriding-extension-functions"><head>Overriding Extension Functions</head><p>The optional <code nobreak="false">override-extension-function</code> attribute defines what
                     happens if an <elcode>xsl:function</elcode> declaration has the same name and 
                     overlapping <termref def="dt-arity-range"/> 
                     as a function provided by the implementer or made available in
                     the static context using an implementation-defined mechanism. If the <code nobreak="false">override-extension-function</code> attribute
                     has the value <code nobreak="false">yes</code>, then this function is used in preference; if it
                     has the value <code nobreak="false">no</code>, then the other function is used in preference. The
                     default value is <code nobreak="false">yes</code>.</p><note><p>Specifying <code nobreak="false">override-extension-function="yes"</code> ensures
                        interoperable behavior: the same code will execute with all processors.
                        Specifying <code nobreak="false">override-extension-function="no"</code> is useful when
                        writing a fallback implementation of a function that is available with some
                        processors but not others: it allows the vendor’s implementation of the
                        function (or a user’s implementation written as an extension function)
                        to be used in preference to the stylesheet implementation, which is useful when
                        the extension function is more efficient.</p><p>The <code nobreak="false">override-extension-function</code> attribute does <emph>not</emph>
                        affect the rules for deciding which of several <termref def="dt-stylesheet-function">stylesheet functions</termref> with the same
                        name and overlapping <termref def="dt-arity-range">arity range</termref> takes precedence.</p></note><p>The <code nobreak="false">override</code> attribute is a <termref def="dt-deprecated"/> synonym of <code nobreak="false">override-extension-function</code>,
                     retained for compatibility with XSLT 2.0. If both attributes are present then they
                     <rfc2119>must</rfc2119> have the same value.</p></div4><div4 id="overriding-functions-in-used-packages"><head>Overriding Functions in a Used Package</head><p>When a package is referenced in <elcode>xsl:use-package</elcode>, functions
               declared in the used package become available in the using package, conditional
               on their declared <termref def="dt-visibility">visibility</termref>, as described 
                  in <specref ref="packages"/>.</p><p>If the <code nobreak="false">visibility</code> attribute of <elcode>xsl:function</elcode> is present with the
                  value <code nobreak="false">abstract</code> then the <termref def="dt-sequence-constructor"/>
                  defining the function body <rfc2119>must</rfc2119> be empty.</p><p>The XPath specification states that the function that is executed as the result of
                  a function call is identified by looking in the static context for a 
                  <termref def="dt-function-definition"/> whose name and <termref def="dt-arity-range"/>
                  match the name and number of arguments in the function call. In XSLT 3.0, final determination of the function to be called cannot be
                     made until all packages have been assembled: see <specref ref="component-references"/>.</p><note><p>XSLT 4.0 allows a <termref def="dt-stylesheet-function"/> to be in no namespace,
                  provided that its <termref def="dt-visibility">visibility</termref> is local to a package.
                  A static function call or named function reference using an unprefixed lexical QName
                  is resolved first by looking for no-namespace functions,
                  then for functions in the standard namespace <code nobreak="false">http://www.w3.org/2005/xpath-functions</code>.
                  A no-namespace function might be a private <termref def="dt-stylesheet-function"/>
                  declared within the same package, or it might be (for example) a constructor function
                  for a user-defined atomic type in an imported no-namespace schema; it will never, however,
                  be a <termref def="dt-stylesheet-function"/> imported or overridden from a different package,
                  so the rules for referencing functions across packages do not come into play.</p></note><p>An <elcode>xsl:function</elcode> declaration defines a
                  <termref def="dt-stylesheet-function"/> which forms a
                     <termref def="dt-component"/> in its containing <termref def="dt-package"/>,
                  unless </p><ulist><item><p>it is <termref def="dt-eclipsed"/>, or</p></item><item><p>the <code nobreak="false">override-extension-function</code> or <code nobreak="false">override</code>
                        attribute has the value <code nobreak="false">no</code> and there is already a 
                        <termref def="dt-function-definition"/> 
                        with the same name and an overlapping <termref def="dt-arity-range"/>
                         in the static context.</p></item></ulist><p>The optional <code nobreak="false">override-extension-function</code> attribute defines what
                  happens if this function has the same name and an 
                  <phrase diff="chg" at="2022-11-27"><termref def="dt-arity-range">arity range</termref> that conflicts 
                  with a function</phrase> provided by the implementer or made available in
                  the static context using an implementation-defined mechanism. If the <code nobreak="false">override-extension-function</code> attribute
                  has the value <code nobreak="false">yes</code>, then this function is used in preference; if it
                  has the value <code nobreak="false">no</code>, then the other function is used in preference. The
                  default value is <code nobreak="false">yes</code>.</p><note><p>Specifying <code nobreak="false">override-extension-function="yes"</code> ensures
                     interoperable behavior: the same code will execute with all processors.
                     Specifying <code nobreak="false">override-extension-function="no"</code> is useful when
                     writing a fallback implementation of a function that is available with some
                     processors but not others: it allows the vendor’s implementation of the
                     function (or a user’s implementation written as an extension function)
                     to be used in preference to the stylesheet implementation, which is useful when
                     the extension function is more efficient.</p><p>The <code nobreak="false">override-extension-function</code> attribute does <emph>not</emph>
                     affect the rules for deciding which of several 
                     <termref def="dt-stylesheet-function">stylesheet functions</termref> with the same
                     name and <termref def="dt-arity-range">arity range</termref> takes precedence.</p></note><p>The <code nobreak="false">override</code> attribute is a <termref def="dt-deprecated"/> synonym of <code nobreak="false">override-extension-function</code>,
                  retained for compatibility with XSLT 2.0. If both attributes are present then they
                     <rfc2119>must</rfc2119> have the same value.</p><p>When the <elcode>xsl:function</elcode> declaration appears as a
                  child of <elcode>xsl:override</elcode>, there <rfc2119>must</rfc2119> be a
                  <termref def="dt-compatible"/> stylesheet function in the 
                  <termref def="dt-package">package</termref> referenced by the containing
                     <elcode>xsl:use-package</elcode> element; the <termref def="dt-visibility">visibility</termref> 
                  of that function must be <code nobreak="false">public</code> or
                  <code nobreak="false">abstract</code> (See also <specref ref="package-overriding-components"/>.)</p></div4></div3><div3 id="function-lookup"><head>Dynamic Access to Functions</head><p>If a <termref def="dt-stylesheet-function">stylesheet
                     function</termref> with a particular <termref def="dt-expanded-qname">expanded
                     QName</termref> and <termref def="dt-arity-range">arity range</termref> exists in the
                  stylesheet, then a call to the <xfunction>function-lookup</xfunction> function
                  <phrase diff="chg" at="2022-11-27">will return the function as a value if it supplies that name and an arity within that range</phrase>. This applies
                  only if the static context for the call on <xfunction>function-lookup</xfunction>
                  includes the stylesheet function, which implies that the function is visible in
                  the containing package.</p><p>The <function>function-available</function> function, when
                  called with a particular <termref def="dt-expanded-qname">expanded QName</termref>
                  and arity, returns <code nobreak="false">true</code> if and only if a call on
                     <xfunction>function-lookup</xfunction> with the same arguments, in the same
                  static context, would return a function item.</p><note><p>For legacy reasons there is also a single-argument version of
                        <function>function-available</function>, which returns <code nobreak="false">true</code> if there is a
                     function with the given name regardless of arity.</p></note><p>The standard rules for
                     <xfunction>function-lookup</xfunction> require that if the supplied name and
                  arity identify a context-dependent function such as <xfunction>name#0</xfunction>
                  or <xfunction>lang#1</xfunction> (call it <var>F</var>), then the returned
                  function value includes in its closure a copy of the static and dynamic context of
                  the call to <xfunction>function-lookup</xfunction>, and the context item for a
                  subsequent dynamic call of <var>F</var> is taken from this saved context. In the
                  case where the context item is a node in a streamed input document, saving the
                  node is not possible. In this case, therefore, the context is saved with an absent
                  focus, so the call on <var>F</var> will fail with a dynamic error saying that
                  there is no context item available.</p></div3><div3 id="function-determinism"><head>Determinism of Functions</head><p>Stylesheet functions have been designed to be largely deterministic: unless a
                  stylesheet function calls some <termref def="dt-extension-function">extension
                     function</termref> which is itself nondeterministic, the function will return
                  results that depend only on the supplied arguments. This property (coupled with
                  the fact that the effect of calling extension functions is entirely <termref def="dt-implementation-dependent"/>) enables a processor to implement various
                  optimizations, such as removing invariant function calls from the body of a loop,
                  or combining common subexpressions.</p><p>One exception to the intrinsic determinism of stylesheet functions arises because
                  constructed nodes have distinct identity. This means that when a function that
                  creates a new node is called, two calls on the function will return nodes that can
                  be distinguished: for example, with such a function, <code nobreak="false">f:make-node() is
                     f:make-node()</code> will return <code nobreak="false">false</code>.</p><p>Three classes of functions can be identified:</p><olist><item><p><xtermref spec="FO40" ref="dt-deterministic">Deterministic</xtermref>
                        functions: as the term is defined in <bibref ref="xpath-functions-40"/>,
                        these offer a guarantee that when a function is called repeatedly with the
                        same arguments, it returns the same results. A classic example is the
                           <xfunction>doc</xfunction> function, which offers the guarantee that
                           <code nobreak="false">doc($X) is doc($X)</code>: that is, two calls supplying the same
                        URI return the same node.</p></item><item><p>Proactive functions: these offer the guarantee that each invocation of the
                        function causes a single execution of the function body, or behaves exactly
                        as if it did so. In particular this means that when the function creates new
                        nodes, it creates new nodes on each invocation. By default, <termref def="dt-stylesheet-function">stylesheet functions</termref> are
                        proactive.</p></item><item><p>Elidable functions: these offer no guarantee of determinism, and no
                        guarantee of proactive evaluation. If the function creates new nodes, then
                        two calls on the function with the same arguments may or may not return the
                        same nodes, at the implementation’s discretion. Examples of elidable functions include
                        the <bibref ref="xpath-functions-40"/> functions
                           <xfunction>analyze-string</xfunction> and
                           <function>json-to-xml</function>.</p></item></olist><p>The <code nobreak="false">new-each-time</code> attribute of <elcode>xsl:function</elcode> allows a
                  stylesheet function to be assigned to one of these three categories. The value
                     <code nobreak="false">new-each-time="no"</code> means the function is deterministic; the value
                     <code nobreak="false">new-each-time="yes"</code> means it is proactive; and the value
                     <code nobreak="false">new-each-time="maybe"</code> means it is elidable.</p><p>The definition of <xtermref spec="FO40" ref="dt-deterministic">determinism</xtermref> 
                  requires a definition of what it means for a function
                  to be called twice with “the same” arguments and to return “the same” result. This
                  is defined in <bibref ref="xpath-functions-40"/>, specifically by the definition
                  of the term <xtermref spec="FO40" ref="dt-identical">identical</xtermref>.</p><p>Processors have considerable freedom to optimize execution of stylesheets, and of
                  function calls in particular, but the strategies that are adopted must respect the
                  specification as to whether functions are deterministic, proactive, or elidable.
                  For example, consider a function call that appears within an
                     <elcode>xsl:for-each</elcode> instruction, where the supplied arguments to the
                  function do not depend on the context item or on any variables declared within the
                     <elcode>xsl:for-each</elcode> instruction. A possible optimization is to
                  execute the function call only once, rather than executing it repeatedly each time
                  round the loop (this is sometimes called loop-lifting). This optimization is safe
                  when the function is deterministic or elidable, but it requires great care if the
                  function is proactive; it is permitted only if the processor is able to determine
                  that the results of stylesheet execution are equivalent to the results that would
                  be obtained if the optimization had not been performed. Declaring a function call
                  to be elidable (by writing <code nobreak="false">new-each-time="maybe"</code>) makes it more
                  likely that an implementation will be able to apply this optimization, as well as
                  other optimizations such as caching or memoization.</p></div3><div3 id="memoization"><head>Memoization</head><p>The <code nobreak="false">cache</code> attribute is an optimization hint which the processor can
                  use or ignore at its discretion; however it <rfc2119>should</rfc2119> be taken
                  seriously, because it may make a difference to whether execution of a stylesheet
                  is practically feasible or not.</p><p>The default value is <code nobreak="false">cache="no".</code></p><p>The value <code nobreak="false">cache="yes"</code> encourages the processor to retain memory of
                     previous calls of this function
                  during the same transformation and to reuse results from this memory whenever
                  possible. The default value <code nobreak="false">cache="no"</code> encourages the
                  processor not to retain memory of previous calls.</p><p>In all cases the results must respect the semantics. If a function is proactive
                     (<code nobreak="false">new-each-time="yes"</code>) then caching of results may be infeasible,
                  especially if the function result can include nodes; but it is not an error to
                  request it, since some implementations may be able to provide caching, or
                  analogous optimizations, even for proactive functions. (One possible strategy is
                  to return a copy of the cached result, thus creating the illusion that the
                  function has been evaluated anew.)</p><note><p>Memoization is essentially a trade-off between time and space; a memoized
                     function can be expected to use more memory to deliver faster execution.
                     Achieving an optimum balance may require configuring the size of the cache that
                     is used; implementations <rfc2119>may</rfc2119> use additional <termref def="dt-extension-attribute">extension attributes</termref> or other
                     mechanisms to provide finer control of this kind.</p></note><note><p>Memoization of a function generally involves creating an associative table (for
                     example, a hash map) that maps argument values to function results. To get this
                     right, it is vital that the key for this table should correctly reflect what it
                     means for two function calls to have “the same arguments”. Does it matter, for
                     example, that one call passes the <code nobreak="false">xs:string</code> value <code nobreak="false">"Paris"</code>, while
                     another passes the <code nobreak="false">xs:untypedAtomic</code> item <code nobreak="false">"Paris"</code>? If the function
                     is declared with <code nobreak="false">new-each-time="maybe"</code>, then the rules say that
                     these cannot be treated as “the same arguments”: the definition of 
                     <xtermref spec="FO40" ref="dt-identical"/> requires them to have the same type
                     as well as being equal. However, an implementation that is able to determine
                     that all references to the argument within the function body only make use of
                     its string value might be able to take advantage of this fact, and thus perform
                     more efficient caching.</p></note></div3><div3 id="function-examples"><head>Examples of Stylesheet Functions</head><example diff="chg" at="2022-01-01"><head>A Stylesheet Function</head><p>The following example creates a recursive <termref def="dt-stylesheet-function">stylesheet function</termref> named <code nobreak="false">str:reverse</code> that reverses
                     the words in a supplied sentence, and then invokes this function from within a
                        <termref def="dt-template-rule">template rule</termref>. </p><eg xml:space="preserve" role="xslt-document">&lt;xsl:transform 
  xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
  xmlns:str="http://example.com/namespace"
  version="3.0"
  expand-text="yes"
  exclude-result-prefixes="str"&gt; 

&lt;xsl:function name="str:reverse" as="string"&gt;
  &lt;xsl:param name="sentence" as="string"/&gt;
  &lt;xsl:if test="contains($sentence, ' ')"
             then="str:reverse(substring-after($sentence, ' ')) ||
                         ' ' || substring-before($sentence, ' ')"
             else="$sentence"/&gt;
&lt;/xsl:function&gt;

&lt;xsl:template match="/"&gt;
  &lt;output&gt;{str:reverse('DOG BITES MAN')}&lt;/output&gt;
&lt;/xsl:template&gt;

&lt;/xsl:transform&gt;</eg></example><example><head>Declaring the Return Type of a Function</head><p>The following example illustrates the use of the <code nobreak="false">as</code> attribute in a
                     function definition. It returns a string containing the representation of its
                     integer argument, expressed as a roman numeral. For example, the function call
                        <code nobreak="false">num:roman(7)</code> will return the string <code nobreak="false">"vii"</code>. This
                     example uses the <elcode>xsl:number</elcode> instruction, described in 
                     <specref ref="number"/>. The <elcode>xsl:number</elcode> instruction returns a text
                     node, and the <termref def="dt-coercion-rules"/> are invoked to convert this text node to the type declared
                     in the <elcode>xsl:function</elcode> element, namely <code nobreak="false">xs:string</code>. So
                     the text node is <termref def="dt-atomization">atomized</termref> to a
                     string.</p><eg xml:space="preserve" role="xslt-declaration xmlns:num='num'">&lt;xsl:function name="num:roman" as="xs:string"&gt;
  &lt;xsl:param name="value" as="xs:integer"/&gt;
  &lt;xsl:number value="$value" format="i"/&gt;
&lt;/xsl:function&gt;</eg></example><example><head>A Higher-Order Function</head><p>XPath 3.0 introduces the ability to pass function items as arguments to a
                     function. A function that takes function items as arguments is known as a
                     higher-order function.</p><p>The following example is a higher-order function that operates on any
                     tree-structured data, for example an organization chart. Given as input a
                     function that finds the direct subordinates of a node in this tree structure
                     (for example, the direct reports of a manager, or the geographical subdivisions
                     of an administrative area), it determines whether one object is present in the
                     subtree rooted at another object (for example, whether one person is among the
                     staff managed directly or indirectly by a manager, or whether one parcel of
                     land is contained directly or indirectly within another parcel). The function
                     does not check for cycles in the data.</p><eg role="xslt-declaration xmlns:f='f'" xml:space="preserve">&lt;xsl:function name="f:is-subordinate" as="xs:boolean"&gt;
    &lt;xsl:param name="superior" 
               as="node()"/&gt;
    &lt;xsl:param name="subordinate" 
               as="node()"/&gt;
    &lt;xsl:param name="get-direct-children" 
               as="fn(node()) as node()*"/&gt;
    &lt;xsl:select&gt;
               some $sub in $get-direct-children($superior) satisfies
                 ($sub is $subordinate or
                  f:is-subordinate($sub, $subordinate, 
                                      $get-direct-children))
    &lt;/xsl:select&gt;                                   
&lt;/xsl:function&gt;</eg><p>(This example is written to use the <elcode>xsl:select</elcode> instruction,
                  newly introduced in XSLT 4.0, to compute the function result.)</p><p>Given source data representing an organization chart in the form of elements
                     such as:</p><eg role="xml" xml:space="preserve">&lt;employee id="P57832" manager="P68951"/&gt;</eg><p>the following function can be defined to get the direct reports of a
                     manager:</p><eg role="xslt-declaration xmlns:f='f'" xml:space="preserve">&lt;xsl:function name="f:direct-reports" 
               as="element(employee)*"&gt;
    &lt;xsl:param name="manager" as="element(employee)"/&gt;
    &lt;xsl:sequence select="$manager/../employee
                               [@manager = $manager/@id]"/&gt;
&lt;/xsl:function&gt;</eg><p>It is then possible to test whether one employee <code nobreak="false">$E</code> reports
                     directly or indirectly to another employee <code nobreak="false">$M</code> by means of the
                     function call:</p><eg role="non-xml" xml:space="preserve">f:is-subordinate($M, $E, f:direct-reports#1)</eg></example></div3></div2><div2 id="static-xpath-evaluation"><head>Static XPath Evaluation</head><p>The two instructions described in this section, <code nobreak="false">xsl:sequence</code>
            and <code nobreak="false">xsl:select</code>, can be used to evaluate XPath expressions that
            are statically known: that is, the XPath expressions are statically processed
            during the static processing of the stylesheet, and are dynamically evaluated
            during the dynamic evaluation of the stylesheet. The <elcode>xsl:sequence</elcode>
            instruction can also be used to evaluate a <termref def="dt-sequence-constructor"/>.</p><div3 id="constructing-sequences"><head>The <code nobreak="false">xsl:sequence</code> Instruction</head><changes><change issue="46" PR="1306" date="2024-06-27">
                  An <code nobreak="false">as</code> attribute is available on the <elcode>xsl:sequence</elcode> instruction.
               </change></changes><e:element-syntax xmlns:e="http://www.w3.org/1999/XSL/Spec/ElementSyntax" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" name="sequence">
      <e:in-category name="instruction"/>
      <e:attribute name="select" required="no">
         <e:data-type name="expression"/>
      </e:attribute>
      <e:attribute name="as" required="no" default="'item()*'">
         <e:data-type name="sequence-type"/>
      </e:attribute>
      <e:model name="sequence-constructor"/>
      <e:allowed-parents>
         <e:parent-category name="sequence-constructor"/>
      </e:allowed-parents>
   </e:element-syntax><p>The <elcode>xsl:sequence</elcode> instruction may be used within a <termref def="dt-sequence-constructor">sequence constructor</termref> to construct a
               sequence of nodes, atomic items, and/or function
                  items. This sequence is returned as the result of the instruction. Unlike
               most other instructions, <elcode>xsl:sequence</elcode> can return a sequence
               containing existing nodes, rather than constructing new nodes. When
                  <elcode>xsl:sequence</elcode> is used to select atomic items or function items, the effect is very similar to the
                  <elcode>xsl:copy-of</elcode> instruction.</p><p>The <code nobreak="false">select</code> attribute and the contained <termref def="dt-sequence-constructor"/>
               are mutually exclusive; if the instruction
               has a <code nobreak="false">select</code> attribute, then it <rfc2119>must</rfc2119> have no children
               other than <elcode>xsl:fallback</elcode> instructions. If there is no
               <code nobreak="false">select</code> attribute and no contained <termref def="dt-sequence-constructor"/>, 
               the result is the empty sequence. 
            </p><p>The effect of the instruction is as follows:</p><olist><item><p>Evaluate the expression in the <code nobreak="false">select</code> attribute if present, 
                  or the contained <termref def="dt-sequence-constructor"/> otherwise. Call the result <var>T</var>.</p></item><item><p>Use the <termref def="dt-coercion-rules"/> to convert <var>T</var> to the sequence
               type appearing in the <code nobreak="false">as</code> attribute, defaulting to <code nobreak="false">item()*</code>.
               The converted result is the value returned by the <elcode>xsl:sequence</elcode>
               instruction.</p></item></olist><p>
               <error spec="XT" type="static" class="SE" code="3185" diff="chg" at="2023-05-10"><p>For the elements <elcode>xsl:sequence</elcode>, <elcode>xsl:on-empty</elcode>,
                     <elcode>xsl:on-non-empty</elcode>, <elcode>xsl:when</elcode>,
                     <elcode>xsl:otherwise</elcode>, <elcode>xsl:matching-substring</elcode>,
                     <elcode>xsl:non-matching-substring</elcode>, <elcode>xsl:map</elcode>,
                     <elcode>xsl:map-entry</elcode>, <elcode>xsl:array</elcode>, <elcode>xsl:array-member</elcode>,
                     and <elcode>xsl:result-document</elcode>,
                     it is a <termref def="dt-static-error">static error</termref> if the
                        <code nobreak="false">select</code> attribute is present
                     and the instruction has children other than <elcode>xsl:fallback</elcode>.</p></error>
            </p><note><p>The <elcode>xsl:sequence</elcode> instruction was first introduced in XSLT 2.0, so the <code nobreak="false">xsl:fallback</code>
               instruction is relevant only to an XSLT 1.0 processor operating in forwards compatibility mode.</p><p>An XSLT 2.0 or 3.0 processor operating in forwards compatibility mode will ignore the <code nobreak="false">@as</code>
               attribute.</p></note><note><p>The <elcode>xsl:sequence</elcode> instruction is most commonly used as the final instruction
            in the body of <elcode>xsl:function</elcode>, to compute the result of the function. If the result
            is a single item, consider writing <code nobreak="false">&lt;xsl:sequence select="..." as="item()"/&gt;</code> to
            make this clear to the reader.</p></note><note><p>The main use case for allowing <elcode>xsl:sequence</elcode> to contain a sequence
                  constructor is to allow the instructions within an <elcode>xsl:fork</elcode>
                  element to be divided into groups.</p><p>It can also be used to limit the scope of local variables or of standard
                  attributes such as <code nobreak="false">[xsl:]default-collation</code>.</p></note><example><head>Constructing a Sequence of Integers</head><p>The following code:</p><eg xml:space="preserve" role="xslt-instruction">&lt;xsl:variable name="values" as="xs:integer*"&gt;
    &lt;xsl:sequence select="(1,2,3,4)"/&gt;
    &lt;xsl:sequence select="(8,9,10)"/&gt;
&lt;/xsl:variable&gt;
&lt;xsl:value-of select="sum($values)"/&gt;</eg><p>produces the output: <code nobreak="false">37</code>
               </p></example><example><head>Using <code nobreak="false">xsl:for-each</code> to Construct a Sequence</head><p>The following code constructs a sequence containing the value of the
                     <code nobreak="false">@price</code> attribute for selected elements, 
                  or a computed price for those elements that
                  have no <code nobreak="false">@price</code> attribute:</p><eg xml:space="preserve" role="xslt-instruction">&lt;xsl:variable name="prices" as="xs:decimal*"&gt;
   &lt;xsl:for-each select="//product"&gt;
      &lt;xsl:sequence select="@price otherwise @cost * 1.5" as="xs:decimal"/&gt;
   &lt;/xsl:for-each&gt;
&lt;/xsl:variable&gt;</eg><p>Note that the existing <code nobreak="false">@price</code> attributes could equally have been
                  added to the <code nobreak="false">$prices</code> sequence using <elcode>xsl:copy-of</elcode> or
                     <elcode>xsl:value-of</elcode>. However, <elcode>xsl:copy-of</elcode> would
                  create a copy of the attribute node, which is not needed in this situation, while
                     <elcode>xsl:value-of</elcode> would create a new text node, which then has to
                  be converted to an <code nobreak="false">xs:decimal</code>. Using <elcode>xsl:sequence</elcode>,
                  which in this case atomizes the existing attribute node and adds an
                     <code nobreak="false">xs:decimal</code> atomic item to the result sequence, is a more direct
                  way of achieving the same result.</p><p>This example could alternatively be solved at the XPath level:</p><eg xml:space="preserve" role="xslt-instruction">&lt;xsl:sequence select="//product/(+@price otherwise @cost*1.5))"/&gt;</eg><p>or, in XSLT 4.0:</p><eg role="xslt-instruction" xml:space="preserve">&lt;xsl:select&gt;//product/(+@price otherwise @cost*1.5))&lt;/xsl:select&gt;</eg><p>The apparently redundant <code nobreak="false">+</code> operator is there to atomize the attribute
                  value: the expression on the right hand side of the <code nobreak="false">/</code> operator must
                  not return a  sequence containing both nodes and
                     non-nodes (atomic items or function items).</p></example></div3><div3 id="select-instruction"><head>The <code nobreak="false">xsl:select</code> Instruction</head><changes><change issue="2004" PR="2008" date="2025-05-20">
                  The <elcode>xsl:select</elcode> instruction is new in 4.0.
               </change></changes><e:element-syntax xmlns:e="http://www.w3.org/1999/XSL/Spec/ElementSyntax" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" name="select">
      <e:in-category name="instruction"/>
      <e:attribute name="as" required="no" default="'item()*'">
         <e:data-type name="sequence-type"/>
      </e:attribute>
      <e:sequence>
         <e:element name="fallback" repeat="zero-or-more"/>
         <e:text/>
      </e:sequence>
      <e:allowed-parents>
         <e:parent-category name="sequence-constructor"/>
      </e:allowed-parents>
   </e:element-syntax><p>The <elcode>xsl:select</elcode> instruction evaluates an XPath expression contained as a child node
            of the instruction. For example, the instruction:</p><eg xml:space="preserve">&lt;xsl:select as="map(*)"&gt;
   {  "title"  : $title,
      "author" : $author
   }
&lt;/xsl:select&gt;</eg><p>evaluates the contained XPath expression, in the current static and dynamic context,
            and returns (in this example) a map with two entries.</p><p>While the <elcode>xsl:sequence</elcode> instruction (with a <code nobreak="false">select</code> 
               attribute) can also be used to evaluate
            an arbitrary XPath expression and return its result, the <elcode>xsl:select</elcode>
            instruction offers some potential advantages:</p><ulist><item><p>An XPath expression written within an XML attribute is subjected by the
               XML parser to attribute value normalization, which changes the arrangement
               of whitespace within the value. While this will rarely affect the actual meaning
               of the expression, it can mean that formatting is lost. Multi-line attribute
               values are therefore best avoided. The loss of formatting also makes it difficult
               for an XSLT processor to provide precise error locations.</p></item><item><p>When an XPath expression appears in an attribute value, then one of the
               characters <char>U+0022</char> or <char>U+0027</char> becomes unavailable for use
               with the expression, unless written as <code nobreak="false">&amp;quot;</code> or <code nobreak="false">&amp;apos;</code>
               respectively. When an expression is written within a text node, this problem does not
               arise, and both characters can be used without escaping.</p></item><item><p>The content of the <elcode>xsl:select</elcode> instruction can be written
               as a CDATA section, allowing operators such as <code nobreak="false">&lt;</code> and <code nobreak="false">&lt;=</code>
               to be written without escaping.</p></item><item><p>The instruction name <elcode>xsl:sequence</elcode> can easily
               confuse people reading the code in cases where the intent is to return a single
               item.</p></item></ulist><p>With the increasing richness of the XPath language, expressions of ten or twenty lines
            become increasingly common, and this instruction makes such expressions more manageable.
            This often arises when constructing maps and arrays designed to be serialized as JSON.
            For example, a function might be defined that takes an element node as input and constructs
            a map containing selected information:</p><eg xml:space="preserve">&lt;xsl:function name="f:book-to-json" as="map(*)"&gt;
   &lt;xsl:param name="book" as="element(book)"/            
   &lt;xsl:select&gt;
      {  "title"  : string($book/title),
         "isbn"   : string($book/isbn),
         "price"  : number($book/@price),
         "author" : array { $book/author ! string() },
         "date"   : current-date()"
      }
   &lt;/xsl:select&gt;
&lt;/xsl:function&gt;</eg><p>Any <elcode>xsl:fallback</elcode> child instructions will be ignored by an 
            XSLT 4.0 processor, but will be evaluated by an XSLT 3.0 or earlier processor running
            in forwards compatible mode. An <elcode>xsl:fallback</elcode> instruction may be preceded
            by a text node consisting entirely of whitespace, but must not be preceded by a text node
            containing non-whitespace characters. The XPath expression to be evaluated is therefore
            contained in the last text node child. (XML comments, processing instructions, and 
            <elcode>xsl:note</elcode> elements will already have been removed.)</p><p>The effect of the <elcode>xsl:select</elcode> instruction is as follows:</p><olist><item><p>Let <var>E</var> be the string value of the last text node child of the
               instruction, if any.</p></item><item><p>If <var>E</var> is absent, zero-length, or consists entirely of whitespace,
               then let <var>V</var> be the empty sequence.</p></item><item><p>Otherwise, let <var>V</var> be the result of evaluating <var>E</var> as an XPath
                  expression in the current static and dynamic context.</p></item><item><p>The result of the <elcode>xsl:select</elcode>
               instruction is the result of using the <termref def="dt-coercion-rules"/> to convert <var>V</var>
                  to the type appearing in the <code nobreak="false">as</code> attribute, 
                  defaulting to <code nobreak="false">item()*</code>.</p></item></olist><note><p>The text node cannot contain text value templates.</p></note><note><p>The <elcode>xsl:select</elcode> instruction requires the XPath expression to
            be known statically (though it can refer to variables whose value is dynamic). The 
            <elcode>xsl:evaluate</elcode> instruction, by contrast, can be used to evaluate
            XPath expressions that are constructed dynamically or read from an external document.
            The <elcode>xsl:evaluate</elcode> instruction is described in the next section.</p></note><note><p>Many instructions take their input either from an XPath expression
            contained in a <code nobreak="false">select</code> attribute, or from a sequence constructor
            forming the content of the instruction, the two options being mutually exclusive. 
            Instructions that follow this pattern
            include <elcode>xsl:break</elcode>, <elcode>xsl:on-completion</elcode>, <elcode>xsl:catch</elcode>,
            <elcode>xsl:on-empty</elcode>, <elcode>xsl:when</elcode>, <elcode>xsl:attribute</elcode>,
            and many others. In most of these cases, writing an XPath expression within
            a child <elcode>xsl:select</elcode> element is equivalent to writing the same expression
            with a <code nobreak="false">select</code> attribute. However, there are a few subtle differences,
            for example in the case of <elcode>xsl:attribute</elcode>, <elcode>xsl:text</elcode>, and <elcode>xsl:value-of</elcode>,
            the default separator is different (a single space when a <code nobreak="false">select</code> attribute is used, a zero-length
            string for a sequence constructor comprising an <elcode>xsl:select</elcode> instruction).</p></note></div3></div2><div2 id="dynamic-xpath"><head>Dynamic XPath Evaluation</head><changes><change issue="2047" PR="2213" date="2025-10-23">
                  A new attribute <code nobreak="false">trusted=yes|no</code> is added to <elcode>xsl:evaluate</elcode>
                  to indicate whether the XPath expression to be evaluated is trusted to access
                  external resources. The default value is <code nobreak="false">no</code>, which may cause backwards
                  incompatibility. Dynamic evaluation using <elcode>xsl:evaluate</elcode> is no longer
                  an optional feature of the XSLT language.
               </change></changes><e:element-syntax xmlns:e="http://www.w3.org/1999/XSL/Spec/ElementSyntax" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" name="evaluate">
      <e:in-category name="instruction"/>
      <e:attribute name="xpath" required="yes">
         <e:data-type name="expression"/>
      </e:attribute>
      <e:attribute name="as" required="no" default="'item()*'">
         <e:data-type name="sequence-type"/>
      </e:attribute>
      <e:attribute name="base-uri" required="no">
         <e:attribute-value-template>
            <e:data-type name="uri"/>
         </e:attribute-value-template>
      </e:attribute>
      <e:attribute name="with-params" required="no">
         <e:data-type name="expression"/>
      </e:attribute>
      <e:attribute name="context-item" required="no">
         <e:data-type name="expression"/>
      </e:attribute>
      <e:attribute name="namespace-context" required="no">
         <e:data-type name="expression"/>
      </e:attribute>
      <e:attribute name="schema-aware" required="no" default="'no'">
         <e:attribute-value-template>
            <e:data-type name="boolean"/>
         </e:attribute-value-template>
      </e:attribute>
      <e:attribute name="trusted" required="no" default="'no'">
         <e:attribute-value-template>
            <e:data-type name="boolean"/>
         </e:attribute-value-template>
      </e:attribute>
      <e:choice repeat="zero-or-more">
         <e:element name="with-param"/>
         <e:element name="fallback"/>
      </e:choice>
      <e:allowed-parents>
         <e:parent-category name="sequence-constructor"/>
      </e:allowed-parents>
   </e:element-syntax><p>The <elcode>xsl:evaluate</elcode> instruction constructs an XPath expression in the
               form of a string, evaluates the expression in a specified context, and returns the
               result of the evaluation.</p><p>The expression given as the value of the <code nobreak="false">xpath</code> attribute is evaluated
               and the result is converted to a string using the <termref def="dt-coercion-rules"/>.</p><p><termdef id="dt-target-expression" term="target expression">The string that results
                  from evaluating the expression in the <code nobreak="false">xpath</code> attribute is referred to
                  as the <term>target expression</term>.</termdef></p><p><error spec="XT" type="dynamic" class="DE" code="3160"><p>It is a <termref def="dt-dynamic-error"> dynamic error</termref> if the <termref def="dt-target-expression">target expression</termref>
                     <error.extra>of an <elcode>xsl:evaluate</elcode> instruction</error.extra> is
                     not a valid <termref def="dt-expression"/> (that is, if a static error occurs when analyzing the string
                     according to the rules of the XPath specification).</p></error></p><p>The <code nobreak="false">as</code> attribute, if present, indicates the required type of the result.
               If the attribute is absent, the required type is <code nobreak="false">item()*</code>, which allows
               any result. The result of evaluating the <termref def="dt-target-expression">target
                  expression</termref> is converted to the required type using the <termref def="dt-coercion-rules"/>. This may
               cause a <termref def="dt-type-error">type error</termref> if conversion is not
               possible. The result after conversion is returned as the result of the
                  <elcode>xsl:evaluate</elcode> instruction.</p><p>The target expression may contain variable references; the values
               of such variables may be supplied using an <elcode>xsl:with-param</elcode> child
               instruction if the names of the variables are known statically, or using a map
               supplied as the value of the expression in the <code nobreak="false">with-params</code> attribute if
               the names are only known dynamically. If the <code nobreak="false">with-params</code> attribute is
               present then it must contain an expression whose value, when evaluated, is of type
                  <code nobreak="false">map(xs:QName, item()*)</code> (see <specref ref="map"/> for details of
               maps).</p><p>
               <error spec="XT" type="type" class="TE" code="3165"><p>It is a <termref def="dt-type-error">type error</termref> if the
                     result of evaluating the expression in the <code nobreak="false">with-params</code>
                     attribute of the <elcode>xsl:evaluate</elcode> instruction is
                     anything other than a single map of type
                     <code nobreak="false">map(xs:QName, item()*)</code>.</p></error>
            </p><div3 id="evaluate-static-context"><head>Static context for the target expression</head><p>The <xtermref spec="XP40" ref="dt-static-context">static context</xtermref> for
                  the <termref def="dt-target-expression">target expression</termref> is as
                  follows:</p><ulist><item><p>XPath 1.0 compatibility mode is <code nobreak="false">false</code>.</p></item><item><p>Trust level: the <xspecref spec="XP40" term="dt-trusted">trust level</xspecref>
                     of the target expression is determined by the <termref def="dt-effective-value"/>
                     of the <code nobreak="false">trusted</code> attribute. If the value is <code nobreak="false">yes</code>,
                     the target expression has the same level of trust, and may therefore access
                     the same external resources, as the calling stylesheet. If the value is 
                        <code nobreak="false">no</code>, the target expression has no access to external resources,
                     other than any resources made explicitly available via some secure
                     <termref def="dt-implementation-defined"/> mechanism.</p></item><item diff="chg" at="2022-01-01"><p>Statically known namespaces and default namespaces for 
                        elements and for types:</p><ulist><item><p>if the <code nobreak="false">namespace-context</code> attribute is present, then its
                              value is an <termref def="dt-expression">expression</termref> whose
                              required type is a single node. The expression is evaluated, and the
                              in-scope namespaces of the resulting node are used as the statically
                              known namespaces for the target expression. The binding for the
                              default namespace in the in-scope namespaces is used as the default
                              namespace for <phrase diff="add" at="2022-01-01">both</phrase>
                              elements and types in the target expression.</p><p>
                              <error spec="XT" type="type" class="TE" code="3170"><p>It is a <termref def="dt-type-error">type error</termref> if the
                                    result of evaluating the <code nobreak="false">namespace-context</code>
                                    attribute of the <elcode>xsl:evaluate</elcode> instruction is
                                    anything other than a single node.</p></error>
                           </p></item><item><p>if the <code nobreak="false">namespace-context</code> attribute is absent, then the
                              <phrase diff="chg" at="2023-05-04"><termref def="dt-applicable-static-namespaces"/></phrase> of the <elcode>xsl:evaluate</elcode> instruction
                              (with the exception of any binding for the default namespace) are used
                              as the statically known namespaces for the target expression, and the
                              value of the attribute <code nobreak="false">[xsl:]xpath-default-namespace</code>,
                              if present, is used to establish the default namespace for elements and
                              types in the target expression, as described in <specref ref="unprefixed-qnames"/>.</p></item></ulist><note><p>XPath 3.0 allows expanded names to be written in a context-independent
                           way using the syntax <code nobreak="false">Q{namespace-uri}local-name</code></p></note></item><item><p>Default function namespace: the <termref def="dt-standard-function-namespace">standard function
                           namespace</termref>.</p></item><item><p>In-scope schema definitions: if the <code nobreak="false">schema-aware</code> attribute is
                        present and has the <termref def="dt-effective-value">effective
                           value</termref>
                        <code nobreak="false">yes</code>, then the in-scope schema definitions from the stylesheet
                        context of the <elcode>xsl:evaluate</elcode> instruction (that is, 
                        the schema definitions imported using
                           <elcode>xsl:import-schema</elcode>, taking into account any <code nobreak="false">[xsl:]schema-role</code>
                        on the <elcode>xsl:evaluate</elcode> instruction or on any of its ancestors). 
                        Otherwise, the built-in types (see
                           <specref ref="built-in-types"/>).</p><note><p>If the containing stylesheet does not import a schema, then the in-scope schema definitions
                        for the target expression will contain only the built-in schema types, regardless of the value
                        of the <code nobreak="false">schema-aware</code> attribute.</p></note></item><item><p>In-scope variables: the names of the in-scope variables
                        are the union of the names appearing in the <code nobreak="false">name</code> attribute of
                        the contained <elcode>xsl:with-param</elcode> elements, and the names
                        present as keys in the map obtained by evaluating the
                           <code nobreak="false">with-params</code> attribute, if present. The corresponding type is
                           <code nobreak="false">item()*</code> in the case of a name found as a key in the
                           <code nobreak="false">with-params</code> map, or the type named in the <code nobreak="false">as</code>
                        attribute of <elcode>xsl:with-param</elcode> child (defaulting to
                           <code nobreak="false">item()*</code>) otherwise.</p><p>If a variable name is present both the static
                           <elcode>xsl:with-param</elcode> children and also in the dynamic
                           <code nobreak="false">with-params</code> map, the value from the latter takes
                        precedence.</p><note><p>Variables declared in the stylesheet in <elcode>xsl:variable</elcode> or
                              <elcode>xsl:param</elcode> elements are <emph>not</emph> in-scope
                           within the target expression.</p></note></item><item><p>Function signatures:</p><ulist><item><p>All functions defined in <bibref ref="xpath-functions-40"/> in the
                           <code nobreak="false">fn</code>, <code nobreak="false">math</code>, <code nobreak="false">map</code>, and <code nobreak="false">array</code> namespaces;</p></item><item><p>Constructor functions for named simple types included in the in-scope schema definitions;</p></item><item><p>All user-defined functions present in the containing package provided their visibility is
                           not <code nobreak="false">hidden</code> or <code nobreak="false">private</code>;</p></item><item><p>An <termref def="dt-implementation-defined">implementation-defined</termref> set of
                           <termref def="dt-extension-function">extension functions</termref>.</p></item></ulist><p>Note that this set deliberately excludes XSLT-defined functions in the
                           <termref def="dt-standard-function-namespace">standard function
                           namespace</termref> including for example, <function>key</function>,
                           <function>current-group</function>, and
                           <function>system-property</function>. A list of these functions is in
                           <specref ref="XSLT-defined-functions"/>.</p><imp-def-feature id="idf-ext-evaluatefunctions">The set of extension functions
                        available in the static context for the target expression of
                           <elcode>xsl:evaluate</elcode> is <termref def="dt-implementation-defined"/>.</imp-def-feature></item><item><p>Statically known collations: the same as the collations available at this
                        point in the stylesheet.</p></item><item><p>Default collation: the same as the default collation defined at this point
                        in the stylesheet (for example, by use of the
                           <code nobreak="false">[xsl:]default-collation</code> attribute)</p></item><item><p>Base URI: if the <code nobreak="false">base-uri</code> attribute is present, then its
                           <termref def="dt-effective-value">effective value</termref>; otherwise,
                        the base URI of the <elcode>xsl:evaluate</elcode> instruction.</p></item></ulist></div3><div3 id="evaluate-dynamic-context"><head>Dynamic context for the target expression</head><p>The dynamic context for evaluation of the target expression is
                  as follows:</p><ulist><item diff="chg" at="2023-10-30"><p>The <xtermref spec="XP40" ref="dt-context-value"/> depends on the result of evaluating the
                        expression in the <code nobreak="false">context-item</code> attribute. If this attribute is
                        absent then the context value,
                        position, and size for evaluation of the target expression are all <termref def="dt-absent"/>. 
                        If the attribute is present then the result of evaluating the expression
                        is used as the <xtermref spec="XP40" ref="dt-context-value"/>, and the <termref def="dt-context-position"/>
                        and <termref def="dt-context-size"/> are both set to 1 (one).</p><p diff="del" at="2023-10-30"><error spec="XT" type="type" class="TE" code="3210"><p>If the result of evaluating the <code nobreak="false">context-item</code> expression
                                 <error.extra>of an <elcode>xsl:evaluate</elcode>
                                 instruction</error.extra> is a sequence containing more than one
                              item, then a <termref def="dt-type-error"/> is raised.</p></error></p><note><p>The attribute name <code nobreak="false">context-item</code> is a misnomer; it reflects the fact
                     that in XSLT 3.0, the supplied expression was required to return a single item, rather than
                     an arbitrary sequence.</p></note></item><item><p>The <term>variable values</term> consists of the values
                        bound to parameters defined either in the contained
                           <elcode>xsl:with-param</elcode> elements, which are evaluated as
                        described in <specref ref="variable-values"/>, or in the map that results
                        from evaluation of the expression in the <code nobreak="false">with-params</code> attribute;
                        if the same QName is bound in both, the value in the
                           <code nobreak="false">with-params</code> map takes precedence.</p></item><item><p>The XSLT-specific aspects of the dynamic context described in <specref ref="additional-dynamic-context"/> are all <termref def="dt-absent"/>.</p></item><item><p diff="chg" at="2022-11-25">The <xtermref spec="XP40" ref="dt-dynamically-known-function-definitions">dynamically known function definitions</xtermref>
                        (representing the functions accessible using <function>function-available</function> or <xfunction>function-lookup</xfunction>)
                        include all the functions available in the static context, and may also include an additional 
                        <termref def="dt-implementation-defined"/> set of functions that are available dynamically but not statically.
                     </p></item><item><p>All other aspects of the dynamic context are the same as the dynamic context
                        for the <elcode>xsl:evaluate</elcode> instruction itself, except that an implementation <code nobreak="false">may</code> restrict
                           the availability of external resources (for example, available documents)
                           or provide options to restrict their availability, for security
                           reasons.</p><note><p>For example, a processor may disallow access using the
                              <xfunction>doc</xfunction> or <xfunction>collection</xfunction> functions
                           to documents in local filestore.</p></note></item></ulist></div3><div3 id="evaluate-effect"><head>The effect of the <code nobreak="false">xsl:evaluate</code> instruction</head><p>The XPath expression is evaluated in the same <xtermref ref="execution-scope" spec="FO40">execution scope</xtermref> as the calling XSLT transformation; this
                  means that the results of <xtermref spec="FO40" ref="dt-deterministic">deterministic</xtermref> functions such as <xfunction>doc</xfunction> or
                     <xfunction>current-dateTime</xfunction> will be consistent between the calling
                  stylesheet and the called XPath expression.</p><p>It is a <termref def="dt-dynamic-error"/> if evaluation of the
                  XPath expression fails with a dynamic error. The XPath-defined error code is used
                  unchanged.</p><note><p>Implementations wanting to avoid the cost of repeated compilation of the same
                     XPath expression should cache the compiled form internally.</p></note><p>Stylesheet authors need to be aware of the security risks
                  associated with the use of <elcode>xsl:evaluate</elcode>. The instruction should
                  not be used to execute code from an untrusted source. To avoid the risk of code
                  injection, user-supplied data should never be inserted into the expression using
                  string concatenation, but should always be referenced by use of parameters.</p></div3><div3 id="evaluation-as-optional-feature"><head>Disabling <elcode>xsl:evaluate</elcode></head><p>A processor <rfc2119>may</rfc2119> allow users, via some
                  <termref def="dt-implementation-defined"/> mechanism, to disable
                  the use of the <elcode>xsl:evaluate</elcode> instruction.
                  It may either be <term>statically
                     disabled</term>, or <term>dynamically
                     disabled</term>.</p><p>If the feature is statically disabled, then:</p><ulist><item><p>A call to <code nobreak="false">element-available('xsl:evaluate')</code> returns <code nobreak="false">false</code>,
                        wherever it appears;</p></item><item><p>A call to <code nobreak="false">system-property('xsl:supports-dynamic-evaluation')</code>
                        returns the string <code nobreak="false">"no"</code>, wherever it appears;</p></item><item><p>If an <elcode>xsl:evaluate</elcode> instruction has an
                           <elcode>xsl:fallback</elcode> child, fallback processing takes place;</p></item><item><p>No static error is raised if an <elcode>xsl:evaluate</elcode> instruction is
                        present in the stylesheet (an error occurs only if it is actually
                        evaluated).</p></item></ulist><p>If the feature is dynamically disabled, then:</p><ulist><item><p>A call to <code nobreak="false">element-available('xsl:evaluate')</code> appearing in a
                           <termref def="dt-static-expression">static expression</termref> (for
                        example, in an <code nobreak="false">[xsl:]use-when</code> attribute) returns <code nobreak="false">true</code>;</p></item><item><p>A call to <code nobreak="false">element-available('xsl:evaluate')</code> appearing anywhere
                        else returns <code nobreak="false">false</code>;</p></item><item><p>A call to <code nobreak="false">system-property('xsl:supports-dynamic-evaluation')</code>
                        appearing in a <termref def="dt-static-expression">static
                           expression</termref> (for example, in an <code nobreak="false">[xsl:]use-when</code>
                        attribute) returns the string <code nobreak="false">"yes"</code>;</p></item><item><p>A call to <code nobreak="false">system-property('xsl:supports-dynamic-evaluation')</code>
                        appearing anywhere else returns the string <code nobreak="false">"no"</code>;</p></item><item><p>If an <elcode>xsl:evaluate</elcode> instruction has an
                           <elcode>xsl:fallback</elcode> child, fallback processing takes place;</p></item><item><p>In the absence of an <elcode>xsl:fallback</elcode> child, a dynamic error is
                        raised if an <elcode>xsl:evaluate</elcode> instruction is evaluated. The
                        dynamic error may be caught using <elcode>xsl:try</elcode> and
                           <elcode>xsl:catch</elcode>.</p></item></ulist><p><error spec="XT" type="dynamic" class="DE" code="3175"><p>It is a <termref def="dt-dynamic-error"/> if an
                           <elcode>xsl:evaluate</elcode> instruction is evaluated when use of
                           <elcode>xsl:evaluate</elcode> has been statically or dynamically
                        disabled. </p></error></p><p>In consequence of these rules, the recommended approach for stylesheet authors to
                  write code that works whether or not <elcode>xsl:evaluate</elcode> is enabled is
                  to use an <elcode>xsl:fallback</elcode> child instruction. For example:</p><eg role="xslt-declaration" xml:space="preserve">&lt;xsl:variable name="isValid" as="xs:boolean"&gt;
  &lt;xsl:evaluate xpath="$validityCondition"&gt;
     &lt;xsl:fallback&gt;&lt;xsl:sequence select="true()"/&gt;&lt;/xsl:fallback&gt;
  &lt;/xsl:evaluate&gt;
&lt;/xsl:variable&gt;</eg><note><p>There may be circumstances where may be inappropriate to allow use of
                        <elcode>xsl:evaluate</elcode>. For example:</p><ulist><item><p>There may be security risks associated with the ability to execute code
                           from an untrusted source, which cannot be inspected during static
                           analysis. This risk is reduced in XSLT 4.0, because a processor
                           is <rfc2119>required</rfc2119> to offer the option <code nobreak="false">trusted="no"</code>,
                           which disables access to external resources. However, some risk remains
                           because untrusted code may still consume unbounded CPU or memory resource.</p></item><item><p>There may be environments where the available computing resources are
                           sufficient to enable pre-compiled stylesheets to be executed, but not to
                           enable XPath expressions to be compiled into executable code.</p></item></ulist></note></div3><div3 id="evaluate-examples"><head>Examples of <elcode>xsl:evaluate</elcode></head><example><head>Using a Dynamic Sort Key</head><p>A common requirement is to sort a table on the value of an expression which is
                     selected at run-time, perhaps by supplying the expression as a string-valued
                     parameter to the stylesheet. Suppose that such an expression is supplied to the
                     parameter:</p><eg role="xslt-declaration" xml:space="preserve">&lt;xsl:param name="sortkey" as="xs:string" select="'@name'"/&gt;</eg><p>Then the data may be sorted as follows:</p><eg role="non-xml" xml:space="preserve">&lt;xsl:sort&gt;
   &lt;xsl:evaluate xpath="$sortkey" as="xs:string" context-item="."/&gt;
&lt;/xsl:sort&gt;</eg><p>Note the importance in this use case of caching the compiled expression, since
                     it is evaluated repeatedly, once for each item in the list being sorted.</p></example><example><head>Getting a Function if it Exists</head><p>If the <xfunction>function-lookup</xfunction> function were not available
                     in the standard library, then a very similar function could be implemented like this:</p><eg role="xslt-declaration xmlns:f='f'" xml:space="preserve">&lt;xsl:function name="f:function-lookup"&gt;
  &lt;xsl:param name="name" as="xs:QName"/&gt;
  &lt;xsl:param name="arity" as="xs:integer"/&gt;
  &lt;xsl:try&gt;
    &lt;xsl:evaluate xpath="'Q{' || namespace-uri-from-QName($name) || '}' 
                || local-name-from-QName($name) || '#' || $arity"&gt;
      &lt;xsl:with-param name="name" as="xs:QName" select="$name"/&gt;
      &lt;xsl:with-param name="arity" as="xs:integer" select="$arity"/&gt;
    &lt;/xsl:evaluate&gt;
    &lt;xsl:catch errors="err:XTDE3160" select="()"/&gt;
  &lt;/xsl:try&gt;  
&lt;/xsl:function&gt;  
     </eg><note><p>The main difference between this function and the standard <xfunction>function-lookup</xfunction>
                     function is that there are differences in the functions that are visible: for example <xfunction>function-lookup</xfunction>
                  gives access to user-defined functions with private visibility, whereas <elcode>xsl:evaluate</elcode> does not.</p></note><p>The <elcode>xsl:evaluate</elcode> instruction uses the supplied QName and arity
                     to construct an expression of the form
                     <code nobreak="false">Q{namespace-uri}local#arity</code>, which is then evaluated to return a
                     function item representing the requested function.</p></example></div3></div2></div1><div1 id="creating-new-nodes"><head>Creating Nodes</head><p>This section describes instructions that directly create new nodes.</p><div2 id="literal-result-element"><head>Literal Result Elements</head><p>
               <termdef id="dt-literal-result-element" term="literal result element">In a <termref def="dt-sequence-constructor">sequence constructor</termref>, an element in the
                     <termref def="dt-stylesheet">stylesheet</termref> that does not belong to the
                     <termref def="dt-xslt-namespace">XSLT namespace</termref> and that is not an
                     <termref def="dt-extension-instruction">extension instruction</termref> (see
                     <specref ref="extension-instruction"/>) is classified as a <term>literal result
                     element</term>.</termdef> A literal result element is evaluated to construct a
               new element node with the same <termref def="dt-expanded-qname">expanded
                  QName</termref> (that is, the same namespace URI, local name, and namespace
               prefix). The result of evaluating a literal result element is a node sequence
               containing one element, the newly constructed element node.</p><p>The content of the element is a <termref def="dt-sequence-constructor">sequence
                  constructor</termref> (see <specref ref="sequence-constructors"/>). The sequence
               obtained by evaluating this sequence constructor, after prepending any attribute
               nodes produced as described in <specref ref="attributes-for-lres"/> and namespace
               nodes produced as described in <specref ref="lre-namespaces"/>, is used to construct
               the content of the element, following the rules in <specref ref="constructing-complex-content"/>
            </p><p>The base URI of the new element is copied from the base URI of the literal result
               element in the stylesheet, unless the content of the new element includes an
                  <code nobreak="false">xml:base</code> attribute, in which case the base URI of the new element is
               the value of that attribute, resolved (if it is a relative URI reference) against the base URI of the literal result element in
               the stylesheet. (Note, however, that this is only relevant when creating a parentless
               element. When the literal result element is copied to form a child of an element or
               document node, the base URI of the new copy is taken from that of its new
               parent.)</p><div3 id="setting-annotation-for-lre"><head>Setting the Type Annotation for Literal Result Elements</head><p>The attributes <code nobreak="false">xsl:type</code> and <code nobreak="false">xsl:validation</code> may be used
                  on a literal result element to invoke validation of the contents of the element
                  against a type definition or element declaration in a schema, and to determine the
                     <termref def="dt-type-annotation"/> that the new element node will carry. These
                  attributes also affect the type annotation carried by any elements and attributes
                  that have the new element node as an ancestor. These two attributes are both
                  optional, and if one is specified then the other <rfc2119>must</rfc2119> be
                  omitted.</p><p>The value of the <code nobreak="false">xsl:validation</code> attribute, if present, must be one of
                  the values <code nobreak="false">strict</code>, <code nobreak="false">lax</code>, <code nobreak="false">preserve</code>, or
                     <code nobreak="false">strip</code>. The value of the <code nobreak="false">xsl:type</code> attribute, if
                  present, must be an <termref def="dt-eqname">EQName</termref> identifying a type definition that is present in
                  the <termref def="dt-in-scope-schema-component">in-scope schema
                     components</termref> for the stylesheet. Neither attribute may be specified as
                  an <termref def="dt-attribute-value-template">attribute value template.</termref>
                  The effect of these attributes is described in <specref ref="validation"/>.</p></div3><div3 id="attributes-for-lres"><head>Attribute Nodes for Literal Result Elements</head><p>Attribute nodes for a literal result element may be created by including
                     <elcode>xsl:attribute</elcode> instructions within the <termref def="dt-sequence-constructor">sequence constructor</termref>. Additionally,
                  attribute nodes are created corresponding to the attributes of the literal result
                  element in the stylesheet, and as a result of expanding the
                     <code nobreak="false">xsl:use-attribute-sets</code> attribute of the literal result element, if
                  present.</p><p>The sequence that is used to construct the content of the literal result element
                  (as described in <specref ref="constructing-complex-content"/>) is the
                  concatenation of the following four sequences, in order:</p><olist><item><p>The sequence of namespace nodes produced as described in <specref ref="lre-namespaces"/>.</p></item><item><p>The sequence of attribute nodes produced by expanding the
                           <code nobreak="false">xsl:use-attribute-sets</code> attribute (if present) following the
                        rules given in <specref ref="attribute-sets"/>
                     </p></item><item><p>The attributes produced by processing the attributes of the literal result
                        element itself, other than attributes in the <termref def="dt-xslt-namespace">XSLT namespace</termref>. The way these are
                        processed is described below.</p></item><item><p>The sequence produced by evaluating the contained <termref def="dt-sequence-constructor">sequence constructor</termref>, if the
                        element is not empty.</p></item></olist><note><p>The significance of this order is that an attribute produced by an
                        <elcode>xsl:attribute</elcode>, <elcode>xsl:copy</elcode>, or
                        <elcode>xsl:copy-of</elcode> instruction in the content of the literal
                     result element takes precedence over an attribute produced by expanding an
                     attribute of the literal result element itself, which in turn takes precedence
                     over an attribute produced by expanding the <code nobreak="false">xsl:use-attribute-sets</code>
                     attribute. This is because of the rules in <specref ref="constructing-complex-content"/>, which specify that when two or more
                     attributes in the sequence have the same name, all but the last of the
                     duplicates are discarded.</p><p>Although the above rules place namespace nodes before attributes, this is not
                     strictly necessary, because the rules in <specref ref="constructing-complex-content"/> allow the namespaces and attributes to
                     appear in any order so long as both come before other kinds of node. The order
                     of namespace nodes and attribute nodes in the sequence has no effect on the
                     relative position of the nodes in document order once they are added to a
                     tree.</p></note><p>Each attribute of the literal result element, other than an attribute in the
                     <termref def="dt-xslt-namespace">XSLT namespace</termref>, is processed to
                  produce an attribute for the element in the <termref def="dt-result-tree">result
                     tree</termref>.</p><p>The value of such an attribute is interpreted as an <termref def="dt-attribute-value-template">attribute value template</termref>: it can
                  therefore contain <termref def="dt-expression">expressions</termref> contained in
                  curly brackets (<code nobreak="false">{}</code>). The new attribute node will have the same
                     <termref def="dt-expanded-qname">expanded QName</termref> (that is, the same
                  namespace URI, local name, and namespace prefix) as the attribute in the
                  stylesheet tree, and its <termref def="dt-string-value">string value</termref>
                  will be the same as the <termref def="dt-effective-value">effective
                     value</termref> of the attribute in the stylesheet tree. The <termref def="dt-type-annotation">type annotation</termref> on the attribute will
                  initially be <code nobreak="false">xs:untypedAtomic</code>, and the <termref def="dt-typed-value">typed value</termref> of the attribute node will be the same as its <termref def="dt-string-value">string value</termref>.</p><note><p>The eventual <termref def="dt-type-annotation"/> of the attribute in the
                        <termref def="dt-result-tree">result tree</termref> depends on the
                        <code nobreak="false">xsl:validation</code> and <code nobreak="false">xsl:type</code> attributes of the
                     parent literal result element, and on the instructions used to create its
                     ancestor elements. If the <code nobreak="false">xsl:validation</code> attribute is set to
                        <code nobreak="false">preserve</code> or <code nobreak="false">strip</code>, the type annotation will be
                        <code nobreak="false">xs:untypedAtomic</code>, and the <termref def="dt-typed-value">typed
                        value</termref> of the attribute node will be the same as its <termref def="dt-string-value">string value</termref>. If the
                        <code nobreak="false">xsl:validation</code> attribute is set to <code nobreak="false">strict</code> or
                        <code nobreak="false">lax</code>, or if the <code nobreak="false">xsl:type</code> attribute is used, the
                     type annotation on the attribute will be set as a result of the schema
                     validation process applied to the parent element. If neither attribute is
                     present, the type annotation on the attribute will be
                        <code nobreak="false">xs:untypedAtomic</code>.</p></note><p>If the name of a constructed attribute is <code nobreak="false">xml:id</code>, the processor must
                  perform attribute value normalization by effectively applying the
                     <xfunction>normalize-space</xfunction> function to the value of the attribute,
                  and the resulting attribute node must be given the <code nobreak="false">is-id</code>
                  property.</p><note><p> If the attribute name is <code nobreak="false">xml:space</code>, it is <emph>not</emph> an
                     error when the value is something other than <code nobreak="false">default</code> or
                        <code nobreak="false">preserve</code>. Although the XML specification states that other
                     values are erroneous, a document containing such values is well-formed; if
                     erroneous values are to be rejected, schema validation should be used. </p></note><note><p>The <code nobreak="false">xml:base</code>, <code nobreak="false">xml:lang</code>, <code nobreak="false">xml:space</code>, and
                        <code nobreak="false">xml:id</code> attributes have two effects in XSLT. They behave as
                     standard XSLT attributes, which means for example that if they appear on a
                     literal result element, they will be copied to the <termref def="dt-result-tree">result tree</termref> in the same way as any other
                     attribute. In addition, they have their standard meaning as defined in the core
                     XML specifications. Thus, an <code nobreak="false">xml:base</code> attribute in the stylesheet
                     affects the base URI of the element on which it appears, and an
                        <code nobreak="false">xml:space</code> attribute affects the interpretation of <termref def="dt-whitespace-text-node">whitespace text nodes</termref> within that
                     element. One consequence of this is that it is inadvisable to write these
                     attributes as attribute value templates: although an XSLT processor will
                     understand this notation, the XML parser will not. See also <specref ref="namespace-aliasing"/> which describes how to use
                        <elcode>xsl:namespace-alias</elcode> with these attributes.</p><p>The same is true of the schema-defined attributes <code nobreak="false">xsi:type</code>,
                        <code nobreak="false">xsi:nil</code>, <code nobreak="false">xsi:noNamespaceSchemaLocation</code>, and
                        <code nobreak="false">xsi:schemaLocation</code>. If the stylesheet is processed by a schema
                     processor, these attributes will be recognized and interpreted by the schema
                     processor, but in addition the XSLT processor treats them like any other
                     attribute on a literal result element: that is, their <termref def="dt-effective-value">effective value</termref> (after expanding <termref def="dt-attribute-value-template">attribute value templates</termref>) is
                     copied to the result tree in the same way as any other attribute. If the
                        <termref def="dt-result-tree">result tree</termref> is validated, the copied
                     attributes will again be recognized and interpreted by the schema
                     processor.</p><p>None of these attributes will be generated in the <termref def="dt-result-tree">result tree</termref> unless the stylesheet writes them to the result tree
                     explicitly, in the same way as any other attribute.</p></note><p>
                  <error spec="XT" type="static" class="SE" code="0805"><p>It is a <termref def="dt-static-error">static error</termref> if an
                        attribute on a literal result element is in the <termref def="dt-xslt-namespace">XSLT namespace</termref>, unless it is one of the
                        attributes explicitly defined in this specification.</p></error>
               </p><note><p>If there is a need to create attributes in the XSLT namespace, this can be
                     achieved using <elcode>xsl:attribute</elcode>, or by means of the
                        <elcode>xsl:namespace-alias</elcode> declaration.</p></note></div3><div3 id="lre-namespaces"><head>Namespace Nodes for Literal Result Elements</head><p>The created element node will have a copy of the namespace nodes that were present
                  on the element node in the stylesheet tree with the exception of any namespace
                  node whose <termref def="dt-string-value">string value</termref> is designated as
                  an <term>excluded namespace</term>. Special considerations apply to aliased
                  namespaces: see <specref ref="namespace-aliasing"/>.
               </p><p>The following namespaces are designated as excluded namespaces:</p><ulist><item><p>The <termref def="dt-xslt-namespace">XSLT namespace</termref> URI
                           (<code nobreak="false">http://www.w3.org/1999/XSL/Transform</code>)</p></item><item><p>A namespace URI declared as an extension namespace (see <specref ref="extension-instruction"/>)</p></item><item><p>A namespace URI designated by using an
                           <code nobreak="false">[xsl:]exclude-result-prefixes</code> attribute either on the
                        literal result element itself or on an ancestor element. The attribute
                           <rfc2119>must</rfc2119> be in the XSLT namespace only if its parent
                        element is <emph>not</emph> in the XSLT namespace.</p><p>The value of the attribute is either <code nobreak="false">#all</code>, or a
                        whitespace-separated list of tokens, each of which is either a namespace
                        prefix or <code nobreak="false">#default</code>. The namespace bound to each of the prefixes
                        is designated as an excluded namespace.</p><p>
                        <error class="SE" type="static" spec="XT" code="0808"><p>It is a <termref def="dt-static-error">static error</termref> if a
                              namespace prefix is used within the
                                 <code nobreak="false">[xsl:]exclude-result-prefixes</code> attribute and there is
                              no namespace binding in scope for that prefix.</p></error>
                     </p><note><p>The prefix must be declared in a 
                        <termref def="dt-native-namespace-bindings">native namespace binding</termref>,
                        not in a <termref def="dt-fixed-namespace-bindings">fixed namespace binding</termref>.</p></note><p>The default namespace of the parent element of the
                           <code nobreak="false">[xsl:]exclude-result-prefixes</code> attribute (see <xspecref spec="DM40" ref="ElementNode"/>) may be designated as an excluded
                        namespace by including <code nobreak="false">#default</code> in the list of namespace
                        prefixes.</p><p>
                        <error class="SE" type="static" spec="XT" code="0809"><p>It is a <termref def="dt-static-error">static error</termref> if the
                              value <code nobreak="false">#default</code> is used within the
                                 <code nobreak="false">[xsl:]exclude-result-prefixes</code> attribute and the parent
                              element of the <code nobreak="false">[xsl:]exclude-result-prefixes</code> attribute
                              has no default namespace.</p></error>
                     </p><p>The value <code nobreak="false">#all</code> indicates that all namespaces that are in scope
                        for the stylesheet element that is the parent of the
                           <code nobreak="false">[xsl:]exclude-result-prefixes</code> attribute are designated as
                        excluded namespaces.</p><p>The designation of a namespace as an excluded namespace is effective within
                        the subtree of the stylesheet module rooted at the element bearing the
                           <code nobreak="false">[xsl:]exclude-result-prefixes</code> attribute; a subtree rooted at
                        an <elcode>xsl:stylesheet</elcode> element does not include any stylesheet
                        modules imported or included by children of that
                           <elcode>xsl:stylesheet</elcode> element.</p></item></ulist><p>The excluded namespaces, as described above, <emph>only</emph> affect namespace
                  nodes copied from the stylesheet when processing a literal result element. There
                  is no guarantee that an excluded namespace will not appear on the <termref def="dt-result-tree">result tree</termref> for some other reason. Namespace
                  nodes are also written to the result tree as part of the process of namespace
                  fixup (see <specref ref="namespace-fixup"/>), or as the result of instructions
                  such as <elcode>xsl:copy</elcode> and <elcode>xsl:element</elcode>.</p><note><p>When a stylesheet uses a namespace declaration only for the purposes of
                     addressing a <termref def="dt-source-tree">source tree</termref>, specifying
                     the prefix in the <code nobreak="false">[xsl:]exclude-result-prefixes</code> attribute will
                     avoid superfluous namespace declarations in the serialized <termref def="dt-result-tree">result tree</termref>. The attribute is also useful to
                     prevent namespaces used solely for the naming of stylesheet functions or
                     extension functions from appearing in the serialized result tree.</p><p diff="add" at="2023-11-28">In XSLT 4.0, a simpler approach is to declare such namespaces in a <code nobreak="false">fixed-namespaces</code>
                  attribute on the <code nobreak="false">xsl:stylesheet</code> element: see <specref ref="fixed-namespaces"/>.
                     Namespace prefixes declared in that way are not eligible to be used in the names
                     of literal result elements and their attributes, and they are not copied into the 
                     result tree.
                  </p></note><example><head>Excluding Namespaces from the Result Tree</head><p>Consider the following stylesheet:</p><eg xml:space="preserve" role="xslt-document">&lt;xsl:stylesheet version="1.0"
  xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
  xmlns:a="a.uri"
  xmlns:b="b.uri"
  exclude-result-prefixes="#all"&gt;
  
&lt;xsl:template match="/"&gt;
  &lt;foo xmlns:c="c.uri" xmlns:d="d.uri" xmlns:a2="a.uri" 
       xsl:exclude-result-prefixes="c"/&gt;
&lt;/xsl:template&gt;

&lt;/xsl:stylesheet&gt;</eg><p>The result of this stylesheet will be:</p><eg xml:space="preserve" role="xml">&lt;foo xmlns:d="d.uri"/&gt;</eg><p>The namespaces <code nobreak="false">a.uri</code> and <code nobreak="false">b.uri</code> are excluded by virtue
                     of the <code nobreak="false">exclude-result-prefixes</code> attribute on the
                        <elcode>xsl:stylesheet</elcode> element, and the namespace
                        <code nobreak="false">c.uri</code> is excluded by virtue of the
                        <code nobreak="false">xsl:exclude-result-prefixes</code> attribute on the <code nobreak="false">foo</code>
                     element. The setting <code nobreak="false">#all</code> does not affect the namespace
                        <code nobreak="false">d.uri</code> because <code nobreak="false">d.uri</code> is not an in-scope namespace
                     for the <elcode>xsl:stylesheet</elcode> element. The element in the <termref def="dt-result-tree">result tree</termref> does not have a namespace node
                     corresponding to <code nobreak="false">xmlns:a2="a.uri"</code> because the effect of
                        <code nobreak="false">exclude-result-prefixes</code> is to designate the namespace URI
                        <code nobreak="false">a.uri</code> as an excluded namespace, irrespective of how many
                     prefixes are bound to this namespace URI.</p><p>If the stylesheet is changed so that the literal result element has an
                     attribute <code nobreak="false">b:bar="3"</code>, then the element in the <termref def="dt-result-tree">result tree</termref> will typically have a namespace
                     declaration <code nobreak="false">xmlns:b="b.uri"</code> (the processor may choose a different
                     namespace prefix if this is necessary to avoid conflicts). The
                        <code nobreak="false">exclude-result-prefixes</code> attribute makes <code nobreak="false">b.uri</code> an
                     excluded namespace, so the namespace node is not automatically copied from the
                     stylesheet, but the presence of an attribute whose name is in the namespace
                        <code nobreak="false">b.uri</code> forces the namespace fixup process (see <specref ref="namespace-fixup"/>) to introduce a namespace node for this
                     namespace.</p></example><p>A literal result element may have an optional <code nobreak="false">xsl:inherit-namespaces</code>
                  attribute, with the value <code nobreak="false">yes</code> or <code nobreak="false">no</code>. The default value
                  is <code nobreak="false">yes</code>. If the value is set to <code nobreak="false">yes</code>, or is omitted, then
                  the namespace nodes created for the newly constructed element are copied to the
                  children and descendants of the newly constructed element, as described in
                     <specref ref="constructing-complex-content"/>. If the value is set to
                     <code nobreak="false">no</code>, then these namespace nodes are not automatically copied to the
                  children. This may result in namespace undeclarations (such as
                     <code nobreak="false">xmlns=""</code> or, in the case of XML 1.1, <code nobreak="false">xmlns:p=""</code>)
                  appearing on the child elements when they are serialized.</p></div3><div3 id="namespace-aliasing"><head>Namespace Aliasing</head><p>When a stylesheet is used to define a transformation whose output is itself a
                  stylesheet module, or in certain other cases where the result document uses
                  namespaces that it would be inconvenient to use in the stylesheet, namespace
                  aliasing can be used to declare a mapping between a namespace URI used in the
                  stylesheet and the corresponding namespace URI to be used in the result
                  document.</p><p>
                  <termdef id="dt-literal-namespace-uri" term="literal namespace URI">A namespace
                     URI in the stylesheet tree that is being used to specify a namespace URI in the
                        <termref def="dt-result-tree">result tree</termref> is called a
                        <term>literal namespace URI</term>.</termdef>
               </p><p>
                  <termdef id="dt-target-namespace-uri" term="target namespace URI">The namespace
                     URI that is to be used in the <termref def="dt-result-tree">result
                        tree</termref> as a substitute for a <termref def="dt-literal-namespace-uri">literal namespace URI</termref> is called the <term>target namespace
                        URI</term>.</termdef>
               </p><p>Either of the <termref def="dt-literal-namespace-uri">literal namespace
                     URI</termref> or the <termref def="dt-target-namespace-uri">target namespace
                     URI</termref> can be <emph>null</emph>: this is treated as a reference to the
                  set of names that are in no namespace.</p><e:element-syntax xmlns:e="http://www.w3.org/1999/XSL/Spec/ElementSyntax" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" name="namespace-alias">
      <e:in-category name="declaration"/>
      <e:attribute name="stylesheet-prefix" required="yes">
         <e:data-type name="prefix"/>
         <e:constant value="#default"/>
      </e:attribute>
      <e:attribute name="result-prefix" required="yes">
         <e:data-type name="prefix"/>
         <e:constant value="#default"/>
      </e:attribute>
      <e:empty/>
      <e:allowed-parents>
         <e:parent name="package"/>
         <e:parent name="stylesheet"/>
         <e:parent name="transform"/>
      </e:allowed-parents>
   </e:element-syntax><p>
                  <termdef id="dt-alias" term="alias">A stylesheet can use the
                        <elcode>xsl:namespace-alias</elcode> element to declare that a <termref def="dt-literal-namespace-uri">literal namespace URI</termref> is being used
                     as an <term>alias</term> for a <termref def="dt-target-namespace-uri">target
                        namespace URI</termref>.</termdef>
               </p><p>The effect is that when names in the namespace identified by the <termref def="dt-literal-namespace-uri">literal namespace URI</termref> are copied to
                  the <termref def="dt-result-tree">result tree</termref>, the namespace URI in the
                  result tree will be the <termref def="dt-target-namespace-uri">target namespace
                     URI</termref>, instead of the literal namespace URI. This applies to:</p><ulist><item><p>the namespace URI in the <termref def="dt-expanded-qname">expanded
                           QName</termref> of a literal result element in the stylesheet</p></item><item><p>the namespace URI in the <termref def="dt-expanded-qname">expanded
                           QName</termref> of an attribute specified on a literal result element in
                        the stylesheet</p></item></ulist><p>The effect of an <elcode>xsl:namespace-alias</elcode>
                  declaration is local to the <termref def="dt-package">package</termref> in which
                  it appears: that is, it only affects the result of <termref def="dt-literal-result-element">literal result elements</termref> within the
                  same package.</p><p>Where namespace aliasing changes the namespace URI part of the <termref def="dt-expanded-qname">expanded QName</termref> containing the name of an
                  element or attribute node, the namespace prefix in that expanded QName is replaced
                  by the prefix indicated by the <code nobreak="false">result-prefix</code> attribute of the
                     <elcode>xsl:namespace-alias</elcode> declaration.</p><p>The <elcode>xsl:namespace-alias</elcode> element declares that the namespace URI
                  bound to the prefix specified by the <code nobreak="false">stylesheet-prefix</code> is the
                     <termref def="dt-literal-namespace-uri">literal namespace URI</termref>, and
                  the namespace URI bound to the prefix specified by the <code nobreak="false">result-prefix</code>
                  attribute is the <termref def="dt-target-namespace-uri">target namespace
                     URI</termref>. Thus, the <code nobreak="false">stylesheet-prefix</code> attribute specifies the
                  namespace URI that will appear in the stylesheet, and the
                     <code nobreak="false">result-prefix</code> attribute specifies the corresponding namespace URI
                  that will appear in the <termref def="dt-result-tree">result tree</termref>. </p><note diff="add" at="2023-05-04"><p>It is the <termref def="dt-native-namespace-bindings"/> that apply,
                  not the <termref def="dt-fixed-namespace-bindings"/>. More specifically: if a prefix <code nobreak="false">p</code>
               appears in the <code nobreak="false">stylesheet-prefix</code> or <code nobreak="false">result-prefix</code> attribute,
               there must be an in-scope namespace declaration of the form <code nobreak="false">xmlns:p="...."</code>;
               it is not sufficient to declare the namespace in the <code nobreak="false">fixed-namespaces</code>
               attribute of the <elcode>xsl:stylesheet</elcode> element.</p></note><p>The default namespace (as declared by <code nobreak="false">xmlns</code>) may be specified by
                  using <code nobreak="false">#default</code> instead of a prefix. If no default namespace is in
                  force, specifying <code nobreak="false">#default</code> denotes the null namespace URI. This
                  allows elements that are in no namespace in the stylesheet to acquire a namespace
                  in the result document, or vice versa. <phrase diff="add" at="2022-01-01">
                     Defining an alias for the null namespace URI does not affect no-namespace attributes; 
                     these remain in no namespace. However, where <code nobreak="false">result-prefix="#default"</code> is specified and 
                     no default namespace is in force, attributes whose namespace matches the literal namespace 
                     URI are renamed to be in no namespace.
                  </phrase></p><p>If a <termref def="dt-literal-namespace-uri">literal namespace URI</termref> is
                  declared to be an alias for multiple different <termref def="dt-literal-namespace-uri">target namespace URIs</termref>, then the
                  declaration with the highest <termref def="dt-import-precedence">import
                     precedence</termref> is used.</p><p>
                  <error spec="XT" type="static" class="SE" code="0810"><p>It is a <termref def="dt-static-error">static error</termref> if within a <termref def="dt-package">package</termref> there is more than one such declaration
                           <error.extra>more than one <elcode>xsl:namespace-alias</elcode>
                           declaration</error.extra> with the same <termref def="dt-literal-namespace-uri">literal namespace URI</termref> and the
                        same <termref def="dt-import-precedence">import precedence</termref> and
                        different values for the <termref def="dt-target-namespace-uri">target
                           namespace URI</termref>, unless there is also an
                           <elcode>xsl:namespace-alias</elcode> declaration with the same <termref def="dt-literal-namespace-uri">literal namespace URI</termref> and a
                        higher import precedence. </p></error>
               </p><p>No error occurs if there is more than one such
                     <elcode>xsl:namespace-alias</elcode> declaration having the same <termref def="dt-literal-namespace-uri">literal namespace URI</termref> and the same
                     <termref def="dt-target-namespace-uri">target namespace URI</termref>, even if
                  the <code nobreak="false">result-prefix</code> differs; in this case the
                     <code nobreak="false">result-prefix</code> used is the one that appears last in <termref def="dt-declaration-order">declaration order</termref>. </p><p>
                  <error spec="XT" type="static" class="SE" code="0812"><p>It is a <termref def="dt-static-error">static error</termref> if a value
                        other than <code nobreak="false">#default</code> is specified for either the
                           <code nobreak="false">stylesheet-prefix</code> or the <code nobreak="false">result-prefix</code>
                        attributes of the <elcode>xsl:namespace-alias</elcode> element when there is
                        no in-scope binding for that namespace prefix.</p></error>
               </p><p>When a literal result element is processed, its namespace nodes are handled as
                  follows:</p><ulist><item><p>A namespace node whose string value is a <termref def="dt-literal-namespace-uri">literal namespace URI</termref> is not
                        copied to the <termref def="dt-result-tree">result tree</termref>.</p></item><item><p>A namespace node whose string value is a <termref def="dt-target-namespace-uri">target namespace URI</termref> is copied to
                        the <termref def="dt-result-tree">result tree</termref>, whether or not the
                        URI identifies an excluded namespace.</p></item></ulist><p>In the event that the same URI is used as a <termref def="dt-literal-namespace-uri">literal namespace URI</termref> and a <termref def="dt-target-namespace-uri">target namespace URI</termref>, the second of
                  these rules takes precedence.</p><note><p>These rules achieve the effect that the element generated from the literal
                     result element will have an in-scope namespace node that binds the
                        <code nobreak="false">result-prefix</code> to the <termref def="dt-target-namespace-uri">target namespace URI</termref>, provided that the namespace declaration
                     associating this prefix with this URI is in scope for both the
                        <elcode>xsl:namespace-alias</elcode> instruction and for the literal result
                     element. Conversely, the <code nobreak="false">stylesheet-prefix</code> and the <termref def="dt-literal-namespace-uri">literal namespace URI</termref> will not
                     normally appear in the <termref def="dt-result-tree">result tree</termref>.</p></note><example><head>Using <elcode>xsl:namespace-alias</elcode> to Generate a Stylesheet</head><p>When literal result elements are being used to create element, attribute, or
                     namespace nodes that use the <termref def="dt-xslt-namespace">XSLT
                        namespace</termref> URI, the stylesheet may use an alias. </p><p>For example, the stylesheet</p><eg xml:space="preserve" role="xslt-document">&lt;xsl:stylesheet
  version="3.0"
  xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
  xmlns:fo="http://www.w3.org/1999/XSL/Format"
  xmlns:axsl="file://namespace.alias"&gt;

&lt;xsl:namespace-alias stylesheet-prefix="axsl" result-prefix="xsl"/&gt;

&lt;xsl:template match="/"&gt;
  &lt;axsl:stylesheet version="3.0"&gt;
    &lt;xsl:apply-templates/&gt;
  &lt;/axsl:stylesheet&gt;
&lt;/xsl:template&gt;

&lt;xsl:template match="elements"&gt;
  &lt;axsl:template match="/"&gt;
     &lt;axsl:comment select="system-property('xsl:version')"/&gt;
     &lt;xsl:apply-templates/&gt;
  &lt;/axsl:template&gt;
&lt;/xsl:template&gt;

&lt;xsl:template match="block"&gt;
  &lt;axsl:template match="{.}"&gt;
     &lt;fo:block&gt;&lt;axsl:apply-templates/&gt;&lt;/fo:block&gt;
  &lt;/axsl:template&gt;
&lt;/xsl:template&gt;

&lt;/xsl:stylesheet&gt;</eg><p>will generate an XSLT stylesheet from a document of the form:</p><eg xml:space="preserve" role="xml">&lt;elements&gt;
&lt;block&gt;p&lt;/block&gt;
&lt;block&gt;h1&lt;/block&gt;
&lt;block&gt;h2&lt;/block&gt;
&lt;block&gt;h3&lt;/block&gt;
&lt;block&gt;h4&lt;/block&gt;
&lt;/elements&gt;</eg><p>The output of the transformation will be a stylesheet such as the following.
                     Whitespace has been added for clarity. Note that an implementation may output
                     different namespace prefixes from those appearing in this example; however, the
                     rules guarantee that there will be a namespace node that binds the prefix
                        <code nobreak="false">xsl</code> to the URI
                        <code nobreak="false">http://www.w3.org/1999/XSL/Transform</code>, which makes it safe to
                     use the QName <code nobreak="false">xsl:version</code> in the content of the generated
                     stylesheet.</p><eg xml:space="preserve" role="xslt-document">&lt;xsl:stylesheet
  version="3.0"
  xmlns:xsl="http://www.w3.org/1999/XSL/Transform" 
  xmlns:fo="http://www.w3.org/1999/XSL/Format"&gt;

&lt;xsl:template match="/"&gt;
  &lt;xsl:comment select="system-property('xsl:version')"/&gt;
  &lt;xsl:apply-templates/&gt;
&lt;/xsl:template&gt;
  
&lt;xsl:template match="p"&gt;
  &lt;fo:block&gt;&lt;xsl:apply-templates/&gt;&lt;/fo:block&gt;
&lt;/xsl:template&gt;

&lt;xsl:template match="h1"&gt;
  &lt;fo:block&gt;&lt;xsl:apply-templates/&gt;&lt;/fo:block&gt;
&lt;/xsl:template&gt;

&lt;xsl:template match="h2"&gt;
  &lt;fo:block&gt;&lt;xsl:apply-templates/&gt;&lt;/fo:block&gt;
&lt;/xsl:template&gt;

&lt;xsl:template match="h3"&gt;
  &lt;fo:block&gt;&lt;xsl:apply-templates/&gt;&lt;/fo:block&gt;
&lt;/xsl:template&gt;

&lt;xsl:template match="h4"&gt;
  &lt;fo:block&gt;&lt;xsl:apply-templates/&gt;&lt;/fo:block&gt;
&lt;/xsl:template&gt;

&lt;/xsl:stylesheet&gt;</eg></example><note><p>It may be necessary also to use aliases for namespaces other than the XSLT
                     namespace URI. For example, it can be useful to define an alias for the
                     namespace <code nobreak="false">http://www.w3.org/2001/XMLSchema-instance</code>, so that the
                     stylesheet can use the attributes <code nobreak="false">xsi:type</code>, <code nobreak="false">xsi:nil</code>,
                     and <code nobreak="false">xsi:schemaLocation</code> on a literal result element, without
                     running the risk that a schema processor will interpret these as applying to
                     the stylesheet itself. Equally, literal result elements belonging to a
                     namespace dealing with digital signatures might cause XSLT stylesheets to be
                     mishandled by general-purpose security software; using an alias for the
                     namespace would avoid the possibility of such mishandling.</p></note><example><head>Aliasing the XML Namespace</head><p>It is possible to define an alias for the XML namespace.</p><eg xml:space="preserve" role="xslt-document">
&lt;xsl:stylesheet xmlns:axml="http://www.example.com/alias-xml"
                xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
                version="3.0"&gt;

&lt;xsl:namespace-alias stylesheet-prefix="axml" result-prefix="xml"/&gt;

&lt;xsl:template match="/"&gt;
  &lt;name axml:space="preserve"&gt;
    &lt;first&gt;James&lt;/first&gt;
    &lt;xsl:text&gt; &lt;/xsl:text&gt;
    &lt;last&gt;Clark&lt;/last&gt;
  &lt;/name&gt;
&lt;/xsl:template&gt;

&lt;/xsl:stylesheet&gt;</eg><p>produces the output:</p><eg xml:space="preserve" role="xml">&lt;name xml:space="preserve"&gt;&lt;first&gt;James&lt;/first&gt; &lt;last&gt;Clark&lt;/last&gt;&lt;/name&gt;</eg><p>This allows an <code nobreak="false">xml:space</code> attribute to be generated in the output
                     without affecting the way the stylesheet is parsed. The same technique can be
                     used for other attributes such as <code nobreak="false">xml:lang</code>, <code nobreak="false">xml:base</code>,
                     and <code nobreak="false">xml:id</code>.</p></example><note><p>Namespace aliasing is only necessary when literal result elements are used. The
                     problem of reserved namespaces does not arise when using
                        <elcode>xsl:element</elcode> and <elcode>xsl:attribute</elcode> to construct
                     the <termref def="dt-result-tree">result tree</termref>. Therefore, as an
                     alternative to using <elcode>xsl:namespace-alias</elcode>, it is always
                     possible to achieve the desired effect by replacing literal result elements
                     with <elcode>xsl:element</elcode> and <elcode>xsl:attribute</elcode>
                     instructions.</p></note></div3></div2><div2 id="xsl-element"><head>Creating Element Nodes Using <code nobreak="false">xsl:element</code>
            </head><e:element-syntax xmlns:e="http://www.w3.org/1999/XSL/Spec/ElementSyntax" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" name="element">
      <e:in-category name="instruction"/>
      <e:attribute name="name" required="yes">
         <e:attribute-value-template>
            <e:data-type name="qname"/>
         </e:attribute-value-template>
      </e:attribute>
      <e:attribute name="namespace">
         <e:attribute-value-template>
            <e:data-type name="uri"/>
         </e:attribute-value-template>
      </e:attribute>
      <e:attribute name="inherit-namespaces" default="'yes'">
         <e:data-type name="boolean"/>
      </e:attribute>
      <e:attribute name="use-attribute-sets" default="''">
         <e:data-type name="eqnames"/>
      </e:attribute>
      <e:attribute name="type">
         <e:data-type name="eqname"/>
      </e:attribute>
      <e:attribute name="validation">
         <e:constant value="strict"/>
         <e:constant value="lax"/>
         <e:constant value="preserve"/>
         <e:constant value="strip"/>
      </e:attribute>
      <e:model name="sequence-constructor"/>
      <e:allowed-parents>
         <e:parent-category name="sequence-constructor"/>
      </e:allowed-parents>
   </e:element-syntax><p>The <elcode>xsl:element</elcode> instruction allows an element to be created with a
               computed name. The <termref def="dt-expanded-qname">expanded QName</termref> of the
               element to be created is specified by a <rfc2119>required</rfc2119>
               <code nobreak="false">name</code> attribute and an optional <code nobreak="false">namespace</code> attribute.</p><p>The result of evaluating the <elcode>xsl:element</elcode> instruction, in usual circumstances, is the newly constructed
               element node.</p><div3 id="xsl-element-content"><head>The Content of the Constructed Element Node</head><p>The content of the <elcode>xsl:element</elcode> instruction is a <termref def="dt-sequence-constructor">sequence constructor</termref> for the children,
                  attributes, and namespaces of the created element. The sequence obtained by
                  evaluating this sequence constructor (see <specref ref="sequence-constructors"/>)
                  is used to construct the content of the element, as described in <specref ref="constructing-complex-content"/>.</p><p>The <elcode>xsl:element</elcode> element may have a
                     <code nobreak="false">use-attribute-sets</code> attribute, whose value is a
                  whitespace-separated list of QNames that identify
                     <elcode>xsl:attribute-set</elcode> declarations. If this attribute is present,
                  it is expanded as described in <specref ref="attribute-sets"/> to produce a
                  sequence of attribute nodes. This sequence is prepended to the sequence produced
                  as a result of evaluating the <termref def="dt-sequence-constructor"/>, as
                  described in <specref ref="constructing-complex-content"/>.</p></div3><div3 id="xsl-element-name"><head>The Name of the Constructed Element Node</head><p>The <code nobreak="false">name</code> attribute is interpreted as an <termref def="dt-attribute-value-template">attribute value template</termref>, whose
                     <termref def="dt-effective-value">effective value</termref>
                  <rfc2119>must</rfc2119> be a <termref def="dt-lexical-qname">lexical
                     QName</termref>.</p><p>
                  <error spec="XT" type="dynamic" class="DE" code="0820"><p>It is a <termref def="dt-dynamic-error"> dynamic error</termref> if the <termref def="dt-effective-value">effective value</termref> of the
                           <code nobreak="false">name</code> attribute <error.extra>of the
                              <elcode>xsl:element</elcode> instruction</error.extra> is not a
                           <termref def="dt-lexical-qname">lexical QName</termref>. </p></error>
               </p><p>
                  <error spec="XT" type="dynamic" class="DE" code="0830"><p>In the case of an <elcode>xsl:element</elcode> instruction with no
                           <code nobreak="false">namespace</code> attribute, it is a <termref def="dt-dynamic-error"> dynamic
                           error</termref> if the <termref def="dt-effective-value">effective
                           value</termref> of the <code nobreak="false">name</code> attribute is a <termref def="dt-lexical-qname">lexical QName</termref> whose prefix is not
                        declared in <phrase diff="chg" at="2023-05-04">the <termref def="dt-applicable-static-namespaces"/></phrase> for the
                           <elcode>xsl:element</elcode> instruction.</p></error>
               </p><note><p>If a <code nobreak="false">fixed-namespaces</code> attribute is present on the containing <elcode>xsl:stylesheet</elcode> or
               <elcode>xsl:package</elcode> element, then the prefix must be declared in that attribute, not in a
               <termref def="dt-native-namespace-bindings">native namespace binding</termref>.</p></note><p>If the <code nobreak="false">namespace</code> attribute is not present then the <termref def="dt-lexical-qname">lexical QName</termref> is expanded into an <termref def="dt-expanded-qname">expanded QName</termref> using the namespace
                  declarations in effect for the <elcode>xsl:element</elcode> element, including any
                  default namespace declaration.</p><p>If the <code nobreak="false">namespace</code> attribute is present, then it too is interpreted as
                  an <termref def="dt-attribute-value-template">attribute value template</termref>.
                  The <termref def="dt-effective-value">effective value</termref>
                  <rfc2119>must</rfc2119> be in the lexical space of the <code nobreak="false">xs:anyURI</code>
                  type. If the string is zero-length, then the <termref def="dt-expanded-qname">expanded QName</termref> of the element has a null namespace URI. Otherwise,
                  the string is used as the namespace URI of the <termref def="dt-expanded-qname">expanded QName</termref> of the element to be created. The local part of the
                     <termref def="dt-lexical-qname">lexical QName</termref> specified by the
                     <code nobreak="false">name</code> attribute is used as the local part of the <termref def="dt-expanded-qname">expanded QName</termref> of the element to be
                  created.</p><p>
                  <error spec="XT" type="dynamic" class="DE" code="0835"><p> It is a <termref def="dt-dynamic-error"> dynamic error</termref> if the <termref def="dt-effective-value"/> of the
                           <code nobreak="false">namespace</code> attribute <error.extra>of the
                              <elcode>xsl:element</elcode> instruction</error.extra> is not in the
                        lexical space of the <code nobreak="false">xs:anyURI</code> datatype or if it is the string
                           <code nobreak="false">http://www.w3.org/2000/xmlns/</code>.</p></error>
               </p><note><p>The XDM data model requires the name of a node to be an instance of
                        <code nobreak="false">xs:QName</code>, and XML Schema defines the namespace part of an
                        <code nobreak="false">xs:QName</code> to be an instance of <code nobreak="false">xs:anyURI</code>. However,
                     the schema specification, and the specifications that it refers to, give
                     implementations some flexibility in how strictly they enforce these
                     constraints.</p></note><p>The prefix of the <termref def="dt-lexical-qname">lexical QName</termref>
                  specified in the <code nobreak="false">name</code> attribute (or the absence of a prefix) is
                  copied to the prefix part of the <termref def="dt-expanded-qname">expanded
                     QName</termref> representing the name of the new element node. In the event of
                  a conflict a prefix may subsequently be added, changed, or removed during the
                  namespace fixup process (see <specref ref="namespace-fixup"/>). The term <emph>conflict</emph>
                  here means any violation of the constraints defined in <bibref ref="xpath-datamodel-40"/>, for example the use of the same prefix to refer to
                  two different namespaces in the element and in one of its attributes, the use of
                  the prefix <code nobreak="false">xml</code> to refer to a namespace other than the XML namespace,
                  or any use of the prefix
                  <code nobreak="false">xmlns</code>.</p></div3><div3 id="xsl-element-properties"><head>Other Properties of the Constructed Element Node</head><p>The <elcode>xsl:element</elcode> instruction has an optional
                     <code nobreak="false">inherit-namespaces</code> attribute, with the value <code nobreak="false">yes</code> or
                     <code nobreak="false">no</code>. The default value is <code nobreak="false">yes</code>. If the value is set to
                     <code nobreak="false">yes</code>, or is omitted, then the namespace nodes created for the newly
                  constructed element (whether these were copied from those of the source node, or
                  generated as a result of namespace fixup) are copied to the children and
                  descendants of the newly constructed element, as described in <specref ref="constructing-complex-content"/>. If the value is set to <code nobreak="false">no</code>,
                  then these namespace nodes are not automatically copied to the children. This may
                  result in namespace undeclarations (such as <code nobreak="false">xmlns=""</code> or, in the case
                  of XML Namespaces 1.1, <code nobreak="false">xmlns:p=""</code>) appearing on the child elements
                  when 
                  the element is serialized.</p><p>The base URI of the new element is copied from the base URI of the
                     <elcode>xsl:element</elcode> instruction in the stylesheet, unless the content
                  of the new element includes an <code nobreak="false">xml:base</code> attribute, in which case the
                  base URI of the new element is the value of that attribute, resolved (if it is a
                  relative URI) against the base URI of the <elcode>xsl:element</elcode> instruction
                  in the stylesheet. (Note, however, that this is only relevant when creating
                  parentless elements. When the new element is copied to form a child of an element
                  or document node, the base URI of the new copy is taken from that of its new
                  parent.)</p><p>The values of the <code nobreak="false">nilled</code>,
                     <code nobreak="false">is-id</code>, and <code nobreak="false">is-idrefs</code> properties of the new element
                  depend on the <code nobreak="false">type</code> and <code nobreak="false">validation</code> attributes of the
                     <elcode>xsl:element</elcode> instruction, as explained in <specref ref="validation"/>.</p></div3><div3 id="annotation-for-constructed-element"><head>The Type Annotation of the Constructed Element Node</head><p>The optional attributes <code nobreak="false">type</code> and <code nobreak="false">validation</code> may be used
                  on the <elcode>xsl:element</elcode> instruction to invoke validation of the
                  contents of the element against a type definition or element declaration in a
                  schema, and to determine the <termref def="dt-type-annotation">type
                     annotation</termref> that the new element node will carry. These attributes
                  also affect the type annotation carried by any elements and attributes that have
                  the new element node as an ancestor. These two attributes are both optional, and
                  if one is specified then the other <rfc2119>must</rfc2119> be omitted. The
                  permitted values of these attributes and their semantics are described in <specref ref="validation"/>.</p><note><p>The final type annotation of the element in the <termref def="dt-result-tree">result tree</termref> also depends on the <code nobreak="false">type</code> and
                        <code nobreak="false">validation</code> attributes of the instructions used to create the
                     ancestors of the element.</p></note></div3></div2><div2 id="creating-attributes"><head>Creating Attribute Nodes Using <code nobreak="false">xsl:attribute</code>
            </head><e:element-syntax xmlns:e="http://www.w3.org/1999/XSL/Spec/ElementSyntax" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" name="attribute">
      <e:in-category name="instruction"/>
      <e:attribute name="name" required="yes">
         <e:attribute-value-template>
            <e:data-type name="qname"/>
         </e:attribute-value-template>
      </e:attribute>
      <e:attribute name="namespace">
         <e:attribute-value-template>
            <e:data-type name="uri"/>
         </e:attribute-value-template>
      </e:attribute>
      <e:attribute name="select">
         <e:data-type name="expression"/>
      </e:attribute>
      <e:attribute name="separator">
         <e:attribute-value-template>
            <e:data-type name="string"/>
         </e:attribute-value-template>
      </e:attribute>
      <e:attribute name="type">
         <e:data-type name="eqname"/>
      </e:attribute>
      <e:attribute name="validation">
         <e:constant value="strict"/>
         <e:constant value="lax"/>
         <e:constant value="preserve"/>
         <e:constant value="strip"/>
      </e:attribute>
      <e:model name="sequence-constructor"/>
      <e:allowed-parents>
         <e:parent name="attribute-set"/>
         <e:parent-category name="sequence-constructor"/>
      </e:allowed-parents>
   </e:element-syntax><p>The <elcode>xsl:attribute</elcode> element can be used to add attributes to result
               elements whether created by literal result elements in the stylesheet or by
               instructions such as <elcode>xsl:element</elcode> or <elcode>xsl:copy</elcode>. The
                  <termref def="dt-expanded-qname">expanded QName</termref> of the attribute to be
               created is specified by a <rfc2119>required</rfc2119>
               <code nobreak="false">name</code> attribute and an optional <code nobreak="false">namespace</code> attribute. Except
               in error cases, the result of evaluating an <elcode>xsl:attribute</elcode>
               instruction is the newly constructed attribute node.</p><p>The string value of the new attribute node may be defined either by using the
                  <code nobreak="false">select</code> attribute, or by the <termref def="dt-sequence-constructor">sequence constructor</termref> that forms the content of the
                  <elcode>xsl:attribute</elcode> element. These are
                  mutually exclusive: if the <code nobreak="false">select</code> attribute is present then the
                  sequence constructor must be empty, and if the sequence constructor is non-empty
                  then the <code nobreak="false">select</code> attribute must be absent. If the <code nobreak="false">select</code>
                  attribute is absent and the sequence constructor is empty, then the
               string value of the new attribute node will be a zero-length string. The way in which
               the value is constructed is specified in <specref ref="constructing-simple-content"/>.</p><p>
               <error spec="XT" type="static" class="SE" code="0840"><p>It is a <termref def="dt-static-error">static error</termref> if the
                        <code nobreak="false">select</code> attribute of the <elcode>xsl:attribute</elcode> element
                     is present unless the element has empty content.</p></error>
            </p><p>If the <code nobreak="false">separator</code> attribute is present, then the <termref def="dt-effective-value">effective value</termref> of this attribute is used to
               separate adjacent items in the result sequence, as described in <specref ref="constructing-simple-content"/>. In the absence of this attribute, the default
               separator is <char>U+0020</char> when the content is specified using the
                  <code nobreak="false">select</code> attribute, or a zero-length string when the content is
               specified using a <termref def="dt-sequence-constructor">sequence
                  constructor</termref>.</p><p>The <code nobreak="false">name</code> attribute is interpreted as an <termref def="dt-attribute-value-template">attribute value template</termref>, whose
                  <termref def="dt-effective-value">effective value</termref>
               <rfc2119>must</rfc2119> be a <termref def="dt-lexical-qname">lexical
               QName</termref>.</p><p>
               <error spec="XT" type="dynamic" class="DE" code="0850"><p>It is a <termref def="dt-dynamic-error"> dynamic error</termref> if the <termref def="dt-effective-value">effective value</termref> 
                     of the <code nobreak="false">name</code>
                     attribute <error.extra>of an <elcode>xsl:attribute</elcode>
                        instruction</error.extra> is not a <termref def="dt-lexical-qname">lexical
                        QName</termref>.</p></error>
            </p><p>
               <error spec="XT" type="dynamic" class="DE" code="0855"><p>In the case of an <elcode>xsl:attribute</elcode> instruction with no
                        <code nobreak="false">namespace</code> attribute, it is a <termref def="dt-dynamic-error"> dynamic
                        error</termref> if the <termref def="dt-effective-value">effective
                        value</termref> of the <code nobreak="false">name</code> attribute is the string
                        <code nobreak="false">xmlns</code>.</p></error>
            </p><p>
               <error spec="XT" type="dynamic" class="DE" code="0860"><p>In the case of an <elcode>xsl:attribute</elcode> instruction with no
                        <code nobreak="false">namespace</code> attribute, it is a <termref def="dt-dynamic-error"> dynamic
                        error</termref> if the <termref def="dt-effective-value">effective
                        value</termref> of the <code nobreak="false">name</code> attribute is a <termref def="dt-lexical-qname">lexical QName</termref> whose prefix is not declared
                     in <phrase diff="chg" at="2023-05-04">the <termref def="dt-applicable-static-namespaces"/></phrase> 
                     for the <elcode>xsl:attribute</elcode>
                     instruction.</p></error>
            </p><note><p>If a <code nobreak="false">fixed-namespaces</code> attribute is present on the containing <elcode>xsl:stylesheet</elcode> or
               <elcode>xsl:package</elcode> element, then the prefix must be declared in that attribute, not in a
               <termref def="dt-native-namespace-bindings">native namespace binding</termref>.</p></note><p>If the <code nobreak="false">namespace</code> attribute is not present, then the <termref def="dt-lexical-qname">lexical QName</termref> is expanded into an <termref def="dt-expanded-qname">expanded QName</termref> using the namespace declarations
               in effect for the <elcode>xsl:attribute</elcode> element, <emph>not</emph> including
               any default namespace declaration.</p><p>If the <code nobreak="false">namespace</code> attribute is present, then it too is interpreted as an
                  <termref def="dt-attribute-value-template">attribute value template</termref>. The
                  <termref def="dt-effective-value">effective value</termref>
               <rfc2119>must</rfc2119> be in the lexical space of the <code nobreak="false">xs:anyURI</code> type.
               If the string is zero-length, then the <termref def="dt-expanded-qname">expanded
                  QName</termref> of the attribute has a null namespace URI. Otherwise, the string
               is used as the namespace URI of the <termref def="dt-expanded-qname">expanded
                  QName</termref> of the attribute to be created. The local part of the <termref def="dt-lexical-qname">lexical QName</termref> specified by the <code nobreak="false">name</code>
               attribute is used as the local part of the <termref def="dt-expanded-qname">expanded
                  QName</termref> of the attribute to be created.</p><p>
               <error spec="XT" type="dynamic" class="DE" code="0865"><p> It is a <termref def="dt-dynamic-error"> dynamic error</termref> if the <termref def="dt-effective-value">effective value</termref> of the
                        <code nobreak="false">namespace</code> attribute <error.extra>of the
                           <elcode>xsl:attribute</elcode> instruction</error.extra> is not in the
                     lexical space of the <code nobreak="false">xs:anyURI</code> datatype or if it is the string
                        <code nobreak="false">http://www.w3.org/2000/xmlns/</code>.</p></error>
            </p><note><p>The same considerations apply as for elements: <errorref spec="XT" class="DE" code="0835"/> in <specref ref="xsl-element"/>.</p></note><p>The prefix of the <termref def="dt-lexical-qname">lexical QName</termref> specified
               in the <code nobreak="false">name</code> attribute (or the absence of a prefix) is copied to the
               prefix part of the <termref def="dt-expanded-qname">expanded QName</termref>
               representing the name of the new attribute node. In the event of a conflict this
               prefix may subsequently be added, changed, or removed during the namespace fixup
               process (see <specref ref="namespace-fixup"/>). If the attribute is in a non-null
               namespace and no prefix is specified, then the namespace fixup process will invent a
               prefix. The term <emph>conflict</emph> here means any violation of the constraints
               defined in <bibref ref="xpath-datamodel-40"/>, for example the use of the same prefix
               to refer to two different namespaces in the element and in one of its attributes, the
               use of the prefix <code nobreak="false">xml</code> to refer to a namespace other than the XML
               namespace, or any use of the prefix <code nobreak="false">xmlns</code>.</p><p>If the name of a constructed attribute is <code nobreak="false">xml:id</code>, the processor must
               perform attribute value normalization by effectively applying the
                  <xfunction>normalize-space</xfunction> function to the value of the attribute, and
               the resulting attribute node must be given the <code nobreak="false">is-id</code> property. This
               applies whether the attribute is constructed using the <elcode>xsl:attribute</elcode>
               instruction or whether it is constructed using an attribute of a literal result
               element. This does not imply any constraints on the value of the attribute, or on its
               uniqueness, and it does not affect the <termref def="dt-type-annotation">type
                  annotation</termref> of the attribute, unless the containing document is
               validated.</p><note><p>The effect of setting the <code nobreak="false">is-id</code> property is that the parent element
                  can be located within the containing document by use of the
                     <xfunction>id</xfunction> function. In effect, XSLT when constructing a
                  document performs some of the functions of an <code nobreak="false">xml:id</code> processor, as
                  defined in <bibref ref="xml-id"/>; the other aspects of <code nobreak="false">xml:id</code>
                  processing are performed during validation.</p></note><example><head>Creating a List-Valued Attribute</head><p>The following instruction creates the attribute <code nobreak="false">colors="red green
                     blue"</code>:</p><eg xml:space="preserve" role="xslt-instruction">&lt;xsl:attribute name="colors" select="'red', 'green', 'blue'"/&gt;</eg></example><example><head>Namespaces are not Attributes</head><p>It is not an error to write:</p><eg xml:space="preserve" role="xslt-instruction">&lt;xsl:attribute name="xmlns:xsl" 
   namespace="file://some.namespace"
   select="'http://www.w3.org/1999/XSL/Transform'"/&gt;</eg><p>However, this will not result in the namespace declaration
                     <code nobreak="false">xmlns:xsl="http://www.w3.org/1999/XSL/Transform"</code> being output.
                  Instead, it will produce an attribute node with local name <code nobreak="false">xsl</code>, and
                  with a system-allocated namespace prefix mapped to the namespace URI
                     <code nobreak="false">file://some.namespace</code>. This is because the namespace fixup process
                  is not allowed to use <code nobreak="false">xmlns</code> as the name of a namespace node.</p></example><p>As described in <specref ref="constructing-complex-content"/>, in a sequence that is
               used to construct the content of an element, any attribute nodes
                  <rfc2119>must</rfc2119> appear in the sequence before any element, text, comment,
               or processing instruction nodes. Where the sequence contains two or more attribute
               nodes with the same <termref def="dt-expanded-qname">expanded QName</termref>, the
               one that comes last is the only one that takes effect.</p><note><p>If a collection of attributes is generated repeatedly, this can be done
                  conveniently by using named attribute sets: see <specref ref="attribute-sets"/>
               </p></note><div3 id="annotation-for-constructed-attribute"><head>Setting the Type Annotation for a Constructed Attribute Node</head><p>The optional attributes <code nobreak="false">type</code> and <code nobreak="false">validation</code> may be used
                  on the <elcode>xsl:attribute</elcode> instruction to invoke validation of the
                  contents of the attribute against a type definition or attribute declaration in a
                  schema, and to determine the <termref def="dt-type-annotation">type
                     annotation</termref> that the new attribute node will carry. These two
                  attributes are both optional, and if one is specified then the other
                     <rfc2119>must</rfc2119> be omitted. The permitted values of these attributes
                  and their semantics are described in <specref ref="validation"/>.</p><p>The process of validation also determines the values of
                  the <code nobreak="false">is-id</code> and <code nobreak="false">is-idrefs</code> properties on the new attribute
                  node.</p><note><p>The final <termref def="dt-type-annotation"/> of the attribute in the <termref def="dt-result-tree">result tree</termref> also depends on the
                        <code nobreak="false">type</code> and <code nobreak="false">validation</code> attributes of the instructions
                     used to create the ancestors of the attribute.</p></note></div3></div2><div2 id="creating-text-nodes"><head>Creating Text Nodes</head><changes><change issue="323" PR="2251" date="2025-10-14">
                  The <elcode>xsl:text</elcode> instruction can now have a <code nobreak="false">select</code> attribute,
                  and it can take a sequence constructor as its content. The only remaining distinction
                  between the <elcode>xsl:text</elcode> and <elcode>xsl:value-of</elcode> instructions
                  is that whitespace text node children of <elcode>xsl:text</elcode> are treated
                  as significant, rather than being stripped during stylesheet preprocessing.
               </change></changes><p>This section describes three different ways of creating text nodes: by means of
               literal text nodes in the stylesheet, or by using the <elcode>xsl:text</elcode> and
                  <elcode>xsl:value-of</elcode> instructions. It is also possible to create text
               nodes using the <elcode>xsl:number</elcode> instruction described in <specref ref="number"/>.</p><p>If and when the sequence that results from evaluating a <termref def="dt-sequence-constructor">sequence constructor</termref> is used to form the
               content of a node, as described in <specref ref="constructing-simple-content"/> and
                  <specref ref="constructing-complex-content"/>, adjacent text nodes in the sequence
               are merged. Within the sequence itself, however, they exist as distinct nodes.</p><example><head>A Sequence of Text Nodes</head><p>The following function returns a sequence of three text nodes:</p><eg xml:space="preserve" role="xslt-declaration xmlns:f='f'">&lt;xsl:function name="f:wrap"&gt;
  &lt;xsl:param name="s"/&gt;
  &lt;xsl:text&gt;(&lt;/xsl:text&gt;
  &lt;xsl:value-of select="$s"/&gt;
  &lt;xsl:text&gt;)&lt;/xsl:text&gt;
&lt;/xsl:function&gt;</eg><p>When this function is called as follows:</p><eg xml:space="preserve" role="xslt-instruction">&lt;xsl:value-of select="f:wrap('---')"/&gt;</eg><p>the result is:</p><eg xml:space="preserve" role="non-xml">(---)</eg><p>No additional spaces are inserted, because the calling
                     <elcode>xsl:value-of</elcode> instruction merges adjacent text nodes before
                  atomizing the sequence. However, the result of the instruction:</p><eg xml:space="preserve" role="xslt-instruction">&lt;xsl:value-of select="data(f:wrap('---'))"/&gt;</eg><p>is:</p><eg xml:space="preserve" role="non-xml">( --- )</eg><p>because in this case the three text nodes are atomized to form three strings, and
                  spaces are inserted between adjacent strings.</p><p>This example reflects the traditional usage of <elcode>xsl:text</elcode> to output
               constant text and <elcode>xsl:value-of</elcode> to output variable text. In XSLT 4.0,
               however, either instruction can be used for either purpose, and in the example above
               either instruction could be replaced by the other.</p></example><p>It is possible to construct text nodes whose string value is zero-length. A
               zero-length text node, when atomized, produces a zero-length string. However,
               zero-length text nodes are ignored when they appear in a sequence that is used to
               form the content of a node, as described in <specref ref="constructing-complex-content"/> and <specref ref="constructing-simple-content"/>.</p><div3 id="literal-text-nodes"><head>Literal Text Nodes</head><p>A <termref def="dt-sequence-constructor"/> can contain text nodes. Each text node
                  in a sequence constructor remaining after <termref def="dt-whitespace-text-node">whitespace text nodes</termref> have been stripped as specified in <specref ref="stylesheet-stripping"/> will construct a new text node with the same
                     <termref def="dt-string-value">string value</termref>. The resulting text node
                  is added to the result of the containing sequence constructor.</p><p>Text is processed at the tree level. Thus, markup of <code nobreak="false">&amp;lt;</code> in a
                  template will be represented in the stylesheet tree by a text node that includes
                  the character <code nobreak="false">&lt;</code>. This will create a text node in the <termref def="dt-result-tree">result tree</termref> that contains a <code nobreak="false">&lt;</code>
                  character, which will be represented by the markup <code nobreak="false">&amp;lt;</code> (or an
                  equivalent character reference) when the result tree is serialized as an XML
                  document, unless otherwise specified using <termref def="dt-character-map">character maps</termref> (see <specref ref="character-maps"/>) or
                     <code nobreak="false">disable-output-escaping</code> (see <specref ref="disable-output-escaping"/>).</p><p>A non-whitespace text node in the stylesheet that is not contained within an <elcode>xsl:text</elcode> or
               <elcode>xsl:value-of</elcode> instruction is equivalent to wrapping the text node in
               <elcode>xsl:text</elcode>. For example:</p><eg xml:space="preserve">&lt;xsl:if test="$debug"&gt;Here I am&lt;/xsl:if&gt;</eg><p>is equivalent to:</p><eg xml:space="preserve">&lt;xsl:if test="$debug"&gt;&lt;xsl:text&gt;Here I am&lt;/xsl:text&gt;&lt;/xsl:if&gt;</eg></div3><div3 id="xsl-text"><head>The <elcode>xsl:text</elcode> and <elcode>xsl:value-of</elcode> instructions</head><changes><change issue="323" PR="2251" date="2025-10-31">The rules for <elcode>xsl:text</elcode>
                  and <elcode>xsl:value-of</elcode> are integrated, allowing <elcode>xsl:text</elcode>
                  to be used to construct all text nodes, whether the content is fixed or variable.</change><change issue="2198" PR="2301" date="2025-11-19">The attribute <code nobreak="false">cdata</code> is added to <elcode>xsl:text</elcode>
                  and <elcode>xsl:value-of</elcode> to request serialization of a text node as a CDATA
                  section.</change></changes><e:element-syntax xmlns:e="http://www.w3.org/1999/XSL/Spec/ElementSyntax" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" name="text">
      <e:in-category name="instruction"/>
      <e:attribute name="select">
         <e:data-type name="expression"/>
      </e:attribute>
      <e:attribute name="separator">
         <e:attribute-value-template>
            <e:data-type name="string"/>
         </e:attribute-value-template>
      </e:attribute>
      <e:attribute name="cdata" default="'no'">
         <e:attribute-value-template>
            <e:data-type name="boolean"/>
         </e:attribute-value-template>
      </e:attribute>
      <e:attribute name="disable-output-escaping" deprecated="yes" default="'no'">
         <e:data-type name="boolean"/>
      </e:attribute>
      <e:model name="sequence-constructor"/>
      <e:allowed-parents>
         <e:parent-category name="sequence-constructor"/>
      </e:allowed-parents>
   </e:element-syntax><e:element-syntax xmlns:e="http://www.w3.org/1999/XSL/Spec/ElementSyntax" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" name="value-of">
      <e:in-category name="instruction"/>
      <e:attribute name="select">
         <e:data-type name="expression"/>
      </e:attribute>
      <e:attribute name="separator">
         <e:attribute-value-template>
            <e:data-type name="string"/>
         </e:attribute-value-template>
      </e:attribute>
      <e:attribute name="cdata" default="'no'">
         <e:attribute-value-template>
            <e:data-type name="boolean"/>
         </e:attribute-value-template>
      </e:attribute>
      <e:attribute name="disable-output-escaping" deprecated="yes" default="'no'">
         <e:data-type name="boolean"/>
      </e:attribute>
      <e:model name="sequence-constructor"/>
      <e:allowed-parents>
         <e:parent-category name="sequence-constructor"/>
      </e:allowed-parents>
   </e:element-syntax><p>The <elcode>xsl:text</elcode> and <elcode>xsl:value-of</elcode>element 
                  have identical content models. The only differences between them are:</p><olist><item><p>The <elcode>xsl:text</elcode> element is treated specially
                     during whitespace-stripping, as described in <specref ref="stylesheet-stripping"/>.
                     Specifically, whitespace text nodes that are children of <elcode>xsl:text</elcode>
                     are preserved, whereas whitespace text nodes that are children of <elcode>xsl:value-of</elcode>
                     are discarded.</p></item><item><p>Special rules apply to <elcode>xsl:value-of</elcode> 
                     when the instruction is processed
                     with <termref def="dt-xslt-10-behavior">XSLT 1.0 behavior</termref>.
                     Specifically, if no <code nobreak="false">separator</code> attribute is present, 
                     and if the <code nobreak="false">select</code> attribute is present, then all items in the 
                     <termref def="dt-atomization">atomized</termref> result sequence 
                     other than the first are ignored.</p></item></olist><p>The <elcode>xsl:text</elcode> or 
                  <elcode>xsl:value-of</elcode> instruction is evaluated to construct a new text
                  node; the result of the instruction is the newly constructed text node.</p><p>The string value of the new text node may be defined either by using the
                     <code nobreak="false">select</code> attribute, or by the 
                  <termref def="dt-sequence-constructor">sequence constructor</termref> 
                  (see <specref ref="sequence-constructors"/>)
                  that forms the content of the <elcode>xsl:text</elcode> or 
                  <elcode>xsl:value-of</elcode> element. 
                  These are mutually exclusive: if the <code nobreak="false">select</code>
                     attribute is present then the sequence constructor must be empty, and if the
                     sequence constructor is non-empty then the <code nobreak="false">select</code> attribute must
                     be absent. If the <code nobreak="false">select</code> attribute is absent and the sequence
                     constructor is empty, then the result of the instruction is a text node whose
                     string value is zero-length. The way in which the value is constructed
                  is specified in <specref ref="constructing-simple-content"/>.</p><p>
                  <error spec="XT" type="static" class="SE" code="0870"><p>It is a <termref def="dt-static-error">static error</termref> if the
                           <code nobreak="false">select</code> attribute of the <elcode>xsl:text</elcode> or 
                        <elcode>xsl:value-of</elcode>
                        element is present when the content of the element is non-empty.</p></error>
               </p><p>If the <code nobreak="false">separator</code> attribute is present, then the 
                  <termref def="dt-effective-value">effective value</termref> of this attribute is used to
                  separate adjacent items in the result sequence, as described in 
                  <specref ref="constructing-simple-content"/>. In the absence of this attribute, the
                  default separator is <char>U+0020</char> when the content is specified using the
                     <code nobreak="false">select</code> attribute, or a zero-length string when the content is
                  specified using a <termref def="dt-sequence-constructor">sequence
                     constructor</termref>.</p><p>If the element or one of its ancestors has an
                     <code nobreak="false">[xsl:]expand-text</code> attribute, and the nearest ancestor with such an
                  attribute has the value <code nobreak="false">yes</code>, then any unescaped curly brackets in the
                  value of the element indicate the presence of <termref def="dt-text-value-template">text value templates</termref>, which are expanded
                  as described in <specref ref="text-value-templates"/>.</p><p>In the absence of such an attribute, or if the
                  <termref def="dt-effective-value"/> is <code nobreak="false">no</code>, the content of the
                     <elcode>xsl:text</elcode> or <elcode>xsl:value-of</elcode>
                  instruction may comprise a single text node whose value forms the
                     <termref def="dt-string-value">string value</termref> of the constructed text node. An
                     <elcode>xsl:text</elcode> or <elcode>xsl:value-of</elcode> element 
                  may also be empty, in which case the result of
                  evaluating the instruction is a text node whose string value is the zero-length
                  string.</p><p>For the effect of the <code nobreak="false">cdata</code> attribute, see <specref ref="generating-cdata"/>.</p><p>For the effect of the <termref def="dt-deprecated">deprecated</termref>
                  <code nobreak="false">disable-output-escaping</code> attribute, see <specref ref="disable-output-escaping"/>
               </p><note><p>It is not always necessary to use the <elcode>xsl:text</elcode> 
                     or <elcode>xsl:value-of</elcode> instruction to
                     write text nodes to the <termref def="dt-result-tree">result tree</termref>.
                     Literal text can be written to the result tree by including it anywhere in a
                        <termref def="dt-sequence-constructor"/>. The principal reason for
                     using <elcode>xsl:text</elcode> is that it offers improved control over
                     whitespace handling.</p></note><note><p>Historically, <elcode>xsl:value-of</elcode> was used to construct
                  variable content, while <elcode>xsl:text</elcode> was used to copy fixed
                  text from the stylesheet to the result document. In 4.0, that distinction
                  is no longer relevant. Stylesheet authors should consider using 
                   <elcode>xsl:text</elcode> whenever there is a need to construct
                     text nodes, as the intent is more clearly expressed. 
                     The <elcode>xsl:value-of</elcode> instruction has often been misunderstood; 
                  it is a common mistake to use it where <elcode>xsl:sequence</elcode> or
                  <elcode>xsl:copy-of</elcode> is more appropriate.</p></note><example><head>Generating a List with Separators</head><p>The instruction:</p><eg xml:space="preserve" role="xslt-fragment">&lt;x&gt;&lt;xsl:text select="1 to 4" separator="|"/&gt;&lt;/x&gt;</eg><p>produces the output:</p><eg xml:space="preserve" role="xml">&lt;x&gt;1|2|3|4&lt;/x&gt;</eg></example><example><head>Generating Whitespace using <code nobreak="false">xsl:text</code></head><p>The instruction:</p><eg xml:space="preserve" role="xslt-fragment">&lt;a&gt;&lt;xsl:text&gt;  &lt;x/&gt;  &lt;/xsl:text&gt;&lt;/a&gt;</eg><p>produces the output:</p><eg xml:space="preserve" role="xml">&lt;a&gt;  &lt;x/&gt;  &lt;/a&gt;</eg><p>This illustrates that all whitespace text node children of <elcode>xsl:text</elcode> are preserved,
                  even if they have non-whitespace siblings.</p></example></div3><div3 id="generating-cdata"><head>Generating CDATA Sections</head><changes><change issue="2198" PR="2301" date="2025-11-19">The attribute <code nobreak="false">cdata</code> is added to <elcode>xsl:text</elcode>
                  and <elcode>xsl:value-of</elcode> to request serialization of a text node as a CDATA
                  section.</change></changes><p>The XDM data model (see <bibref ref="xpath-datamodel-40"/>) does not recognize CDATA sections as a special kind
               of node; CDATA is regarded simply as one way of serializing a text node. The elements
               <code nobreak="false">&lt;e&gt;x &amp;lt; y&lt;/e&gt;</code> and <code nobreak="false">&lt;e&gt;&lt;![CDATA[x &lt; y]]&gt;&lt;/e&gt;</code> have
               exactly the same representation in XDM: an element node with a text node child, the string value
               of the text node being <code nobreak="false">"x &lt; y"</code>.</p><p>It is however possible to request that a text node should be serialized as a CDATA section. If all elements
               with a given name are to be serialized as CDATA, this can be achieved using the serialization parameter
               <code nobreak="false">cdata-section-elements</code> (available, for example, as an attribute on <elcode>xsl:output</elcode>
               and <elcode>xsl:result-document</elcode>). If CDATA serialization is to be used more selectively than this, 
               it can also be requested using the <code nobreak="false">cdata</code> attribute on the <elcode>xsl:text</elcode> and
               <elcode>xsl:value-of</elcode> instructions.</p><p>The <code nobreak="false">cdata</code> attribute, if its effective value is <code nobreak="false">yes</code>,
               is a request to the processor to serialize the text node as a CDATA section.
               For example, the text node produced by the instruction <code nobreak="false">&lt;xsl:text cdata="yes"&gt;&gt;&gt;&gt;&lt;/xsl:text&gt;</code>
               might be serialized as <code nobreak="false">&lt;![CDATA[&gt;&gt;&gt;]]&gt;</code>. Honoring this request
               requires close coupling between the processor and the serializer, and
               processors <rfc2119>may</rfc2119> therefore ignore the request. In particular, it is
               likely that a processor will ignore the request unless the result of the transformation
               is passed directly to the serializer, bypassing the construction of an in-memory
               result tree.</p><p>It is <termref def="dt-implementation-defined"/> whether, and under what circumstances, the
               <code nobreak="false">cdata</code> attribute of the <elcode>xsl:text</elcode> and
               <elcode>xsl:value-of</elcode> instructions has any effect on the serialized output.</p><note><p>A processor delivering output in the form of an in-memory tree using a data model
               (such as the DOM model) that includes CDATA nodes <rfc2119>may</rfc2119> take account of
               the <code nobreak="false">cdata</code> attribute to generate such nodes.</p></note><p>If the <code nobreak="false">cdata</code> attribute is present, regardless of its <termref def="dt-effective-value"/>,
               then the <code nobreak="false">disable-output-escaping</code> attribute is ignored.</p><note><p>The attribute is likely to have effect only in the following circumstances:</p><ulist><item><p>The output of the transformation is sent directly to a serializer (or to
                           another destination, such as a DOM, that recognizes CDATA).</p></item><item><p>The serialization method is <code nobreak="false">xml</code> or <code nobreak="false">xhtml</code> (perhaps
                     invoked indirectly via the <code nobreak="false">html</code> or <code nobreak="false">adaptive</code> output methods).</p></item><item><p>The text node is not bound to a variable.</p></item><item><p>The parent element of the text node is not listed in the <code nobreak="false">cdata-section-elements</code>
                            serialization parameter (in this case every text node child of the element
                            should be serialized as a CDATA section, regardless of any <code nobreak="false">cdata</code>
                            attributes).</p></item><item><p>The text node is not used as input to the process of constructing
                        an attribute, comment, processing instruction, or another text node: 
                        see <specref ref="constructing-simple-content"/>.</p></item><item><p>The text node is not used as input to the process of constructing
                        a <termref def="dt-temporary-tree"/>.</p></item></ulist></note><note><p>The <code nobreak="false">cdata</code> attribute is an <termref def="dt-attribute-value-template"/>, so the
               value can be made conditional on the actual content of the text. For example,
               the instruction:</p><eg xml:space="preserve">&lt;xsl:value-of select="$s" cdata="{matches($s, '[&amp;lt;&amp;amp;]')}"/&gt;</eg><p>will request serialization as a CDATA section if the text contains either of the
               characters <code nobreak="false">&lt;</code> or <code nobreak="false">&amp;</code>.</p></note><note><p>Whether or not the output of an <elcode>xsl:text</elcode> or <elcode>xsl:value-of</elcode>
               instruction is “sent directly to a serializer” is essentially implementation-defined.
               There may be cases that vary between processors, for example an instruction that returns
               the result of a <termref def="dt-stylesheet-function"/>.</p></note><p>The effect of setting <code nobreak="false">cdata="yes"</code> (in cases where it has any effect at all)
                  is as if the text node were wrapped in a containing element
                  whose name is listed in the <code nobreak="false">cdata-section-elements</code> parameter,
                  with the start and end tags of that element then being stripped from the serialized output.</p><p>This implies:</p><ulist><item><p>If the text node includes the character sequence <code nobreak="false">]]&gt;</code>, then the CDATA section
                  must be closed, and a new CDATA section opened, after the <code nobreak="false">]]</code>.</p></item><item><p>Similarly, if the text node includes a codepoint that cannot be represented
                        using the selected encoding, then the CDATA section
                  must be closed, and a new CDATA section opened, after the escaped representation of that codepoint.</p></item><item><p>Unicode normalization does not operate across the boundary between a CDATA
                        and a non-CDATA text node.</p></item><item><p>Character mapping (as defined by the <code nobreak="false">use-character-maps</code> parameter)
                        does not take place within a CDATA text node.</p></item><item><p>Special characters such as <code nobreak="false">&amp;</code> and <code nobreak="false">&lt;</code>
                        in a CDATA text node are not escaped.</p></item></ulist></div3></div2><div2 id="creating-document-nodes"><head>Creating Document Nodes</head><e:element-syntax xmlns:e="http://www.w3.org/1999/XSL/Spec/ElementSyntax" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" name="document">
      <e:in-category name="instruction"/>
      <e:attribute name="validation">
         <e:constant value="strict"/>
         <e:constant value="lax"/>
         <e:constant value="preserve"/>
         <e:constant value="strip"/>
      </e:attribute>
      <e:attribute name="type">
         <e:data-type name="eqname"/>
      </e:attribute>
      <e:model name="sequence-constructor"/>
      <e:allowed-parents>
         <e:parent-category name="sequence-constructor"/>
      </e:allowed-parents>
   </e:element-syntax><p>The <elcode>xsl:document</elcode> instruction is used to create a new document node.
               The content of the <elcode>xsl:document</elcode> element is a <termref def="dt-sequence-constructor">sequence constructor</termref> for the children of
               the new document node. A document node is created, and the sequence obtained by
               evaluating the sequence constructor is used to construct the content of the document,
               as described in <specref ref="constructing-complex-content"/>. </p><p>Except in error situations, the result of evaluating the
                  <elcode>xsl:document</elcode> instruction is a single node, the newly constructed
               document node.</p><note><p>The new document is not serialized. To construct a document that is to form a
                  final result rather than an intermediate result, use the
                     <elcode>xsl:result-document</elcode> instruction described in <specref ref="creating-result-trees"/>.</p></note><p>The optional attributes <code nobreak="false">type</code> and <code nobreak="false">validation</code> may be used on
               the <elcode>xsl:document</elcode> instruction to validate the contents of the new
               document, and to determine the <termref def="dt-type-annotation"/> that elements and
               attributes within the <termref def="dt-result-tree">result tree</termref> will carry.
               The permitted values and their semantics are described in <specref ref="validating-document-nodes"/>.</p><p>The base URI of the new document node is taken from the base URI of the
                  <elcode>xsl:document</elcode> instruction.</p><p>The <code nobreak="false">document-uri</code> and <code nobreak="false">unparsed-entities</code> properties of the
               new document node are set to empty.</p><example><head>Checking Uniqueness Constraints in a Temporary Tree</head><p>The following example creates a temporary tree held in a variable. The use of an
                  enclosed <elcode>xsl:document</elcode> instruction ensures that uniqueness
                  constraints defined in the schema for the relevant elements are checked.</p><eg xml:space="preserve" role="xslt-declaration">&lt;xsl:variable name="tree" as="document-node()"&gt;
  &lt;xsl:document validation="strict"&gt;
    &lt;xsl:apply-templates/&gt;
  &lt;/xsl:document&gt;
&lt;/xsl:variable&gt;</eg></example></div2><div2 id="creating-processing-instructions"><head>Creating Processing Instructions</head><e:element-syntax xmlns:e="http://www.w3.org/1999/XSL/Spec/ElementSyntax" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" name="processing-instruction">
      <e:in-category name="instruction"/>
      <e:attribute name="name" required="yes">
         <e:attribute-value-template>
            <e:data-type name="ncname"/>
         </e:attribute-value-template>
      </e:attribute>
      <e:attribute name="select">
         <e:data-type name="expression"/>
      </e:attribute>
      <e:model name="sequence-constructor"/>
      <e:allowed-parents>
         <e:parent-category name="sequence-constructor"/>
      </e:allowed-parents>
   </e:element-syntax><p>The <elcode>xsl:processing-instruction</elcode> element is evaluated to create a
               processing instruction node.</p><p>The <elcode>xsl:processing-instruction</elcode> element has a
                  <rfc2119>required</rfc2119>
               <code nobreak="false">name</code> attribute that specifies the name of the processing instruction
               node. The value of the <code nobreak="false">name</code> attribute is interpreted as an <termref def="dt-attribute-value-template">attribute value template</termref>.</p><p>The string value of the new processing instruction node may be defined either by
               using the <code nobreak="false">select</code> attribute, or by the <termref def="dt-sequence-constructor">sequence constructor</termref> that forms the
               content of the <elcode>xsl:processing-instruction</elcode> element. These are mutually exclusive: if the <code nobreak="false">select</code>
                  attribute is present then the sequence constructor must be empty, and if the
                  sequence constructor is non-empty then the <code nobreak="false">select</code> attribute must be
                  absent. If the <code nobreak="false">select</code> attribute is absent and the sequence
                  constructor is empty, then the string value of the new
               processing instruction node will be a zero-length string. The way in which the value
               is constructed is specified in <specref ref="constructing-simple-content"/>.</p><p>
               <error spec="XT" type="static" class="SE" code="0880"><p>It is a <termref def="dt-static-error">static error</termref> if the
                        <code nobreak="false">select</code> attribute of the
                        <elcode>xsl:processing-instruction</elcode> element is present unless the
                     element has empty content.</p></error>
            </p><p>Except in error situations, the result of evaluating the
                  <elcode>xsl:processing-instruction</elcode> instruction is a single node, the
               newly constructed processing instruction node.</p><example><head>Creating a Processing Instruction</head><p>This instruction:</p><eg xml:space="preserve" role="xslt-instruction">&lt;xsl:processing-instruction name="xml-stylesheet"
  select="('href=&amp;quot;book.css&amp;quot;', 'type=&amp;quot;text/css&amp;quot;')"/&gt;</eg><p>creates the processing instruction</p><eg xml:space="preserve" role="non-xml">&lt;?xml-stylesheet href="book.css" type="text/css"?&gt;</eg><p>Note that the <code nobreak="false">xml-stylesheet</code> processing instruction contains
                     <emph>pseudo-attributes</emph> in the form <code nobreak="false">name="value"</code>. Although
                  these have the same textual form as attributes in an element start tag, they are
                  not represented as XDM attribute nodes, and cannot therefore be constructed using
                     <elcode>xsl:attribute</elcode> instructions.</p></example><p>
               <error spec="XT" type="dynamic" class="DE" code="0890"><p>It is a <termref def="dt-dynamic-error"> dynamic error</termref> if the <termref def="dt-effective-value">effective value</termref> of the <code nobreak="false">name</code>
                     attribute <error.extra>of the <elcode>xsl:processing-instruction</elcode>
                        instruction</error.extra> is not both an <xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="Names" ref="NT-NCName" xlink:type="simple">NCName</xnt> and a <xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="XML" ref="PITarget" xlink:type="simple">PITarget</xnt>.</p></error>
            </p><note><p>Because these rules disallow the name <code nobreak="false">xml</code>, the
                     <elcode>xsl:processing-instruction</elcode> cannot be used to output an XML
                  declaration. The <elcode>xsl:output</elcode> declaration should be used to control
                  this instead (see <specref ref="serialization"/>).</p></note><p>If the result of evaluating the content of the
                  <elcode>xsl:processing-instruction</elcode> contains the string
               <code nobreak="false">?&gt;</code>, this string is modified by inserting a space between the
                  <code nobreak="false">?</code> and <code nobreak="false">&gt;</code> characters.</p><p>The base URI of the new processing instruction is copied from the base URI of the
                  <elcode>xsl:processing-instruction</elcode> element in the stylesheet. (Note,
               however, that this is only relevant when creating a parentless processing
               instruction. When the new processing instruction is copied to form a child of an
               element or document node, the base URI of the new copy is taken from that of its new
               parent.)</p></div2><div2 id="creating-namespace-nodes"><head>Creating Namespace Nodes</head><e:element-syntax xmlns:e="http://www.w3.org/1999/XSL/Spec/ElementSyntax" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" name="namespace">
      <e:in-category name="instruction"/>
      <e:attribute name="name" required="yes">
         <e:attribute-value-template>
            <e:data-type name="ncname"/>
         </e:attribute-value-template>
      </e:attribute>
      <e:attribute name="select">
         <e:data-type name="expression"/>
      </e:attribute>
      <e:model name="sequence-constructor"/>
      <e:allowed-parents>
         <e:parent-category name="sequence-constructor"/>
      </e:allowed-parents>
   </e:element-syntax><p>The <elcode>xsl:namespace</elcode> element is evaluated to create a namespace node.
               Except in error situations, the result of evaluating the
                  <elcode>xsl:namespace</elcode> instruction is a single node, the newly constructed
               namespace node.</p><p>The <elcode>xsl:namespace</elcode> element has a <rfc2119>required</rfc2119>
               <code nobreak="false">name</code> attribute that specifies the name of the namespace node (that is,
               the namespace prefix). The value of the <code nobreak="false">name</code> attribute is interpreted as
               an <termref def="dt-attribute-value-template">attribute value template</termref>. If
               the <termref def="dt-effective-value">effective value</termref> of the
                  <code nobreak="false">name</code> attribute is a zero-length string, a namespace node is added for
               the default namespace.</p><p>The string value of the new namespace node (that is, the namespace URI) may be
               defined either by using the <code nobreak="false">select</code> attribute, or by the <termref def="dt-sequence-constructor">sequence constructor</termref> that forms the
               content of the <elcode>xsl:namespace</elcode> element. These are mutually exclusive: if the <code nobreak="false">select</code> attribute is present
                  then the sequence constructor must be empty, and if the sequence constructor is
                  non-empty then the <code nobreak="false">select</code> attribute must be absent. Since
               the string value of a namespace node cannot be a zero-length string, either a <code nobreak="false">select</code> attribute or a non-empty sequence
                  constructor <rfc2119>must</rfc2119> be present. The way in which the
               value is constructed is specified in <specref ref="constructing-simple-content"/>.</p><p>
               <error spec="XT" type="dynamic" class="DE" code="0905"><p>It is a <termref def="dt-dynamic-error"> dynamic error</termref> if the string value of
                     the new namespace node is not valid in the lexical space of the datatype
                        <code nobreak="false">xs:anyURI</code>, or if it is the string
                        <code nobreak="false">http://www.w3.org/2000/xmlns/</code>.</p></error>
            </p><p>
               <error spec="XT" type="static" class="SE" code="0910"><p>It is a <termref def="dt-static-error">static error</termref> if the
                        <code nobreak="false">select</code> attribute of the <elcode>xsl:namespace</elcode> element
                     is present when the element has content other than one or more
                        <elcode>xsl:fallback</elcode> instructions, or if the <code nobreak="false">select</code>
                     attribute is absent when the element has empty content.</p></error>
            </p><p>Note the restrictions described in <specref ref="constructing-complex-content"/> for
               the position of a namespace node relative to other nodes in the node sequence
               returned by a sequence constructor.</p><example><head>Constructing a QName-Valued Attribute</head><p>This literal result element:</p><eg xml:space="preserve" role="non-xml">&lt;data xsi:type="xs:integer" 
             xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"&gt;
  &lt;xsl:namespace name="xs" 
                 select="'http://www.w3.org/2001/XMLSchema'"/&gt;
  &lt;xsl:text&gt;42&lt;/xsl:text&gt;
&lt;/data&gt;</eg><p>would typically cause the output document to contain the element:</p><eg xml:space="preserve" role="non-xml">&lt;data xsi:type="xs:integer"
     xmlns:xs="http://www.w3.org/2001/XMLSchema"
     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"&gt;42&lt;/data&gt;</eg><p>In this case, the element is constructed using a literal result element, and the
                  namespace <code nobreak="false">xmlns:xs="http://www.w3.org/2001/XMLSchema"</code> could therefore
                  have been added to the <termref def="dt-result-tree">result tree</termref> simply
                  by declaring it as one of the in-scope namespaces in the stylesheet. In practice,
                  the <elcode>xsl:namespace</elcode> instruction is more likely to be useful in
                  situations where the element is constructed using an <elcode>xsl:element</elcode>
                  instruction, which does not copy all the in-scope namespaces from the
                  stylesheet.</p></example><p>
               <error spec="XT" type="dynamic" class="DE" code="0920"><p>It is a <termref def="dt-dynamic-error"> dynamic error</termref> if the <termref def="dt-effective-value">effective value</termref> of the <code nobreak="false">name</code>
                     attribute <error.extra>of the <elcode>xsl:namespace</elcode>
                        instruction</error.extra> is neither a zero-length string nor an <xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="Names" ref="NT-NCName" xlink:type="simple">NCName</xnt>, or if it is <code nobreak="false">xmlns</code>.
                  </p></error>
            </p><p>
               <error spec="XT" type="dynamic" class="DE" code="0925"><p>It is a <termref def="dt-dynamic-error"> dynamic error</termref> if the
                        <elcode>xsl:namespace</elcode> instruction generates a namespace node whose
                     name is <code nobreak="false">xml</code> and whose string value is not
                        <code nobreak="false">http://www.w3.org/XML/1998/namespace</code>, or a namespace node whose
                     string value is <code nobreak="false">http://www.w3.org/XML/1998/namespace</code> and whose
                     name is not <code nobreak="false">xml</code>.</p></error>
            </p><p>
               <error spec="XT" type="dynamic" class="DE" code="0930"><p>It is a <termref def="dt-dynamic-error"> dynamic error</termref> if evaluating the
                        <code nobreak="false">select</code> attribute or the contained <termref def="dt-sequence-constructor"/> of an <elcode>xsl:namespace</elcode>
                     instruction results in a zero-length string. </p></error>
            </p><p>For details of other error conditions that may arise, see <specref ref="sequence-constructors"/>.</p><note><p>It is rarely necessary to use <elcode>xsl:namespace</elcode> to create a namespace
                  node in the <termref def="dt-result-tree">result tree</termref>; in most
                  circumstances, the required namespace nodes will be created automatically, as a
                  side-effect of writing elements or attributes that use the namespace. An example
                  where <elcode>xsl:namespace</elcode> is needed is a situation where the required
                  namespace is used only within attribute values in the result document, not in
                  element or attribute names; especially where the required namespace prefix or
                  namespace URI is computed at run-time and is not present in either the source
                  document or the stylesheet.</p><p>Adding a namespace node to the <termref def="dt-result-tree">result tree</termref>
                  will never change the <termref def="dt-expanded-qname">expanded QName</termref> of
                  any element or attribute node in the result tree: that is, it will never change
                  the namespace URI of an element or attribute. It might, however, constrain the
                  choice of prefixes when namespace fixup is performed.</p><p>Namespace prefixes for element and attribute names are initially established by
                  the rules of the instruction that creates the element or attribute node, and in
                  the event of conflicts, they may be changed by the namespace fixup process
                  described in <specref ref="namespace-fixup"/>. The fixup process ensures that an
                  element has in-scope namespace nodes for the namespace URIs used in the element
                  name and in its attribute names, and the serializer will typically use these
                  namespace nodes to determine the prefix to use in the serialized output. The fixup
                  process cannot generate namespace nodes that are inconsistent with those already
                  present in the tree. This means that it is not possible for the processor to
                  decide the prefix to use for an element or for any of its attributes until all the
                  namespace nodes for the element have been added.</p><p>If a namespace prefix is mapped to a particular namespace URI using the
                     <elcode>xsl:namespace</elcode> instruction, or by using
                     <elcode>xsl:copy</elcode> or <elcode>xsl:copy-of</elcode> to copy a namespace
                  node, this prevents the namespace fixup process (and hence the serializer) from
                  using the same prefix for a different namespace URI on the same element.</p></note><example><head>Conflicting Namespace Prefixes</head><p>Given the instruction:</p><eg xml:space="preserve" role="xslt-instruction">&lt;xsl:element name="p:item" 
                 xmlns:p="http://www.example.com/p"&gt;
  &lt;xsl:namespace name="p"&gt;http://www.example.com/q&lt;/xsl:namespace&gt;
&lt;/xsl:element&gt;</eg><p>a possible serialization of the <termref def="dt-result-tree">result
                     tree</termref> is:</p><eg xml:space="preserve" role="xml">&lt;ns0:item 
    xmlns:ns0="http://www.example.com/p" 
    xmlns:p="http://www.example.com/q"/&gt;</eg><p>The processor must invent a namespace prefix for the URI <code nobreak="false">p.uri</code>; it
                  cannot use the prefix <code nobreak="false">p</code> because that prefix has been explicitly
                  associated with a different URI.</p></example><note><p>The <elcode>xsl:namespace</elcode> instruction cannot be used to generate a
                     <term>namespace undeclaration</term> of the form <code nobreak="false">xmlns=""</code> (nor the
                  new forms of namespace undeclaration permitted in <bibref ref="xml-names11"/>).
                  Namespace undeclarations are generated automatically by the serializer if
                     <code nobreak="false">undeclare-prefixes="yes"</code> is specified on
                     <elcode>xsl:output</elcode>, whenever a parent element has a namespace node for
                  the default namespace prefix, and a child element has no namespace node for that
                  prefix.</p></note></div2><div2 id="creating-comments"><head>Creating Comments</head><e:element-syntax xmlns:e="http://www.w3.org/1999/XSL/Spec/ElementSyntax" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" name="comment">
      <e:in-category name="instruction"/>
      <e:attribute name="select">
         <e:data-type name="expression"/>
      </e:attribute>
      <e:model name="sequence-constructor"/>
      <e:allowed-parents>
         <e:parent-category name="sequence-constructor"/>
      </e:allowed-parents>
   </e:element-syntax><p>The <elcode>xsl:comment</elcode> element is evaluated to construct a new comment
               node. Except in error cases, the result of evaluating the
                  <elcode>xsl:comment</elcode> instruction is a single node, the newly constructed
               comment node.</p><p>The string value of the new comment node may be defined either by using the
                  <code nobreak="false">select</code> attribute, or by the <termref def="dt-sequence-constructor">sequence constructor</termref> that forms the content of the
                  <elcode>xsl:comment</elcode> element. These are mutually
                  exclusive: if the <code nobreak="false">select</code> attribute is present then the sequence
                  constructor must be empty, and if the sequence constructor is non-empty then the
                     <code nobreak="false">select</code> attribute must be absent. If the <code nobreak="false">select</code>
                  attribute is absent and the sequence constructor is empty, then the
               string value of the new comment node will be a zero-length string. The way in which
               the value is constructed is specified in <specref ref="constructing-simple-content"/>.</p><p>
               <error spec="XT" type="static" class="SE" code="0940"><p>It is a <termref def="dt-static-error">static error</termref> if the
                        <code nobreak="false">select</code> attribute of the <elcode>xsl:comment</elcode> element is
                     present unless the element has empty content.</p></error>
            </p><example><head>Generating a Comment Node</head><p>For example, this</p><eg xml:space="preserve" role="xslt-instruction">&lt;xsl:comment&gt;This file is automatically generated. Do not edit!&lt;/xsl:comment&gt;</eg><p>would create the comment</p><eg xml:space="preserve" role="non-xml">&lt;!--This file is automatically generated. Do not edit!--&gt;</eg></example><p>In the generated comment node, the processor <rfc2119>must</rfc2119> insert a space
               after any occurrence of <code nobreak="false">x2D</code> (hyphen) that is followed by another occurrence of <code nobreak="false">x2D</code> (hyphen) or
               that ends the comment.</p></div2><div2 id="copying"><head>Copying Nodes</head><div3 id="shallow-copy"><head>Shallow Copy</head><e:element-syntax xmlns:e="http://www.w3.org/1999/XSL/Spec/ElementSyntax" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" name="copy">
      <e:in-category name="instruction"/>
      <e:attribute name="select">
         <e:data-type name="expression"/>
      </e:attribute>
      <e:attribute name="copy-namespaces" default="'yes'">
         <e:data-type name="boolean"/>
      </e:attribute>
      <e:attribute name="inherit-namespaces" default="'yes'">
         <e:data-type name="boolean"/>
      </e:attribute>
      <e:attribute name="use-attribute-sets" default="''">
         <e:data-type name="eqnames"/>
      </e:attribute>
      <e:attribute name="type">
         <e:data-type name="eqname"/>
      </e:attribute>
      <e:attribute name="validation">
         <e:constant value="strict"/>
         <e:constant value="lax"/>
         <e:constant value="preserve"/>
         <e:constant value="strip"/>
      </e:attribute>
      <e:model name="sequence-constructor"/>
      <e:allowed-parents>
         <e:parent-category name="sequence-constructor"/>
      </e:allowed-parents>
   </e:element-syntax><p>The <elcode>xsl:copy</elcode> instruction provides a way of copying a selected item. The selected item is the item selected by
                     evaluating the expression in the <code nobreak="false">select</code> attribute if present, or
                     the <termref def="dt-context-item">context item</termref> otherwise.
                  If the selected item is a node, evaluating the <elcode>xsl:copy</elcode>
                  instruction constructs a copy of the selected node, and the result of the
                     <elcode>xsl:copy</elcode> instruction is this newly constructed node. By
                  default, the namespace nodes of the context node are automatically copied as well,
                  but the attributes and children of the node are not automatically copied.</p><p>
                  <error spec="XT" type="type" class="TE" code="0945"><p>It is a <termref def="dt-type-error">type error</termref> to use the
                           <elcode>xsl:copy</elcode> instruction with no <code nobreak="false">select</code>
                        attribute when the context item is absent. </p></error>
               </p><p>If the <code nobreak="false">select</code> expression returns the empty sequence,
                  the <elcode>xsl:copy</elcode> instruction returns the empty sequence, and the
                  contained <termref def="dt-sequence-constructor"/> is not evaluated.</p><p><error spec="XT" type="type" class="TE" code="3180"><p>It is a <termref def="dt-type-error">type error</termref> if the result of
                        evaluating the <code nobreak="false">select</code> expression <error.extra>of the
                              <elcode>xsl:copy</elcode> element</error.extra> is a sequence of more
                        than one item.</p></error></p><p>When the selected item is an atomic item
                     or function item, the
                     <elcode>xsl:copy</elcode> instruction returns this value. The <termref def="dt-sequence-constructor">sequence constructor</termref> is not evaluated.
                     </p><p>When the selected item is an attribute node,
                  text node, comment node, processing instruction node, or namespace node, the
                     <elcode>xsl:copy</elcode> instruction returns a new node that is a copy of the
                  context node. The new node will have the same node kind, name, and string value as
                  the context node. In the case of an attribute node, it will also have the same
                  values for the <code nobreak="false">is-id</code> and <code nobreak="false">is-idrefs</code> properties. The
                     <termref def="dt-sequence-constructor"/> is not evaluated. </p><p>When the selected item is a document node or
                  element node, the <elcode>xsl:copy</elcode> instruction returns a new node that
                  has the same node kind and name as the selected
                  node. The content of the new node is formed by evaluating the <termref def="dt-sequence-constructor">sequence constructor</termref> contained in the
                     <elcode>xsl:copy</elcode> instruction. If the
                        <code nobreak="false">select</code> attribute is present then the sequence constructor is
                     evaluated with the selected item as the <termref def="dt-singleton-focus">singleton focus</termref>; otherwise it is evaluated using the context of
                     the <elcode>xsl:copy</elcode> instruction unchanged. The sequence
                  obtained by evaluating this sequence constructor is used (after prepending any
                  attribute nodes or namespace nodes as described in the following paragraphs) to
                  construct the content of the document or element node, as described in <specref ref="constructing-complex-content"/>.</p><p>When the selected item is a document node, the
                     <code nobreak="false">unparsed-entities</code> property of the existing document node is copied
                  to the new document node.</p><p>When the selected item is an element or attribute node,
                  the values of the <code nobreak="false">is-id</code>, <code nobreak="false">is-idrefs</code>, and
                     <code nobreak="false">nilled</code> properties of the new element or attribute depend on the
                  values of the <code nobreak="false">validation</code> and <code nobreak="false">type</code> attributes, as defined
                  in <specref ref="validation"/>.</p><p>The <elcode>xsl:copy</elcode> instruction has an optional
                     <code nobreak="false">use-attribute-sets</code> attribute, whose value is a
                  whitespace-separated list of QNames that identify
                     <elcode>xsl:attribute-set</elcode> declarations. This attribute is used only
                  when copying element nodes. This list is expanded as described in <specref ref="attribute-sets"/> to produce a sequence of attribute nodes. This sequence
                  is prepended to the sequence produced as a result of evaluating the <termref def="dt-sequence-constructor">sequence constructor</termref>.</p><p>The <elcode>xsl:copy</elcode> instruction has an optional
                     <code nobreak="false">copy-namespaces</code> attribute, with the value <code nobreak="false">yes</code> or
                     <code nobreak="false">no</code>. The default value is <code nobreak="false">yes</code>. The attribute is used
                  only when copying element nodes. If the value is set to <code nobreak="false">yes</code>, or is
                  omitted, then all the namespace nodes of the source element are copied as
                  namespace nodes for the result element. These copied namespace nodes are prepended
                  to the sequence produced as a result of evaluating the <termref def="dt-sequence-constructor">sequence constructor</termref> (it is immaterial
                  whether they come before or after any attribute nodes produced by expanding the
                     <code nobreak="false">use-attribute-sets</code> attribute). If the value is set to
                     <code nobreak="false">no</code>, then the namespace nodes are not copied. However, namespace
                  nodes will still be added to the result element as <rfc2119>required</rfc2119> by
                  the namespace fixup process: see <specref ref="namespace-fixup"/>.</p><p>The <elcode>xsl:copy</elcode> instruction has an optional
                     <code nobreak="false">inherit-namespaces</code> attribute, with the value <code nobreak="false">yes</code> or
                     <code nobreak="false">no</code>. The default value is <code nobreak="false">yes</code>. The attribute is used
                  only when copying element nodes. If the value is set to <code nobreak="false">yes</code>, or is
                  omitted, then the namespace nodes created for the newly constructed element
                  (whether these were copied from those of the source node, or generated as a result
                  of namespace fixup) are copied to the children and descendants of the newly
                  constructed element, as described in <specref ref="constructing-complex-content"/>. If the value is set to <code nobreak="false">no</code>, then these namespace nodes are not
                  automatically copied to the children. This may result in namespace undeclarations
                  (such as <code nobreak="false">xmlns=""</code> or, in the case of XML Namespaces 1.1,
                     <code nobreak="false">xmlns:p=""</code>) appearing on the child elements when a <termref def="dt-final-result-tree">final result tree</termref> is serialized.</p><p>
                  <error spec="XT" type="type" class="TE" code="0950"><p>It is a <termref def="dt-type-error">type error</termref> to use the
                           <elcode>xsl:copy</elcode> or <elcode>xsl:copy-of</elcode> instruction to
                        copy a node that has namespace-sensitive content if the
                           <code nobreak="false">copy-namespaces</code> attribute has the value <code nobreak="false">no</code> and
                        its explicit or implicit <code nobreak="false">validation</code> attribute has the value
                           <code nobreak="false">preserve</code>. It is also a type error if either of these
                        instructions (with <code nobreak="false">validation="preserve"</code>) is used to copy an
                        attribute having namespace-sensitive content, unless the parent element is
                        also copied. A node has namespace-sensitive content if its typed value
                        contains an item of type <code nobreak="false">xs:QName</code> or <code nobreak="false">xs:NOTATION</code>
                        or a type derived therefrom. The reason this is an error is because the
                        validity of the content depends on the namespace context being
                        preserved.</p></error>
               </p><note><p>When attribute nodes are copied, whether with <elcode>xsl:copy</elcode> or with
                        <elcode>xsl:copy-of</elcode>, the processor does not automatically copy any
                     associated namespace information. The namespace used in the attribute name
                     itself will be declared by virtue of the namespace fixup process (see <specref ref="namespace-fixup"/>) when the attribute is added to an element in the
                        <termref def="dt-result-tree">result tree</termref>, but if namespace
                     prefixes are used in the content of the attribute (for example, if the value of
                     the attribute is an XPath expression) then it is the responsibility of the
                     stylesheet author to ensure that suitable namespace nodes are added to the
                        <termref def="dt-result-tree">result tree</termref>. This can be achieved by
                     copying the namespace nodes using <elcode>xsl:copy</elcode>, or by generating
                     them using <elcode>xsl:namespace</elcode>.</p></note><p>The optional attributes <code nobreak="false">type</code> and <code nobreak="false">validation</code> may be used
                  on the <elcode>xsl:copy</elcode> instruction to validate the contents of an
                  element, attribute or document node against a type definition, element
                  declaration, or attribute declaration in a schema, and thus to determine the
                     <termref def="dt-type-annotation"/> that the new copy of an element or
                  attribute node will carry. These attributes are ignored when copying an item that
                  is not an element, attribute or document node. When the node being copied is an
                  element or document node, these attributes also affect the type annotation carried
                  by any elements and attributes that have the copied element or document node as an
                  ancestor. These two attributes are both optional, and if one is specified then the
                  other <rfc2119>must</rfc2119> be omitted. The permitted values of these attributes
                  and their semantics are described in <specref ref="validation"/>.</p><note><p>The final <termref def="dt-type-annotation"/> of the node in the <termref def="dt-result-tree">result tree</termref> also depends on the
                        <code nobreak="false">type</code> and <code nobreak="false">validation</code> attributes of the instructions
                     used to create the ancestors of the node.</p></note><p>When a node is copied, its base URI is copied, except
                  when the result of the <elcode>xsl:copy</elcode> instruction is an element node
                  having an <code nobreak="false">xml:base</code> attribute, in which case the base URI of the new
                  node is taken as the value of its <code nobreak="false">xml:base</code> attribute, resolved if it
                  is relative against the base URI of the <elcode>xsl:copy</elcode> instruction. </p><p>When an <code nobreak="false">xml:id</code> attribute is copied, using either the
                     <elcode>xsl:copy</elcode> or <elcode>xsl:copy-of</elcode> instruction, it is
                     <termref def="dt-implementation-defined"/> whether the value of the attribute
                  is subjected to attribute value normalization (that is, effectively applying the
                     <xfunction>normalize-space</xfunction> function).</p><note><p>In most cases the value will already have been subjected to attribute value
                     normalization on the source tree, but if this processing has not been performed
                     on the source tree, it is not an error for it to be performed on the result
                     tree.</p></note><imp-def-feature id="idf-feature-xmlid">If an <code nobreak="false">xml:id</code> attribute that has
                  not been subjected to attribute value normalization is copied from a source tree
                  to a result tree, it is implementation-defined whether attribute value
                  normalization will be applied during the copy process.</imp-def-feature></div3><div3 id="copy-of"><head>Deep Copy</head><e:element-syntax xmlns:e="http://www.w3.org/1999/XSL/Spec/ElementSyntax" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" name="copy-of">
      <e:in-category name="instruction"/>
      <e:attribute name="select" required="yes">
         <e:data-type name="expression"/>
      </e:attribute>
      <e:attribute name="copy-accumulators" default="'no'">
         <e:data-type name="boolean"/>
      </e:attribute>
      <e:attribute name="copy-namespaces" default="'yes'">
         <e:data-type name="boolean"/>
      </e:attribute>
      <e:attribute name="type">
         <e:data-type name="eqname"/>
      </e:attribute>
      <e:attribute name="validation">
         <e:constant value="strict"/>
         <e:constant value="lax"/>
         <e:constant value="preserve"/>
         <e:constant value="strip"/>
      </e:attribute>
      <e:empty/>
      <e:allowed-parents>
         <e:parent-category name="sequence-constructor"/>
      </e:allowed-parents>
   </e:element-syntax><p>The <elcode>xsl:copy-of</elcode> instruction can be used to construct a copy of a
                  sequence of nodes, atomic items, and/or function
                     items with each new node containing copies of all the children,
                  attributes, and (by default) namespaces of the original node, recursively. The
                  result of evaluating the instruction is a sequence of items corresponding
                  one-to-one with the supplied sequence, and retaining its order.</p><p>The <rfc2119>required</rfc2119>
                  <code nobreak="false">select</code> attribute contains an <termref def="dt-expression">expression</termref>, whose value may be any sequence of nodes, atomic items,
                     and/or function items. The items in this
                  sequence are processed as follows:</p><ulist><item><p>If the item is an element node, a new element is constructed and appended to
                        the result sequence. The new element will have the same <termref def="dt-expanded-qname">expanded QName</termref> as the original, and it
                        will have deep copies of the attribute nodes and children of the element
                        node.</p><p>The new element will also have namespace nodes copied from the original
                        element node, unless they are excluded by specifying
                           <code nobreak="false">copy-namespaces="no"</code>. If this attribute is omitted, or takes
                        the value <code nobreak="false">yes</code>, then all the namespace nodes of the original
                        element are copied to the new element. If it takes the value
                        <code nobreak="false">no</code>, then none of the namespace nodes are copied: however,
                        namespace nodes will still be created in the <termref def="dt-result-tree">result tree</termref> as <rfc2119>required</rfc2119> by the namespace
                        fixup process: see <specref ref="namespace-fixup"/>. This attribute affects
                        all elements copied by this instruction: both elements selected directly by
                        the <code nobreak="false">select</code>
                        <termref def="dt-expression">expression</termref>, and elements that are
                        descendants of nodes selected by the <code nobreak="false">select</code> expression. </p><p>The values of the <code nobreak="false">is-id</code>,
                           <code nobreak="false">is-idrefs</code>, and <code nobreak="false">nilled</code> properties of the new
                        element depend on the values of the <code nobreak="false">validation</code> and
                           <code nobreak="false">type</code> attributes, as defined in <specref ref="validation"/>.</p></item><item><p>If the item is a document node, the instruction adds a new document node to
                        the result sequence; the children of this document node will be one-to-one
                        copies of the children of the original document node (each copied according
                        to the rules for its own node kind). The
                              <code nobreak="false">unparsed-entities</code> property of the original document node
                           is copied to the new document node.</p></item><item><p>If the item is an attribute or namespace node, or a text node, a comment, or
                        a processing instruction, the same rules apply as with
                           <elcode>xsl:copy</elcode> (see <specref ref="shallow-copy"/>).</p></item><item><p>If the item is an atomic item or a function
                           item, the value is appended to the result sequence, as with
                           <elcode>xsl:sequence</elcode>.</p></item></ulist><p>The optional attributes <code nobreak="false">type</code> and <code nobreak="false">validation</code> may be used
                  on the <elcode>xsl:copy-of</elcode> instruction to validate the contents of an
                  element, attribute or document node against a type definition, element
                  declaration, or attribute declaration in a schema and thus to determine the
                     <termref def="dt-type-annotation"/> that the new copy of an element or
                  attribute node will carry. These attributes are applied individually to each
                  element, attribute, and document node that is selected by the expression in the
                     <code nobreak="false">select</code> attribute. These attributes are ignored when copying an
                  item that is not an element, attribute or document node.</p><p>The specified <code nobreak="false">type</code> and <code nobreak="false">validation</code> apply directly only to
                  elements, attributes and document nodes created as copies of nodes actually
                  selected by the <code nobreak="false">select</code> expression, they do not apply to nodes that
                  are implicitly copied because they have selected nodes as an ancestor. However,
                  these attributes do indirectly affect the <termref def="dt-type-annotation">type
                     annotation</termref> carried by such implicitly copied nodes, as a consequence
                  of the validation process.</p><p>These two attributes are both optional, and if one is specified then the other
                     <rfc2119>must</rfc2119> be omitted. The permitted values of these attributes
                  and their semantics are described in <specref ref="validation"/>.</p><p>Errors may occur when copying namespace-sensitive elements or attributes using
                     <code nobreak="false">validation="preserve"</code>. <errorref class="TE" code="0950"/>.</p><p>If removal of namespaces is requested using
                     <code nobreak="false">copy-namespaces="no"</code>, then any validation that is requested is
                  applied to the tree that remains after the relevant namespaces have been removed.
                  This will cause validation to fail if there is namespace-sensitive content that
                  depends on the presence of the removed namespaces.</p><p diff="del" at="2022-01-01">The base URI of a node is copied, except in the case of an element node having an
                     <code nobreak="false">xml:base</code> attribute, in which case the base URI of the new node is
                  taken as the value of the <code nobreak="false">xml:base</code> attribute, resolved if it is
                  relative against the base URI of the <elcode>xsl:copy-of</elcode> instruction. If
                  the copied node is subsequently attached as a child to a new element or document
                  node, the final copy of the node inherits its base URI from its parent node,
                  unless this is overridden using an <code nobreak="false">xml:base</code> attribute.</p><p diff="add" at="2022-01-01">
                  For any node <var>N</var> that is explicitly selected by the evaluation of the 
                  <code nobreak="false">select</code> expression, the base URI of the new copy is as follows:</p><ulist diff="add" at="2022-01-01"><item><p>If <var>N</var> is an element node having an <code nobreak="false">xml:base</code> attribute, 
                     the base URI of the new node is taken as the value of the <code nobreak="false">xml:base</code> attribute, 
                     resolved if it is relative against the static base URI of the <code nobreak="false">xsl:copy-of</code> instruction.
                  </p></item><item><p>Otherwise, the base URI of the new copy is the same as the base URI of <var>N</var>.
                  </p></item></ulist><p diff="add" at="2022-01-01">For any element or processing instruction node that has <var>N</var> as an ancestor, 
                     the base URI of the new copy is set to be the same as that of its new parent, 
                     with the following exception: if a copied element has an <code nobreak="false">xml:base</code> 
                     attribute, then its base URI is set to the value of that attribute, 
                     resolved if it is relative against the base URI of the new parent node.
                  </p><note><p>If two elements in a subtree have different base URIs for some reason 
                     unconnected with <code nobreak="false">xml:base</code> attributes (for example, if they originated in different 
                     external entities), then these differences are lost when the subtree is copied.
                  </p></note><note><p>As a consequence of rules specified elsewhere (see <specref ref="constructing-complex-content"/>), 
                        if a node created using the <code nobreak="false">xsl:copy-of</code> instruction is subsequently attached 
                        as a child to a new element or document node, the final copy of the node inherits 
                        its base URI from its new parent node, unless this is overridden using an <code nobreak="false">xml:base</code> attribute.
                     </p></note><p>The effect of the <code nobreak="false">copy-accumulators</code> attribute is described in
                  <specref ref="applicability-of-accumulators"/>.</p></div3></div2></div1><div1 id="number"><head>Numbering</head><e:element-syntax xmlns:e="http://www.w3.org/1999/XSL/Spec/ElementSyntax" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" name="number">
      <e:in-category name="instruction"/>
      <e:attribute name="value">
         <e:data-type name="expression"/>
      </e:attribute>
      <e:attribute name="select">
         <e:data-type name="expression"/>
      </e:attribute>
      <e:attribute name="level" default="'single'">
         <e:constant value="single"/>
         <e:constant value="multiple"/>
         <e:constant value="any"/>
      </e:attribute>
      <e:attribute name="count">
         <e:data-type name="pattern"/>
      </e:attribute>
      <e:attribute name="from">
         <e:data-type name="pattern"/>
      </e:attribute>
      <e:attribute name="format" default="'1'">
         <e:attribute-value-template>
            <e:data-type name="string"/>
         </e:attribute-value-template>
      </e:attribute>
      <e:attribute name="lang">
         <e:attribute-value-template>
            <e:data-type name="language"/>
         </e:attribute-value-template>
      </e:attribute>
      <e:attribute name="letter-value">
         <e:attribute-value-template>
            <e:constant value="alphabetic"/>
            <e:constant value="traditional"/>
         </e:attribute-value-template>
      </e:attribute>
      <e:attribute name="ordinal" default="'no'">
         <e:attribute-value-template>
            <e:data-type name="string"/>
         </e:attribute-value-template>
      </e:attribute>
      <e:attribute name="start-at">
         <e:attribute-value-template>
            <e:data-type name="string"/>
         </e:attribute-value-template>
      </e:attribute>
      <e:attribute name="grouping-separator">
         <e:attribute-value-template>
            <e:data-type name="char"/>
         </e:attribute-value-template>
      </e:attribute>
      <e:attribute name="grouping-size">
         <e:attribute-value-template>
            <e:data-type name="integer"/>
         </e:attribute-value-template>
      </e:attribute>
      <e:empty/>
      <e:allowed-parents>
         <e:parent-category name="sequence-constructor"/>
      </e:allowed-parents>
   </e:element-syntax><p>The <elcode>xsl:number</elcode> instruction is used to create a formatted number. The
            result of the instruction is a newly constructed text node containing the formatted
            number as its <termref def="dt-string-value">string value</termref>.</p><p>
            <termdef id="dt-place-marker" term="place marker">The <elcode>xsl:number</elcode>
               instruction performs two tasks: firstly, determining a <term>place marker</term>
               (this is a sequence of integers, to allow for hierarchic numbering schemes such as
                  <code nobreak="false">1.12.2</code> or <code nobreak="false">3(c)ii</code>), and secondly, formatting the place
               marker for output as a text node in the result sequence.</termdef> The place marker
            to be formatted can either be supplied directly, in the <code nobreak="false">value</code> attribute, or
            it can be computed based on the position of a selected node within the tree that
            contains it.</p><p>
            <error spec="XT" type="static" class="SE" code="0975"><p>It is a <termref def="dt-static-error">static error</termref> if the
                     <code nobreak="false">value</code> attribute of <elcode>xsl:number</elcode> is present unless
                  the <code nobreak="false">select</code>, <code nobreak="false">level</code>, <code nobreak="false">count</code>, and
                     <code nobreak="false">from</code> attributes are all absent.</p></error>
         </p><note><p>The facilities described in this section are specifically designed to enable the
               calculation and formatting of section numbers, paragraph numbers, and the like. For
               formatting of other numeric quantities, the <xfunction>format-number</xfunction>
               function may be more suitable.</p><p>Furthermore, formatting of integers where there is no requirement to calculate the
               position of a node in the document can now be accomplished using the
                  <xfunction>format-integer</xfunction> function, which borrows many concepts from
               the <elcode>xsl:number</elcode> specification.</p></note><div2 id="start-at"><head>The <code nobreak="false">start-at</code> Attribute</head><p>The <termref def="dt-effective-value"/> of the
                  <code nobreak="false">start-at</code> attribute <rfc2119>must</rfc2119> be a string representing a
               whitespace-separated sequence of one or more integers, each one optionally preceded
               by a minus sign, separated by whitespace. More specifically, the value must be a
               string matching the regular expression <code nobreak="false">-?[0-9]+(\s+-?[0-9]+)*</code>. This
               sequence of integers is used to <term>re-base</term> the sequence of integers being
               formatted. Specifically if <var>$S</var> is the sequence of integers represented by
               the <code nobreak="false">start-at</code> attribute, and <var>$V</var> is the sequence of integers to
               be formatted, then the following transformation is applied to <var>$V</var>:</p><eg role="non-xml" xml:space="preserve">
for $i in 1 to count($V)
return if ($i le count($S))
  then $V[$i] + $S[$i] - 1
  else $V[$i] + $S[last()] - 1
</eg><note><p>This means that if there are <var>N</var> integers in the <code nobreak="false">start-at</code>
                  attribute, then these are used to re-base the first <var>N</var> numbers, while
                  numbers after the <var>Nth</var> are re-based using the last (<var>Nth</var>)
                  integer in the <code nobreak="false">start-at</code> attribute. If the <code nobreak="false">start-at</code>
                  attribute contains more integers than are required, the surplus is ignored.</p></note><p>For example, if the attribute is given as
                  <code nobreak="false">start-at="3 0 0"</code>, and the number sequence to be formatted is
                  <code nobreak="false">(1, 1, 1, 1)</code>, then the re-based sequence is <code nobreak="false">3, 0, 0,
               0</code>.</p></div2><div2 id="formatting-supplied-number"><head>Formatting a Supplied Number</head><p>The <termref def="dt-place-marker">place marker</termref> to be formatted may be
               specified by an expression. The <code nobreak="false">value</code> attribute contains the <termref def="dt-expression">expression</termref>. 
               The value of this expression is 
               <termref def="dt-atomization">atomized</termref> using the procedure defined in <bibref ref="xpath-40"/>, 
               and each value <var>$V</var> in the atomized sequence is then
               converted to the integer value returned by the XPath expression
                  <code nobreak="false">xs:integer(round(number($V)))</code>. If
                  the <code nobreak="false">start-at</code> attribute is present, this sequence is then re-based as
                  described in <specref ref="start-at"/>. The resulting sequence of
               integers is used as the place marker to be formatted.</p><p>If the instruction is processed with <termref def="dt-xslt-10-behavior">XSLT 1.0 behavior</termref>, then:</p><ulist><item><p>All items in the <termref def="dt-atomization">atomized</termref> sequence
                     after the first are discarded;</p></item><item><p>If the atomized sequence is empty, it is replaced by a sequence containing the
                        <code nobreak="false">xs:double</code> value <code nobreak="false">NaN</code> as its only item;</p></item><item><p>If any value in the sequence cannot be converted to an integer (this includes
                     the case where the sequence contains a <code nobreak="false">NaN</code> value) then the string
                        <code nobreak="false">NaN</code> is inserted into the formatted result string in its proper
                     position. The error described in the following paragraph does not apply in this
                     case.</p></item></ulist><p>
               <error spec="XT" type="dynamic" class="DE" code="0980"><p>It is a <termref def="dt-dynamic-error"> dynamic error</termref> if any undiscarded item
                     in the atomized sequence supplied as the value of the <code nobreak="false">value</code>
                     attribute of <elcode>xsl:number</elcode> cannot be converted to an integer, or
                     if the resulting integer is less than 0 (zero). </p></error>
            </p><note><p>The value zero does not arise when numbering nodes in a source document, but it
                  can arise in other numbering sequences. It is permitted specifically because the
                  rules of the <elcode>xsl:number</elcode> instruction are also invoked by functions
                  such as <xfunction>format-time</xfunction>: the minutes and seconds component of a
                  time value can legitimately be zero.</p></note><p>The resulting sequence is formatted as a string using the <termref def="dt-effective-value">effective values</termref> of the attributes specified in
                  <specref ref="convert"/>; each of these attributes is interpreted as an <termref def="dt-attribute-value-template">attribute value template</termref>. After
               conversion, the <elcode>xsl:number</elcode> element constructs a new text node
               containing the resulting string, and returns this node.</p><example><head>Numbering a Sorted List</head><p>The following example numbers a sorted list:</p><eg xml:space="preserve" role="xslt-declaration">&lt;xsl:template match="items"&gt;
  &lt;xsl:for-each select="item"&gt;
    &lt;xsl:sort select="."/&gt;
    &lt;p&gt;
      &lt;xsl:number value="position()" format="1. "/&gt;
      &lt;xsl:value-of select="."/&gt;
    &lt;/p&gt;
  &lt;/xsl:for-each&gt;
&lt;/xsl:template&gt;</eg></example></div2><div2 id="numbering-based-on-position"><head>Numbering based on Position in a Document </head><p>If no <code nobreak="false">value</code> attribute is specified, then the <elcode>xsl:number</elcode>
               instruction returns a new text node containing a formatted <termref def="dt-place-marker">place marker</termref> that is based on the position of a
               selected node within its containing document. If the <code nobreak="false">select</code> attribute is
               present, then the expression contained in the <code nobreak="false">select</code> attribute is
               evaluated to determine the selected node. If the <code nobreak="false">select</code> attribute is
               omitted, then the selected node is the <termref def="dt-context-node">context
                  node</termref>.</p><p>
               <error spec="XT" type="type" class="TE" code="0990"><p>It is a <termref def="dt-type-error">type error</termref> if the
                        <elcode>xsl:number</elcode> instruction is evaluated, with no
                        <code nobreak="false">value</code> or <code nobreak="false">select</code> attribute, when the <termref def="dt-context-item">context item</termref> is not a node. </p></error>
            </p><p>
               <error spec="XT" type="type" class="TE" code="1000"><p>It is a <termref def="dt-type-error">type error</termref> if the result of
                     evaluating the <code nobreak="false">select</code> attribute of the <elcode>xsl:number</elcode>
                     instruction is anything other than a single node.</p></error>
            </p><p> The following attributes control how the selected node is to be numbered:</p><ulist><item><p>The <code nobreak="false">level</code> attribute specifies rules for selecting the nodes that
                     are taken into account in allocating a number; it has the values
                        <code nobreak="false">single</code>, <code nobreak="false">multiple</code> or <code nobreak="false">any</code>. The default
                     is <code nobreak="false">single</code>.</p></item><item><p>The <code nobreak="false">count</code> attribute is a <termref def="dt-pattern">pattern</termref> that specifies which nodes are to be counted at those
                     levels. If <code nobreak="false">count</code> attribute is not specified, then it defaults to
                     the pattern that matches any node with the same node kind as the selected node
                     and, if the selected node has an <termref def="dt-expanded-qname">expanded
                        QName</termref>, with the same <termref def="dt-expanded-qname">expanded
                        QName</termref> as the selected node.</p></item><item><p>The <code nobreak="false">from</code> attribute is a <termref def="dt-pattern">pattern</termref> that specifies where counting starts.</p></item></ulist><p>In addition, the attributes specified in <specref ref="convert"/> are used for number
               to string conversion, as in the case when the <code nobreak="false">value</code> attribute is
               specified.</p><p>The <elcode>xsl:number</elcode> element first constructs a sequence of positive
               integers using the <code nobreak="false">level</code>, <code nobreak="false">count</code> and <code nobreak="false">from</code>
               attributes. Where <code nobreak="false">level</code> is <code nobreak="false">single</code> or <code nobreak="false">any</code>, this
               sequence will either be empty or contain a single number; where <code nobreak="false">level</code> is
                  <code nobreak="false">multiple</code>, the sequence may be of any length. The sequence is
               constructed as follows:</p><p>Let <code nobreak="false">matches-count($node)</code> be a function that returns <code nobreak="false">true</code> if and only if
               the given node <code nobreak="false">$node</code> matches the pattern given in the <code nobreak="false">count</code>
               attribute, or the implied pattern (according to the rules given above) if the
                  <code nobreak="false">count</code> attribute is omitted.</p><p>Let <code nobreak="false">matches-from($node)</code> be a function that returns <code nobreak="false">true</code> if and only if
               the given node <code nobreak="false">$node</code> matches the pattern given in the <code nobreak="false">from</code>
               attribute, or if <code nobreak="false">$node</code> is the root node of a tree. If the
                  <code nobreak="false">from</code> attribute is omitted, then the function returns <code nobreak="false">true</code> if and only
               if <code nobreak="false">$node</code> is the root node of a tree.</p><p>Let <code nobreak="false">$S</code> be the selected node.</p><p>When <code nobreak="false">level="single"</code>: </p><ulist><item><p>Let <code nobreak="false">$A</code> be the node sequence selected by the following
                     expression:</p><p>
                     <code nobreak="false">   $S/ancestor-or-self::node()[matches-count(.)][1]</code>
                  </p><p>(this selects the innermost ancestor-or-self node that matches the
                        <code nobreak="false">count</code> pattern)</p></item><item><p>Let <code nobreak="false">$F</code> be the node sequence selected by the expression:</p><p>
                     <code nobreak="false">   $S/ancestor-or-self::node()[matches-from(.)][1]</code>
                  </p><p>(this selects the innermost ancestor-or-self node that matches the
                        <code nobreak="false">from</code> pattern)</p></item><item><p>Let <code nobreak="false">$AF</code> be the value of:</p><p>
                     <code nobreak="false">   $A[ancestor-or-self::node()[. is $F]]</code>
                  </p><p>(this selects $A if it is in the subtree rooted at $F, or the empty sequence
                     otherwise)</p></item><item><p>If <code nobreak="false">$AF</code> is empty, return the empty sequence, <code nobreak="false">()</code>
                  </p></item><item><p>Otherwise return the value of:</p><p>
                     <code nobreak="false">   1 + count($AF/preceding-sibling::node()[matches-count(.)])</code>
                  </p><p>(the number of preceding siblings of the counted node that match the
                        <code nobreak="false">count</code> pattern, plus one).</p></item></ulist><p>When <code nobreak="false">level="multiple"</code>: </p><ulist><item><p>Let <code nobreak="false">$A</code> be the node sequence selected by the expression:</p><p>
                     <code nobreak="false">   $S/ancestor-or-self::node()[matches-count(.)]</code>
                  </p><p>(the set of ancestor-or-self nodes that match the <code nobreak="false">count</code>
                     pattern)</p></item><item><p>Let <code nobreak="false">$F</code> be the node sequence selected by the expression:</p><p>
                     <code nobreak="false">   $S/ancestor-or-self::node()[matches-from(.)][1]</code>
                  </p><p>(the innermost ancestor-or-self node that matches the <code nobreak="false">from</code>
                     pattern)</p></item><item><p>Let <code nobreak="false">$AF</code> be the value of:</p><p>
                     <code nobreak="false">   $A[ancestor-or-self::node()[. is $F]]</code>
                  </p><p>(the nodes selected in the first step that are in the subtree rooted at the
                     node selected in the second step)</p></item><item><p>Return the result of the expression:</p><p>
                     <code nobreak="false">   for $af in $AF return
                        1+count($af/preceding-sibling::node()[matches-count(.)])</code>
                  </p><p>(a sequence of integers containing, for each of these nodes, one plus the
                     number of preceding siblings that match the <code nobreak="false">count</code> pattern)</p></item></ulist><p>When <code nobreak="false">level="any"</code>: </p><ulist><item><p>Let <code nobreak="false">$A</code> be the node sequence selected by the expression:</p><p>
                     <code nobreak="false">   $S/(preceding::node()|ancestor-or-self::node())[matches-count(.)]</code>
                  </p><p>(the set of nodes consisting of the selected node together with all nodes,
                     other than attributes and namespaces, that precede the selected node in
                     document order, provided that they match the <code nobreak="false">count</code> pattern)</p></item><item><p>Let <code nobreak="false">$F</code> be the node sequence selected by the expression:</p><p>
                     <code nobreak="false">   $S/(preceding::node()|ancestor-or-self::node())[matches-from(.)][last()]</code>
                  </p><p>(the last node in document order that matches the <code nobreak="false">from</code> pattern and
                     that precedes the selected node, using the same definition)</p></item><item><p>Let <code nobreak="false">$AF</code> be the node sequence <code nobreak="false">$A[. is $F or . &gt;&gt;
                        $F]</code></p><p>(the nodes selected in the first step, excluding those that precede the node
                     selected in the second step)</p></item><item><p>If <code nobreak="false">$AF</code> is empty, return the empty sequence, <code nobreak="false">()</code>
                  </p></item><item><p>Otherwise return the value of the expression <code nobreak="false">count($AF)</code>
                  </p></item></ulist><p>The resulting sequence of numbers is referred to as the <termref def="dt-place-marker">place marker</termref>.</p><p>If the <code nobreak="false">start-at</code> attribute is present, then the
                  <termref def="dt-place-marker">place marker</termref> is re-based as described in <specref ref="start-at"/>.</p><p>The sequence of numbers is then converted into a string using the <termref def="dt-effective-value">effective values</termref> of the attributes specified in
                  <specref ref="convert"/>; each of these attributes is interpreted as an <termref def="dt-attribute-value-template">attribute value template</termref>. After
               conversion, the resulting string is used to create a text node, which forms the
               result of the <elcode>xsl:number</elcode> instruction.</p><example><head>Numbering the Items in an Ordered List</head><p>The following will number the items in an ordered list:</p><eg xml:space="preserve" role="xslt-declaration xmlns:fo='fo'">&lt;xsl:template match="ol/item"&gt;
  &lt;fo:block&gt;
    &lt;xsl:number/&gt;
    &lt;xsl:text&gt;. &lt;/xsl:text&gt;
    &lt;xsl:apply-templates/&gt;
  &lt;/fo:block&gt;
&lt;/xsl:template&gt;</eg></example><example><head>Multi-Level Numbering</head><p>The following two rules will number <code nobreak="false">title</code> elements. This is intended
                  for a document that contains a sequence of chapters followed by a sequence of
                  appendices, where both chapters and appendices contain sections, which in turn
                  contain subsections. Chapters are numbered 1, 2, 3; appendices are numbered A, B,
                  C; sections in chapters are numbered 1.1, 1.2, 1.3; sections in appendices are
                  numbered A.1, A.2, A.3. Subsections within a chapter are numbered 1.1.1, 1.1.2,
                  1.1.3; subsections within an appendix are numbered A.1.1, A.1.2, A.1.3.</p><eg xml:space="preserve" role="xslt-declaration xmlns:fo='fo'">&lt;xsl:template match="title"&gt;
  &lt;fo:block&gt;
     &lt;xsl:number level="multiple"
                 count="chapter|section|subsection"
                 format="1.1 "/&gt;
     &lt;xsl:apply-templates/&gt;
  &lt;/fo:block&gt;
&lt;/xsl:template&gt;

&lt;xsl:template match="appendix//title" priority="1"&gt;
  &lt;fo:block&gt;
     &lt;xsl:number level="multiple"
                 count="appendix|section|subsection"
                 format="A.1 "/&gt;
     &lt;xsl:apply-templates/&gt;
  &lt;/fo:block&gt;
&lt;/xsl:template&gt;</eg></example><example><head>Numbering Notes within a Chapter</head><p>This example numbers notes sequentially within a chapter, starting from the number 100: :</p><eg xml:space="preserve" role="xslt-declaration xmlns:fo='fo'">&lt;xsl:template match="note"&gt;
  &lt;fo:block&gt;
     &lt;xsl:number level="any" from="chapter" format="(1) " start-at="100"/&gt;
     &lt;xsl:apply-templates/&gt;
  &lt;/fo:block&gt;
&lt;/xsl:template&gt;</eg></example></div2><div2 id="convert"><head>Number to String Conversion Attributes</head><note><p>This specification is aligned with that of the
                     <xfunction>format-integer</xfunction> function, but there are differences; for
                  example grouping separators are part of the primary format token in
                     <xfunction>format-integer</xfunction>, but are indicated by separate attributes
                  in <elcode>xsl:number</elcode>.</p></note><p>The following attributes are used to control conversion of a sequence of numbers into
               a string. The numbers are integers greater than or equal to 0 (zero). The attributes
               are all optional.</p><p>The main attribute is <code nobreak="false">format</code>. The default value for the
                  <code nobreak="false">format</code> attribute is <code nobreak="false">1</code>. The <code nobreak="false">format</code> attribute
               is split into a sequence of tokens where each token is a maximal sequence of
               alphanumeric characters or a maximal sequence of non-alphanumeric characters.
                  <emph>Alphanumeric</emph> means any character that has a Unicode category of Nd,
               Nl, No, Lu, Ll, Lt, Lm or Lo (see <bibref ref="UNICODE"/>). The alphanumeric tokens (<emph>format tokens</emph>)
               indicate the format to be used for each number in the sequence; in most cases the
               format token is the same as the required representation of the number 1 (one).</p><p>Each non-alphanumeric token is either a prefix, a separator, or a suffix. If there is
               a non-alphanumeric token but no format token, then the single non-alphanumeric token
               is used as both the prefix and the suffix. The prefix, if it exists, is the
               non-alphanumeric token that precedes the first format token: the prefix always
               appears exactly once in the constructed string, at the start. The suffix, if it
               exists, is the non-alphanumeric token that follows the last format token: the suffix
               always appears exactly once in the constructed string, at the end. All other
               non-alphanumeric tokens (those that occur between two format tokens) are
                  <emph>separator tokens</emph> and are used to separate numbers in the
               sequence.</p><p>The <var>n</var>th format token is used to format the <var>n</var>th number in the
               sequence. If there are more numbers than format tokens, then the last format token is
               used to format remaining numbers. If there are no format tokens, then a format token
               of <code nobreak="false">1</code> is used to format all numbers. Each number after the first is
               separated from the preceding number by the separator token preceding the format token
               used to format that number, or, if that is the first format token, then by
                  <code nobreak="false">.</code> (dot).</p><example><head>Formatting a List of Numbers</head><p>Given the sequence of numbers <code nobreak="false">5, 13, 7</code> and the format token
                     <code nobreak="false">A-001(i)</code>, the output will be the string <code nobreak="false">E-013(vii)</code>
               </p></example><p>Format tokens are interpreted as follows:</p><ulist><item><p>Any token where the last character has a decimal digit value of 1 (as specified
                     in the Unicode character property database, see <bibref ref="UNICODE"/>), and the Unicode
                     value of preceding characters is one less than the Unicode value of the last
                     character generates a decimal representation of the number where each number is
                     at least as long as the format token. The digits used in the decimal
                     representation are the set of digits containing the digit character used in the
                     format token. Thus, a format token <code nobreak="false">1</code> generates the sequence
                        <code nobreak="false">0 1 2 ... 10 11 12 ...</code>, and a format token <code nobreak="false">01</code>
                     generates the sequence <code nobreak="false">00 01 02 ... 09 10 11 12 ... 99 100 101</code>. A
                     format token of <char>U+0661</char> generates the
                     sequence <code nobreak="false">١</code> then <code nobreak="false">٢</code> then
                        <code nobreak="false">٣</code> ...</p></item><item><p>A format token <code nobreak="false">A</code> generates the sequence <code nobreak="false">A B C ... Z AA AB
                        AC...</code>.</p></item><item><p>A format token <code nobreak="false">a</code> generates the sequence <code nobreak="false">a b c ... z aa ab
                        ac...</code>.</p></item><item><p>A format token <code nobreak="false">i</code> generates the sequence <code nobreak="false">i ii iii iv v vi vii
                        viii ix x ...</code>.</p></item><item><p>A format token <code nobreak="false">I</code> generates the sequence <code nobreak="false">I II III IV V VI VII
                        VIII IX X ...</code>.</p></item><item><p>A format token <code nobreak="false">w</code> generates numbers written as lower-case words,
                     for example in English, <code nobreak="false">one two three four ...</code>.
                  </p></item><item><p>A format token <code nobreak="false">W</code> generates numbers written as upper-case words,
                     for example in English, <code nobreak="false">ONE TWO THREE FOUR ...</code>.
                  </p></item><item><p>A format token <code nobreak="false">Ww</code> generates numbers written as title-case words,
                     for example in English, <code nobreak="false">One Two Three Four ...</code>.
                  </p></item><item><p>Any other format token indicates a numbering sequence in which that token
                     represents the number 1 (one) (but see the note below).
                     
                     It is <termref def="dt-implementation-defined"/> 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 nobreak="false">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> and sometimes an <emph>aristeri
                           keraia</emph> is added.</p></note></item></ulist><imp-def-feature id="idf-local-numbering">The combinations of languages and numbering
               sequences recognized by the <elcode>xsl:number</elcode> instruction, beyond those
               defined as mandatory in this specification, are <termref def="dt-implementation-defined"/>. There <rfc2119>may</rfc2119> be
               implementation-defined upper bounds on the numbers that can be formatted using any
               particular numbering sequence. There <rfc2119>may</rfc2119> be constraints on the
               values of the <code nobreak="false">ordinal</code> attribute recognized for any given
               language.</imp-def-feature><p>For all format tokens other than the first kind above (one that consists of decimal
               digits), there <rfc2119>may</rfc2119> be <termref def="dt-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 <char>U+2460</char> has a range imposed
                  by the Unicode character repertoire (zero to 20 in Unicode versions prior to 3.2,
                  or zero to 50 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 nobreak="false">1</code>. The numbering sequence associated
               with the format token <code nobreak="false">1</code> has a lower bound of 0 (zero).</p><p>The above expansions of numbering sequences for format tokens such as <code nobreak="false">a</code>
               and <code nobreak="false">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 nobreak="false">IV</code> versus <code nobreak="false">IIII</code> as the representation of the number 4).
               Sometimes alphabetic sequences are used that omit letters such as <code nobreak="false">i</code> and
                  <code nobreak="false">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 nobreak="false">w</code>, <code nobreak="false">W</code> and <code nobreak="false">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 nobreak="false">lang</code>
               attribute specifies which language’s conventions are to be used; its <termref def="dt-effective-value">effective
                     value</termref>
                  <rfc2119>must</rfc2119> either be a string in the value space of
                     <code nobreak="false">xs:language</code>, or a zero-length string. If no
                  <code nobreak="false">lang</code> value is specified, or if the
                  value is a zero-length string, the language that is used is <termref def="dt-implementation-defined">implementation-defined</termref>. The set of
               languages for which numbering is supported is <termref def="dt-implementation-defined">implementation-defined</termref>. If a language is
               requested that is not supported, the processor <rfc2119>may</rfc2119> use a fallback language identified by removing
                  successive hyphen-separated suffixes from the supplied value until a supported
                  language code is obtained; failing this, the processor  uses the language
               that it would use if the <code nobreak="false">lang</code> attribute were omitted.</p><p>The optional <code nobreak="false">ordinal</code> attribute is used to
               indicate whether cardinal or ordinal numbers are required, and to select other
               options relating to the grammatical context of the number to be formatted. The
               allowed set of values is <termref def="dt-implementation-defined"/>. If the attribute
               is absent, or if its value is zero-length, or if its value is <code nobreak="false">no</code> or
                  <code nobreak="false">0</code> or <code nobreak="false">false</code>, then cardinal numbers appropriate to the
               selected language are output. If the value is <code nobreak="false">yes</code> or <code nobreak="false">1</code> or
                  <code nobreak="false">true</code>, then ordinal numbers appropriate to the target language are
               output. Other values are <termref def="dt-implementation-defined"/>.</p><p>For example, in English, the value <code nobreak="false">ordinal="yes"</code> when used with the
               format token <code nobreak="false">1</code> outputs the sequence <code nobreak="false">1st 2nd 3rd 4th ...</code>,
               and when used with the format token <code nobreak="false">w</code> outputs the sequence <code nobreak="false">first
                  second third fourth ...</code>.</p><note><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 value of the
                     <code nobreak="false">ordinal</code> attribute may be used to indicate the variation of the
                  cardinal or ordinal number required, in an <termref def="dt-implementation-defined"/> way. </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 nobreak="false">ordinal="-e"</code>, <code nobreak="false">ordinal="-er"</code>,
                     <code nobreak="false">ordinal="-es"</code>, <code nobreak="false">ordinal="-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 of the attribute to be the name of a registered numbering rule
                  set for the language in question, conventionally prefixed with a percent sign: for
                  example, <code nobreak="false">ordinal="%spellout-ordinal-masculine"</code>, or
                     <code nobreak="false">ordinal="%spellout-cardinal-year"</code>. (The attribute name
                     <code nobreak="false">ordinal</code> in this case is a misnomer, but serves the purpose.) </p></note><example><head>Ordinal Numbering in Italian</head><p>The specification <code nobreak="false">format="1" ordinal="-º" lang="it"</code>, if supported,
                  should produce the sequence:</p><eg xml:space="preserve" role="non-xml">1º 2º 3º 4º ...</eg><p>The specification <code nobreak="false">format="Ww" ordinal="-o" lang="it"</code>, if supported,
                  should produce the sequence:</p><eg xml:space="preserve" role="non-xml">Primo Secondo Terzo Quarto Quinto ...</eg></example><p>The <code nobreak="false">letter-value</code> attribute 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 nobreak="false">a</code> and <code nobreak="false">i</code>.
               In some languages, the first member of each sequence is the same, and so the format
               token alone would be ambiguous. A value of <code nobreak="false">alphabetic</code> specifies the
               alphabetic sequence; a value of <code nobreak="false">traditional</code> specifies the other
               sequence. If the <code nobreak="false">letter-value</code> attribute is not specified, then it is
                  <termref def="dt-implementation-dependent">implementation-dependent</termref> how
               any ambiguity is resolved.</p><note><p>Implementations may use <termref def="dt-extension-attribute">extension
                     attributes</termref> on <elcode>xsl:number</elcode> to provide additional
                  control over the way in which numbers are formatted.</p></note><p>The <code nobreak="false">grouping-separator</code> attribute gives the separator used as a grouping
               (for example, thousands) separator in decimal numbering sequences, and the optional
                  <code nobreak="false">grouping-size</code> specifies the size (normally 3) of the grouping. For
               example, <code nobreak="false">grouping-separator=","</code> and <code nobreak="false">grouping-size="3"</code> would
               produce numbers of the form <code nobreak="false">1,000,000</code> while
                  <code nobreak="false">grouping-separator="."</code> and <code nobreak="false">grouping-size="2"</code> would
               produce numbers of the form <code nobreak="false">1.00.00.00</code>. If only one of the
                  <code nobreak="false">grouping-separator</code> and <code nobreak="false">grouping-size</code> attributes is
               specified, then it is ignored.</p><p>The <termref def="dt-effective-value">effective
                  value</termref> of the <code nobreak="false">grouping-separator</code> attribute
                  <rfc2119>may</rfc2119> be any string, including a zero-length string. </p><p>The <termref def="dt-effective-value">effective
                  value</termref> of the <code nobreak="false">grouping-size</code> attribute
                  <rfc2119>must</rfc2119> be a string in the lexical space of
                  <code nobreak="false">xs:integer</code>. If the resulting integer is positive then it defines the
               number of digits between adjacent grouping separators; it if is zero or negative,
               then no grouping separators are inserted. </p><example><head>Format Tokens and the Resulting Sequences</head><p>These examples use non-Latin characters which might not display correctly in all
                  browsers, depending on the system configuration.</p><table class="data" border="1" cellpadding="5" width="100%"><caption>Format tokens for use with xsl:number</caption><thead><tr><th align="left" rowspan="1" colspan="1" valign="top">Description</th><th align="left" rowspan="1" colspan="1" valign="top">Format Token</th><th align="left" rowspan="1" colspan="1" valign="top">Sequence</th></tr></thead><tbody><tr><td rowspan="1" colspan="1" align="left" valign="top">French cardinal words</td><td rowspan="1" colspan="1" align="left" valign="top">
                           <code nobreak="false">format="Ww" lang="fr"</code>
                        </td><td rowspan="1" colspan="1" align="left" valign="top">Un, Deux, Trois, Quatre</td></tr><tr><td rowspan="1" colspan="1" align="left" valign="top">German ordinal words</td><td rowspan="1" colspan="1" align="left" valign="top">
                           <code nobreak="false">format="w" ordinal="-e" lang="de"</code>
                        </td><td rowspan="1" colspan="1" align="left" valign="top">erste, zweite, dritte, vierte</td></tr><tr><td rowspan="1" colspan="1" align="left" valign="top">Katakana numbering</td><td rowspan="1" colspan="1" align="left" valign="top">
                           <code nobreak="false">format="&amp;#x30A2;"</code>
                        </td><td rowspan="1" colspan="1" align="left" valign="top">ア, イ, ウ, エ, オ, カ, キ,
                           ク, ケ, コ, サ, シ, ス, セ,
                           ソ, タ, チ, ツ, テ, ト, ナ,
                           ニ, ヌ, ネ, ノ, ハ, ヒ, フ,
                           ヘ, ホ, マ, ミ, ム, メ, モ,
                           ヤ, ユ, ヨ, ラ, リ, ル, レ,
                           ロ, ワ, ヰ, ヱ, ヲ, ン</td></tr><tr><td rowspan="1" colspan="1" align="left" valign="top">Katakana numbering in iroha order</td><td rowspan="1" colspan="1" align="left" valign="top">
                           <code nobreak="false">format="&amp;#x30A4;"</code>
                        </td><td rowspan="1" colspan="1" align="left" valign="top">イ, ロ, ハ, ニ, ホ, ヘ, ト,
                           チ, リ, ヌ, ル, ヲ, ワ, カ,
                           ヨ, タ, レ, ソ, ツ, ネ, ナ,
                           ラ, ム, ウ, ヰ, ノ, オ, ク,
                           ヤ, マ, ケ, フ, コ, エ, テ,
                           ア, サ, キ, ユ, メ, ミ, シ,
                           ヱ, ヒ, モ, セ, ス</td></tr><tr><td rowspan="1" colspan="1" align="left" valign="top">Thai numbering</td><td rowspan="1" colspan="1" align="left" valign="top">
                           <code nobreak="false">format="&amp;#x0E51;"</code>
                        </td><td rowspan="1" colspan="1" align="left" valign="top">๑, ๒, ๓, ๔, ๕, ๖, ๗, ๘,
                           ๙, ๑๐, ๑๑, ๑๒, ๑๓,
                           ๑๔, ๑๕, ๑๖, ๑๗,
                           ๑๘, ๑๙, ๒๐</td></tr><tr><td rowspan="1" colspan="1" align="left" valign="top">Traditional Hebrew numbering</td><td rowspan="1" colspan="1" align="left" valign="top">
                           <code nobreak="false">format="&amp;#x05D0;" letter-value="traditional"</code>
                        </td><td rowspan="1" colspan="1" align="left" valign="top">א, ב, ג, ד, ה, ו, ז, ח,
                           ט, י, יא, יב, יג,
                           יד, טו, טז, יז,
                           יח, יט, כ</td></tr><tr><td rowspan="1" colspan="1" align="left" valign="top">Traditional Georgian numbering</td><td rowspan="1" colspan="1" align="left" valign="top">
                           <code nobreak="false">format="&amp;#x10D0;" letter-value="traditional"</code>
                        </td><td rowspan="1" colspan="1" align="left" valign="top">ა, ბ, გ, დ, ე, ვ, ზ,
                           ჱ, თ, ი, ია, იბ,
                           იგ, იდ, იე, ივ,
                           იზ, იჱ, ით, კ </td></tr><tr><td rowspan="1" colspan="1" align="left" valign="top">Classical Greek numbering (see note)</td><td rowspan="1" colspan="1" align="left" valign="top">
                           <code nobreak="false">format="&amp;#x03B1;" letter-value="traditional"</code>
                        </td><td rowspan="1" colspan="1" align="left" valign="top"><phrase role="normalize-nfc"> αʹ, βʹ, γʹ, δʹ,
                           εʹ, ϛʹ, ζʹ, ηʹ,
                           θʹ, ιʹ, ιαʹ,
                           ιβʹ, ιγʹ, ιδʹ,
                           ιεʹ, ιϛʹ, ιζʹ,
                           ιηʹ, ιθʹ, κʹ</phrase></td></tr><tr><td rowspan="1" colspan="1" align="left" valign="top">Old Slavic numbering</td><td rowspan="1" colspan="1" align="left" valign="top">
                           <code nobreak="false">format="&amp;#x0430;" letter-value="traditional"</code>
                        </td><td rowspan="1" colspan="1" align="left" valign="top">А, В, Г, Д, Е, Ѕ, З, И,
                           Ѳ, Ӏ, АӀ, ВӀ, ГӀ,
                           ДӀ, ЕӀ, ЅӀ, ЗӀ,
                           ИӀ, ѲӀ, К</td></tr></tbody></table><p>Note that Classical Greek is an example where the format token is not the same as
                  the representation of the number 1.</p></example></div2></div1><div1 id="sorting"><head>Sorting</head><p>
            <termdef id="dt-sort-key-specification" term="sort key specification">A <term>sort key
                  specification</term> is a sequence of one or more adjacent
                  <elcode>xsl:sort</elcode> elements which together define rules for sorting the
               items in an input sequence to form a sorted sequence.</termdef>
         </p><p>
            <termdef id="dt-sort-key-component" term="sort key component">Within a <termref def="dt-sort-key-specification">sort key specification</termref>, each
                  <elcode>xsl:sort</elcode> element defines one <term>sort key
               component</term>.</termdef> The first <elcode>xsl:sort</elcode> element specifies the
            primary component of the sort key specification, the second <elcode>xsl:sort</elcode>
            element specifies the secondary component of the sort key specification, and so on.</p><p>A sort key specification may occur immediately within an
               <elcode>xsl:apply-templates</elcode>, <elcode>xsl:for-each</elcode>,
               <elcode>xsl:perform-sort</elcode>, or <elcode>xsl:for-each-group</elcode>
            element.</p><note><p>When used within <elcode>xsl:for-each</elcode>, <elcode>xsl:for-each-group</elcode>,
               or <elcode>xsl:perform-sort</elcode>, <elcode>xsl:sort</elcode> elements must occur
               before any other children.</p></note><div2 id="xsl-sort"><head>The <elcode>xsl:sort</elcode> Element</head><e:element-syntax xmlns:e="http://www.w3.org/1999/XSL/Spec/ElementSyntax" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" name="sort">
      <e:attribute name="select">
         <e:data-type name="expression"/>
      </e:attribute>
      <e:attribute name="lang">
         <e:attribute-value-template>
            <e:data-type name="language"/>
         </e:attribute-value-template>
      </e:attribute>
      <e:attribute name="order" default="'ascending'">
         <e:attribute-value-template>
            <e:constant value="ascending"/>
            <e:constant value="descending"/>
         </e:attribute-value-template>
      </e:attribute>
      <e:attribute name="collation">
         <e:attribute-value-template>
            <e:data-type name="uri"/>
         </e:attribute-value-template>
      </e:attribute>
      <e:attribute name="stable" default="'yes'">
         <e:attribute-value-template>
            <e:data-type name="boolean"/>
         </e:attribute-value-template>
      </e:attribute>
      <e:attribute name="case-order">
         <e:attribute-value-template>
            <e:constant value="upper-first"/>
            <e:constant value="lower-first"/>
         </e:attribute-value-template>
      </e:attribute>
      <e:attribute name="data-type">
         <e:attribute-value-template>
            <e:constant value="text"/>
            <e:constant value="number"/>
            <e:data-type name="eqname"/>
         </e:attribute-value-template>
      </e:attribute>
      <e:model name="sequence-constructor"/>
      <e:allowed-parents>
         <e:parent name="apply-templates"/>
         <e:parent name="for-each"/>
         <e:parent name="for-each-group"/>
         <e:parent name="perform-sort"/>
      </e:allowed-parents>
   </e:element-syntax><p>The <elcode>xsl:sort</elcode> element defines a <termref def="dt-sort-key-component">sort key component</termref>. A sort key component specifies how a <termref def="dt-sort-key-value">sort key value</termref> is to be computed for each item
               in the sequence being sorted, and also how two sort key values are to be
               compared.</p><p>The value of a <termref def="dt-sort-key-component">sort key component</termref> is
               determined either by its <code nobreak="false">select</code> attribute or by the contained <termref def="dt-sequence-constructor">sequence constructor</termref>. If neither is
               present, the default is <code nobreak="false">select="."</code>, which has the effect of sorting on
               the actual value of the item if it is an atomic item, or on the typed-value of the
               item if it is a node. If a <code nobreak="false">select</code> attribute is present, its value
                  <rfc2119>must</rfc2119> be an XPath <termref def="dt-expression">expression</termref>.</p><p>
               <error spec="XT" type="static" class="SE" code="1015"><p>It is a <termref def="dt-static-error">static error</termref> if an
                        <elcode>xsl:sort</elcode> element with a <code nobreak="false">select</code> attribute has
                     non-empty content.</p></error>
            </p><p>Those attributes of the <elcode>xsl:sort</elcode> elements whose values are <termref def="dt-attribute-value-template">attribute value templates</termref> are
               evaluated using the same <termref def="dt-focus">focus</termref> as is used to
               evaluate the <code nobreak="false">select</code> attribute of the containing instruction
               (specifically, <elcode>xsl:apply-templates</elcode>, <elcode>xsl:for-each</elcode>,
                  <elcode>xsl:for-each-group</elcode>, or <elcode>xsl:perform-sort</elcode>).</p><p>The <code nobreak="false">stable</code> attribute is permitted only on the first
                  <elcode>xsl:sort</elcode> element within a <termref def="dt-sort-key-specification">sort key specification</termref>.
            </p><p>
               <error spec="XT" type="static" class="SE" code="1017"><p>It is a <termref def="dt-static-error">static error</termref> if an
                        <elcode>xsl:sort</elcode> element other than the first in a sequence of
                     sibling <elcode>xsl:sort</elcode> elements has a <code nobreak="false">stable</code>
                     attribute.</p></error>
            </p><p>
               <termdef id="dt-stable" term="stable">A <termref def="dt-sort-key-specification">sort
                     key specification</termref> is said to be <term>stable</term> if its first
                     <elcode>xsl:sort</elcode> element has no <code nobreak="false">stable</code> attribute, or has
                  a <code nobreak="false">stable</code> attribute whose <termref def="dt-effective-value">effective
                     value</termref> is <code nobreak="false">yes</code>.</termdef>
            </p><div3 id="sorting-process"><head>The Sorting Process</head><p>
                  <termdef id="dt-initial-sequence" term="initial sequence">The sequence to be
                     sorted is referred to as the <term>initial sequence</term>.</termdef>
               </p><p>
                  <termdef id="dt-sorted-sequence" term="sorted sequence">The sequence after sorting
                     as defined by the <elcode>xsl:sort</elcode> elements is referred to as the
                        <term>sorted sequence</term>.</termdef>
               </p><p>
                  <termdef id="dt-sort-key-value" term="sort key value"> For each item in the
                        <termref def="dt-initial-sequence">initial sequence</termref>, a value is
                     computed for each <termref def="dt-sort-key-component">sort key
                        component</termref> within the <termref def="dt-sort-key-specification">sort
                        key specification</termref>. The value computed for an item by using the
                        <var>N</var>th sort key component is referred to as the <var>N</var>th
                        <term>sort key value</term> of that item.</termdef>
               </p><p>The items in the <termref def="dt-initial-sequence">initial sequence</termref> are
                  ordered into a <termref def="dt-sorted-sequence">sorted sequence</termref> by
                  comparing their <termref def="dt-sort-key-value">sort key values</termref>. The
                  relative position of two items <var>A</var> and <var>B</var> in the sorted
                  sequence is determined as follows. The first sort key value of <var>A</var> is
                  compared with the first sort key value of <var>B</var>, according to the rules of
                  the first <termref def="dt-sort-key-component">sort key component</termref>. If,
                  under these rules, <var>A</var> is less than <var>B</var>, then <var>A</var> will
                  precede <var>B</var> in the sorted sequence, unless the <code nobreak="false">order</code>
                  attribute of this <termref def="dt-sort-key-component">sort key
                     component</termref> specifies <code nobreak="false">descending</code>, in which case
                     <var>B</var> will precede <var>A</var> in the sorted sequence. If, however, the
                  relevant sort key values compare equal, then the second sort key value of
                     <var>A</var> is compared with the second sort key value of <var>B</var>,
                  according to the rules of the second <termref def="dt-sort-key-component">sort key
                     component</termref>. This continues until two sort key values are found that
                  compare unequal. If all the sort key values compare equal, and the <termref def="dt-sort-key-specification">sort key specification</termref> is <termref def="dt-stable">stable</termref>, then <var>A</var> will precede <var>B</var>
                  in the <termref def="dt-sorted-sequence">sorted sequence</termref> if and only if
                     <var>A</var> preceded <var>B</var> in the <termref def="dt-initial-sequence">initial sequence</termref>. If all the sort key values compare equal, and the
                     <termref def="dt-sort-key-specification">sort key specification</termref> is
                  not <termref def="dt-stable">stable</termref>, then the relative order of
                     <var>A</var> and <var>B</var> in the <termref def="dt-sorted-sequence">sorted
                     sequence</termref> is <termref def="dt-implementation-dependent">implementation-dependent</termref>.</p><note><p>If two items have equal <termref def="dt-sort-key-value">sort key
                        values</termref>, and the sort is <termref def="dt-stable">stable</termref>,
                     then their order in the <termref def="dt-sorted-sequence">sorted
                        sequence</termref> will be the same as their order in the <termref def="dt-initial-sequence">initial sequence</termref>, regardless of whether
                        <code nobreak="false">order="descending"</code> was specified on any or all of the <termref def="dt-sort-key-component">sort key components</termref>.</p></note><p>The <var>N</var>th sort key value is computed by evaluating either the
                     <code nobreak="false">select</code> attribute or the contained <termref def="dt-sequence-constructor">sequence constructor</termref> of the
                     <var>N</var>th <elcode>xsl:sort</elcode> element, or the expression
                     <code nobreak="false">.</code> (dot) if neither is present. This evaluation is done with the
                     <termref def="dt-focus">focus</termref> set as follows:</p><ulist><item><p>The <termref def="dt-context-item">context item</termref> is the item in the
                           <termref def="dt-initial-sequence">initial sequence</termref> whose
                           <termref def="dt-sort-key-value">sort key value</termref> is being
                        computed.</p></item><item><p>The <termref def="dt-context-position">context position</termref> is the
                        position of that item in the initial sequence.</p></item><item><p>The <termref def="dt-context-size">context size</termref> is the size of the
                        initial sequence.</p></item></ulist><note><p>As in any other XPath expression, the <function>current</function> function may
                     be used within the <code nobreak="false">select</code> expression of <elcode>xsl:sort</elcode>
                     to refer to the item that is the context item for the expression as a whole;
                     that is, the item whose <termref def="dt-sort-key-value">sort key
                        value</termref> is being computed.</p></note><p>The <termref def="dt-sort-key-value">sort key values</termref> are <termref def="dt-atomization">atomized</termref>, and are then compared. The way they
                  are compared depends on their datatype, as described in the next section.</p></div3><div3 id="comparing-sort-keys"><head>Comparing Sort Key Values</head><changes><change issue="98" PR="2218" date="2025-10-07">
                     Numeric values of type <code nobreak="false">xs:decimal</code> are compared
                     as decimals, without first converting to <code nobreak="false">xs:double</code>.
                  </change><change issue="1662" PR="1674" date="2025-01-07">
                     Composite sort keys are allowed in <elcode>xsl:sort</elcode>.
                  </change></changes><p>It is possible to force the system to compare <termref def="dt-sort-key-value">sort key values</termref> using the rules for a particular datatype by
                  including a cast as part of the <termref def="dt-sort-key-component">sort key
                     component</termref>. For example, <code nobreak="false">&lt;xsl:sort
                     select="xs:date(@dob)"/&gt;</code> will force the attributes to be compared as
                  dates. In the absence of such a cast, the sort key values are compared using the
                  rules appropriate to their datatype. Any values of type
                     <code nobreak="false">xs:untypedAtomic</code> are cast to <code nobreak="false">xs:string</code>.</p><p>For backwards compatibility with XSLT 1.0, the <code nobreak="false">data-type</code> attribute
                  remains available. If this has the <termref def="dt-effective-value">effective
                     value</termref>
                  <code nobreak="false">text</code>, the atomized <termref def="dt-sort-key-value">sort key
                     values</termref> are converted to strings before being compared. If it has the
                  <termref def="dt-effective-value"/> <code nobreak="false">number</code>, the atomized sort key values are converted to
                  doubles before being compared. The conversion is done by using the
                     <xfunction>string</xfunction> or <xfunction>number</xfunction> function as
                  appropriate. If the <code nobreak="false">data-type</code> attribute has
                     any other <termref def="dt-effective-value"/>, then
                     this value <rfc2119>must</rfc2119> be an <termref def="dt-eqname">EQName</termref> denoting an <termref def="dt-expanded-qname">expanded
                        QName</termref> with a non-absent namespace, and the effect of the
                  attribute is <termref def="dt-implementation-defined"/>. 
               <phrase diff="add" at="2023-07-04">If the attribute is omitted, no conversion
               takes place.</phrase></p><imp-def-feature id="idf-ext-sortdatatype">If the <code nobreak="false">data-type</code> attribute of
                  the <elcode>xsl:sort</elcode> element has a value other than <code nobreak="false">text</code> or
                     <code nobreak="false">number</code>, the effect is implementation-defined.</imp-def-feature><p>
                  If the <elcode>xsl:sort</elcode> element is processed with <termref def="dt-xslt-10-behavior">XSLT 1.0
                              behavior</termref>,
                  then if any <termref def="dt-sort-key-value">sort key value</termref>, after
                           <termref def="dt-atomization">atomization</termref> and any type
                        conversion <rfc2119>required</rfc2119> by the <code nobreak="false">data-type</code>
                        attribute, is a sequence containing more than one item, then the effective
                        sort key value is the first item in the sequence.</p><p>In general the <termref def="dt-sort-key-value">sort key values</termref> (after any
                  conversion) are sequences of atomic items. Two sequences of atomic items
                  <var>S1</var> and <var>S2</var> are compared as follows:</p><olist><item><p>If both <var>S1</var> and <var>S2</var> are empty sequences,
                     then they compare equal.</p></item><item><p>A sequence that is empty is considered to be less than
                        a sequence that is not empty.</p></item><item><p>If neither sequence is empty, then
                        <code nobreak="false">head(<var>S1</var>)</code> and 
                        <code nobreak="false">head(<var>S2</var>)</code> are compared
                        according to the rules below.</p><olist><item><p>If they compare equal, the result is obtained
                        by comparing <code nobreak="false">tail(<var>S1</var>)</code> to 
                        <code nobreak="false">tail(<var>S2</var>)</code>.</p></item><item><p>Otherwise, the result of comparing these two
                        items is used as the result of the sequence comparison.</p></item></olist></item></olist><p>For example:</p><ulist><item><p><code nobreak="false">(1, 2, 3)</code> precedes <code nobreak="false">(1, 2, 4)</code>.</p></item><item><p><code nobreak="false">(1, 2)</code> precedes <code nobreak="false">(1, 2, 3)</code></p></item><item><p><code nobreak="false">()</code> precedes <code nobreak="false">(1, 2)</code></p></item></ulist><p>Individual atomic items are compared by calling the function 
               <code nobreak="false">fn:compare(<var>A1</var>, <var>A2</var>, <var>C</var>)</code>,
               where <var>C</var> is the appropriate collation,
                  as described in the next section.
               This will raise an error if the values are
                  not comparable (for example, if one is an <code nobreak="false">xs:integer</code> and the other is
                  an <code nobreak="false">xs:date</code>).</p><p>
                  <error spec="XT" type="dynamic" class="DE" code="1030"><p>It is a <termref def="dt-dynamic-error"> dynamic error</termref> if, for any <termref def="dt-sort-key-component">sort key component</termref>, the set of
                           <termref def="dt-sort-key-value">sort key values</termref> evaluated for
                        all the items in the <termref def="dt-initial-sequence">initial
                           sequence</termref>, after any type conversion requested, contains a pair
                        of atomic items that are not comparable using the <function>fn:compare</function>. If the processor is
                           able to detect the error statically, it <rfc2119>may</rfc2119> optionally
                           raise it as a <termref def="dt-static-error">static
                           error</termref>.</p></error>
               </p><note><p>The above error condition may occur if the
                     sequence is heterogeneous (for example, if it contains both strings and
                     numbers). The error can generally be prevented by invoking a cast or
                     constructor function within the sort key component.</p><p>The error condition is subject to the usual caveat that a processor is not
                     required to evaluate any expression solely in order to determine whether it
                     raises an error. For example, if there are several sort key components, then a
                     processor is not required to evaluate or compare minor sort key values unless
                     the corresponding major sort key values are equal.</p><p>In XSLT 4.0 the error can no longer occur if the items in the sequence
                  all have the same data type. An order relation is now defined for all
                  atomic types (including, for example, <code nobreak="false">xs:duration</code>).</p></note></div3><div3 id="collating-sequences"><head>Sorting Using Collations</head><p>The rules given in this section apply when comparing values whose type is
                     <code nobreak="false">xs:string</code> or a type derived by restriction from
                     <code nobreak="false">xs:string</code>, or whose type is <code nobreak="false">xs:anyURI</code> or a type
                  derived by restriction from <code nobreak="false">xs:anyURI</code>.</p><p>
                  <termdef id="dt-collation" term="collation">Facilities in XSLT 3.0 and XPath 3.0 that
                     require strings to be ordered rely on the concept of a named
                        <term>collation</term>. A collation is a set of rules that determine whether
                     two strings are equal, and if not, which of them is to be sorted before the
                     other.</termdef> A collation is identified by a URI, but the manner in which
                  this URI is associated with an actual rule or algorithm is largely <termref def="dt-implementation-defined">implementation-defined</termref>.</p><p>For more information about collations, see <xspecref spec="FO40" ref="string-compare"/> in <bibref ref="xpath-functions-40"/>. Some
                  specifications, for example <bibref ref="UNICODE-TR10"/>, use the term “collation”
                  to describe rules that can be tailored or parameterized for various purposes. In
                  this specification, a collation URI refers to a collation in which all such
                  parameters have already been fixed. Therefore, if a collation URI is specified,
                  other attributes such as <code nobreak="false">case-order</code> and <code nobreak="false">lang</code> are
                  ignored. </p><imp-def-feature id="idf-local-collations">The facilities for defining collations and
                  allocating URIs to identify them are largely
                  implementation-defined.</imp-def-feature><p>Every implementation <rfc2119>must</rfc2119>
                     recognize the collation URI 
                  <code nobreak="false">http://www.w3.org/2005/xpath-functions/collation/codepoint</code>, which
                  provides the ability to compare strings based on the Unicode codepoint values of
                  the characters in the string.</p><p>Furthermore, every implementation must recognize collation URIs
                  representing tailorings of the Unicode Collation Algorithm (UCA), as described in
                     <xspecref spec="FO40" ref="uca-collations"/>. Although this form of collation URI must be
                  recognized, implementations are not required to support every possible
                  tailoring.</p><p>If the <elcode>xsl:sort</elcode> element has a <code nobreak="false">collation</code> attribute,
                  then the strings are compared according to the rules for the named <termref def="dt-collation">collation</termref>: that is, they are compared using the
                  XPath function call <code nobreak="false">compare($a, $b, $collation)</code>.</p><p>If the <termref def="dt-effective-value">effective value</termref> of the
                     <code nobreak="false">collation</code> attribute of <elcode>xsl:sort</elcode> is a relative
                  URI, then it is resolved against the base URI of the <elcode>xsl:sort</elcode>
                  element.</p><p>
                  <error spec="XT" type="dynamic" class="DE" code="1035"><p>It is a <termref def="dt-dynamic-error"> dynamic error</termref> if the
                           <code nobreak="false">collation</code> attribute of <elcode>xsl:sort</elcode> (after
                        resolving against the base URI) is not a URI that is recognized by the
                        implementation as referring to a collation.</p></error>
               </p><note><p>It is entirely for the implementation to determine whether it recognizes a
                     particular collation URI. For example, if the implementation allows collation
                     URIs to contain parameters in the query part of the URI, it is the
                     implementation that determines whether a URI containing an unknown or invalid
                     parameter is or is not a recognized collation URI. The fact that this situation
                     is described as an error thus does not prevent an implementation applying a
                     fallback collation if it chooses to do so.</p></note><p>The <code nobreak="false">lang</code> and <code nobreak="false">case-order</code> attributes are ignored if a
                     <code nobreak="false">collation</code> attribute is present. But in the absence of a
                     <code nobreak="false">collation</code> attribute, these attributes provide input to an <termref def="dt-implementation-defined">implementation-defined</termref> algorithm to
                  locate a suitable collation:</p><imp-def-feature id="idf-local-implicitcollations">The algorithm used by
                     <elcode>xsl:sort</elcode> to locate a collation, given the values of the
                     <code nobreak="false">lang</code> and <code nobreak="false">case-order</code> attributes, is
                  implementation-defined.</imp-def-feature><ulist><item><p>The <code nobreak="false">lang</code> attribute indicates that a collation suitable for a
                        particular natural language <rfc2119>should</rfc2119> be used. 
                        The <termref def="dt-effective-value"/> of the attribute <rfc2119>must</rfc2119>
                         either be a string in the value space of
                              <code nobreak="false">xs:language</code>, or a zero-length string. Supplying the
                           zero-length string has the same effect as omitting the attribute. If a
                           language is requested that is not supported, the processor
                              <rfc2119>may</rfc2119> use a fallback language identified by removing
                           successive hyphen-separated suffixes from the supplied value until a
                           supported language code is obtained; failing this, the processor behaves
                           as if the <code nobreak="false">lang</code> attribute were omitted. </p><note><p>The fallback algorithm described above is 
                        identical to the rules in RFC4647 Basic Filtering used in BCP 47,
                     and is specified in <bibref ref="RFC4647"/> in greater detail.</p></note></item><item><p>The <code nobreak="false">case-order</code> attribute indicates whether the desired
                        collation <rfc2119>should</rfc2119> sort upper-case letters before
                        lower-case or vice versa. The <termref def="dt-effective-value">effective
                           value</termref> of the attribute <rfc2119>must</rfc2119> be either
                           <code nobreak="false">lower-first</code> (indicating that lower-case letters precede
                        upper-case letters in the collating sequence) or <code nobreak="false">upper-first</code>
                        (indicating that upper-case letters precede lower-case).</p><p>When <code nobreak="false">lower-first</code> is requested, the returned collation
                           <rfc2119>should</rfc2119> have the property that when two strings differ
                        only in the case of one or more characters, then a string in which the first
                        differing character is lower-case should precede a string in which the
                        corresponding character is title-case, which should in turn precede a string
                        in which the corresponding character is upper-case. When upper-first is
                        requested, the returned collation <rfc2119>should</rfc2119> have the
                        property that when two strings differ only in the case of one or more
                        characters, then a string in which the first differing character is
                        upper-case should precede a string in which the corresponding character is
                        title-case, which should in turn precede a string in which the corresponding
                        character is lower-case.</p><p>So, for example, if <code nobreak="false">lang="en"</code>, then <code nobreak="false">A a B b</code> are
                        sorted with <code nobreak="false">case-order="upper-first"</code> and <code nobreak="false">a A b B</code>
                        are sorted with <code nobreak="false">case-order="lower-first"</code>.</p><p>As a further example, if <code nobreak="false">lower-first</code> is requested, then a sorted sequence
                        might be “MacAndrew, macintosh, macIntosh, Macintosh, MacIntosh,
                        macintoshes, Macintoshes, McIntosh”. If <code nobreak="false">upper-first</code> is requested, the same
                        sequence would sort as “MacAndrew, MacIntosh, Macintosh, macIntosh,
                        macintosh, MacIntoshes, macintoshes, McIntosh”.</p></item></ulist><p>If none of the <code nobreak="false">collation</code>, <code nobreak="false">lang</code>, or
                     <code nobreak="false">case-order</code> attributes is present, the collation is chosen in an
                     <termref def="dt-implementation-defined"/> way. It is not
                     <rfc2119>required</rfc2119> that the default collation for sorting should be
                  the same as the <termref def="dt-default-collation">default collation</termref>
                  used when evaluating XPath expressions, as described in <specref ref="static-context"/> and <specref ref="default-collation-attribute"/>.</p><imp-def-feature id="idf-local-defaultsortcollation">If none of the
                     <code nobreak="false">collation</code>, <code nobreak="false">lang</code>, or <code nobreak="false">case-order</code>
                  attributes is present (on <elcode>xsl:sort</elcode>), the collation is chosen in
                  an <termref def="dt-implementation-defined"/> way.</imp-def-feature><note><p>It is usually appropriate, when sorting, to use a strong collation, that is,
                     one that takes account of secondary differences (accents) and tertiary
                     differences (case) between strings that are otherwise equal. A weak collation,
                     which ignores such differences, may be more suitable when comparing strings for
                     equality.</p><p>Useful background information on international sorting is provided in <bibref ref="UNICODE-TR10"/>. The <code nobreak="false">case-order</code> attribute may be
                     interpreted as described in section 6.6 of <bibref ref="UNICODE-TR10"/>.</p></note><p diff="add" at="2022-01-01">
                  The <code nobreak="false">collation</code>, <code nobreak="false">case-order</code>, and <code nobreak="false">lang</code> attributes are 
                  ignored when no string comparisons are performed during the sorting process; this 
                  includes the cases where (a) the sequences to be sorted are empty, (b) the sort 
                  keys are of a non-string type such as <code nobreak="false">xs:integer</code>, or (c) <code nobreak="false">data-type="number"</code> is 
                  specified. In these cases, an implementation may raise errors in the value 
                  of these attributes, but is not required to do so. As always, an implementation 
                  may issue warnings.
               </p></div3></div2><div2 id="creating-sorted-sequence"><head>Creating a Sorted Sequence</head><e:element-syntax xmlns:e="http://www.w3.org/1999/XSL/Spec/ElementSyntax" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" name="perform-sort">
      <e:in-category name="instruction"/>
      <e:attribute name="select" required="no">
         <e:data-type name="expression"/>
      </e:attribute>
      <e:sequence>
         <e:element repeat="one-or-more" name="sort"/>
         <e:model name="sequence-constructor"/>
      </e:sequence>
      <e:allowed-parents>
         <e:parent-category name="sequence-constructor"/>
      </e:allowed-parents>
   </e:element-syntax><p>The <elcode>xsl:perform-sort</elcode> instruction is used to return a <termref def="dt-sorted-sequence">sorted sequence</termref>.</p><p>The <termref def="dt-initial-sequence">initial sequence</termref> is obtained either
               by evaluating the <code nobreak="false">select</code> attribute or by evaluating the contained
               sequence constructor (but not both). If there is no <code nobreak="false">select</code> attribute and
               no sequence constructor then the <termref def="dt-initial-sequence">initial
                  sequence</termref> (and therefore, the <termref def="dt-sorted-sequence">sorted
                  sequence</termref>) is the empty sequence.</p><p>
               <error spec="XT" type="static" class="SE" code="1040"><p>It is a <termref def="dt-static-error">static error</termref> if an
                        <elcode>xsl:perform-sort</elcode> instruction with a <code nobreak="false">select</code>
                     attribute has any content other than <elcode>xsl:sort</elcode> and
                        <elcode>xsl:fallback</elcode> instructions.</p></error>
            </p><p>The result of the <elcode>xsl:perform-sort</elcode> instruction is the result of
               sorting its <termref def="dt-initial-sequence">initial sequence</termref> using its
               contained <termref def="dt-sort-key-specification">sort key
               specification</termref>.</p><example><head>Sorting a Sequence of Atomic Items</head><p>The following stylesheet function sorts a sequence of atomic items using the
                  value itself as the sort key.</p><eg xml:space="preserve" role="xslt-declaration xmlns:local='local'">&lt;xsl:function name="local:sort" 
          as="xs:anyAtomicType*"&gt;
  &lt;xsl:param name="in" as="xs:anyAtomicType*"/&gt;
  &lt;xsl:perform-sort select="$in"&gt;
    &lt;xsl:sort select="."/&gt;
  &lt;/xsl:perform-sort&gt;
&lt;/xsl:function&gt;</eg></example><example><head>Writing a Function to Perform a Sort</head><p>The following example defines a function that sorts books by price, and uses this
                  function to output the five books that have the lowest prices:</p><eg xml:space="preserve" role="non-xml">&lt;xsl:function name="bib:books-by-price" 
          as="schema-element(bib:book)*"&gt;
  &lt;xsl:param name="in" as="schema-element(bib:book)*"/&gt;
  &lt;xsl:perform-sort select="$in"&gt;
    &lt;xsl:sort select="xs:decimal(bib:price)"/&gt;
  &lt;/xsl:perform-sort&gt;
&lt;/xsl:function&gt;
   ...
   &lt;xsl:copy-of select="bib:books-by-price(//bib:book)
                             [position() = 1 to 5]"/&gt;

 </eg></example></div2><div2 id="sorted-iteration"><head>Processing a Sequence in Sorted Order</head><p>When used within <elcode>xsl:for-each</elcode> or
                  <elcode>xsl:apply-templates</elcode>, a <termref def="dt-sort-key-specification">sort key specification</termref> indicates that the sequence of items selected by
               that instruction is to be processed in sorted order, not in the order of the supplied
               sequence.</p><example><head>Processing Elements in Sorted Order</head><p>For example, suppose an employee database has the form</p><eg xml:space="preserve" role="xml">&lt;employees&gt;
  &lt;employee&gt;
    &lt;name&gt;
      &lt;given&gt;James&lt;/given&gt;
      &lt;family&gt;Clark&lt;/family&gt;
    &lt;/name&gt;
    ...
  &lt;/employee&gt;
&lt;/employees&gt;
</eg><p>Then a list of employees sorted by name could be generated using:</p><eg xml:space="preserve" role="xslt-declaration">&lt;xsl:template match="employees"&gt;
  &lt;ul&gt;
    &lt;xsl:apply-templates select="employee"&gt;
      &lt;xsl:sort select="name/family"/&gt;
      &lt;xsl:sort select="name/given"/&gt;
    &lt;/xsl:apply-templates&gt;
  &lt;/ul&gt;
&lt;/xsl:template&gt;

&lt;xsl:template match="employee"&gt;
  &lt;li&gt;
    &lt;xsl:value-of select="name/given"/&gt;
    &lt;xsl:text&gt; &lt;/xsl:text&gt;
    &lt;xsl:value-of select="name/family"/&gt;
  &lt;/li&gt;
&lt;/xsl:template&gt;</eg></example><p>When used within <elcode>xsl:for-each-group</elcode>, a <termref def="dt-sort-key-specification">sort key specification</termref> indicates the
               order in which the groups are to be processed. For the effect of
                  <elcode>xsl:for-each-group</elcode>, see <specref ref="grouping"/>. </p></div2></div1><div1 id="grouping"><head>Grouping</head><changes><change issue="571" PR="740" date="2023-09-26">
               A new attribute <code nobreak="false">xsl:for-each-group/@split-when</code> is available to
               give applications more complete control over how a sequence is partitioned
            </change><change issue="2051" PR="2123" date="2025-09-30">
               A new attribute <code nobreak="false">xsl:for-each-group/@merge-when</code> is available to
               give applications control to create groups based on clustering, overlap, and networks.
            </change></changes><p>The facilities described in this section are designed to allow items in a sequence to be
            grouped based on common values; for example it allows grouping of elements having the
            same value for a particular attribute, or elements with the same name, or elements with
            common values for any other <termref def="dt-expression">expression</termref>. Since
            grouping identifies items with duplicate values, the same facilities also allow
            selection of the distinct values in a sequence of items, that is, the elimination of
            duplicates.</p><note><p>Simple elimination of duplicates can also be achieved using the function
                  <xfunction>distinct-values</xfunction>: see <bibref ref="xpath-functions-40"/>.</p></note><p>In addition these facilities allow grouping based on sequential position, for example
            selecting groups of adjacent <code nobreak="false">para</code> elements. The facilities also provide an
            easy way to do fixed-size grouping, for example identifying groups of three adjacent
            nodes, which is useful when arranging data in multiple columns.</p><p>For each group of items identified, it is possible to evaluate a <termref def="dt-sequence-constructor">sequence constructor</termref> for the group. Grouping
            is nestable to multiple levels so that groups of distinct items can be identified, then
            from among the distinct groups selected, further sub-grouping of distinct items in the
            current group can be done. </p><p>It is also possible for one item to participate in more than one group.</p><note><p>Grouping can also be achieved by constructing a map. For example, 
            the function call <code nobreak="false">map:build(//employee, fn { department })</code> constructs a map
            in which employees are grouped by department.</p></note><div2 id="xsl-for-each-group"><head>The <code nobreak="false">xsl:for-each-group</code> Element</head><p>The <elcode>xsl:for-each-group</elcode> <termref def="dt-instruction">instruction</termref> 
               allows a flat sequence of items to be processed as a sequence
               of groups, allowing a number of criteria to be used to define the grouping. The
               instruction may be used anywhere within a <termref def="dt-sequence-constructor">sequence
               constructor</termref>.</p><e:element-syntax xmlns:e="http://www.w3.org/1999/XSL/Spec/ElementSyntax" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" name="for-each-group">
      <e:in-category name="instruction"/>
      <e:attribute name="select" required="yes">
         <e:data-type name="expression"/>
      </e:attribute>
      <e:attribute name="group-by" required="no">
         <e:data-type name="expression"/>
      </e:attribute>
      <e:attribute name="group-adjacent" required="no">
         <e:data-type name="expression"/>
      </e:attribute>
      <e:attribute name="group-starting-with" required="no">
         <e:data-type name="pattern"/>
      </e:attribute>
      <e:attribute name="group-ending-with" required="no">
         <e:data-type name="pattern"/>
      </e:attribute>
      <e:attribute name="split-when" required="no">
         <e:data-type name="expression"/>
      </e:attribute>
      <e:attribute name="merge-when" required="no">
         <e:data-type name="expression"/>
      </e:attribute>
      <e:attribute name="composite" default="'no'">
         <e:data-type name="boolean"/>
      </e:attribute>
      <e:attribute name="collation">
         <e:attribute-value-template>
            <e:data-type name="uri"/>
         </e:attribute-value-template>
      </e:attribute>
      <e:sequence>
         <e:element repeat="zero-or-more" name="sort"/>
         <e:model name="sequence-constructor"/>
      </e:sequence>
      <e:allowed-parents>
         <e:parent-category name="sequence-constructor"/>
      </e:allowed-parents>
   </e:element-syntax><p>The <code nobreak="false">select</code> attribute contains an
               <termref def="dt-expression">expression</termref> which is evaluated to produce a
               sequence, called the <termref def="dt-population"/>.</p><p>
               <termdef id="dt-group" term="group">The <elcode>xsl:for-each-group</elcode>
                  instruction allocates the items in an input sequence into <term>groups</term> of
                  items (that is, it establishes a collection of sequences) based either on common
                  values of a grouping key, or on a <termref def="dt-pattern">pattern</termref> that
                  the initial or final item in a group must
                  match.</termdef> The <termref def="dt-sequence-constructor">sequence
                  constructor</termref> that forms the content of the
                  <elcode>xsl:for-each-group</elcode> instruction is evaluated once for each of
               these groups.</p><p>
               <termdef id="dt-population" term="population">The sequence of items to be grouped,
                  which is referred to as the <term>population</term>, is determined by evaluating
                  the XPath <termref def="dt-expression">expression</termref> contained in the
                  <code nobreak="false">select</code> attribute.</termdef>
            </p><p>
               <termdef id="dt-population-order" term="population order">The population is treated
                  as a sequence; the order of items in this sequence is referred to as
                     <term>population order</term>.</termdef></p><p>A group is never empty. If the population is empty, the number of groups will be
               zero.</p><p>The assignment of items to groups depends on the <code nobreak="false">group-by</code>, 
                  <code nobreak="false">group-adjacent</code>, <code nobreak="false">group-starting-with</code>, 
                  <code nobreak="false">group-ending-with</code>, <phrase diff="add" at="2023-10-10"><code nobreak="false">split-when</code>,</phrase>
               <phrase diff="add" at="2025-07-27">and <code nobreak="false">merge-when</code></phrase> attributes. </p><p>
               <error spec="XT" type="static" class="SE" code="1080"><p>These <phrase diff="add" at="2025-07-23">six</phrase> attributes <error.extra>the <code nobreak="false">group-by</code>,
                     <code nobreak="false">group-adjacent</code>, <code nobreak="false">group-starting-with</code>, 
                     <code nobreak="false">group-ending-with</code>, 
                     <phrase diff="add" at="2023-10-10"><code nobreak="false">split-when</code>,</phrase>
                     <phrase diff="add" at="2023-10-10">and <code nobreak="false">merge-when</code></phrase> attributes of
                           <elcode>xsl:for-each-group</elcode>
                     </error.extra> are mutually exclusive: it is a <termref def="dt-static-error">static error</termref> 
                     if none of these attributes is present or if
                     more than one of them is present.</p></error>
            </p><p>
               <error spec="XT" type="static" class="SE" code="1090"><p>It is a <termref def="dt-static-error">static error</termref> to specify the
                        <code nobreak="false">collation</code> attribute or the
                           <code nobreak="false">composite</code> attribute if neither the
                        <code nobreak="false">group-by</code> attribute nor the <code nobreak="false">group-adjacent</code> attribute is
                     specified.</p></error>
            </p><p>
               <termdef id="dt-grouping-key" term="grouping key">If the
                     <code nobreak="false">group-by</code> or <code nobreak="false">group-adjacent</code> attributes is present,
                  then for each item in the <termref def="dt-population">population</termref> a set
                  of <term>grouping keys</term> is calculated, as follows: the expression contained
                  in the <code nobreak="false">group-by</code> or <code nobreak="false">group-adjacent</code> attribute is
                  evaluated; the result is atomized; and any <code nobreak="false">xs:untypedAtomic</code> items
                  are cast to <code nobreak="false">xs:string</code>. If
                        <code nobreak="false">composite="yes"</code> is specified, there is a single grouping key
                     whose value is the resulting sequence; otherwise, there is a set of grouping
                     keys, consisting of the distinct atomic items present in the result
                     sequence.</termdef>
            </p><p>When calculating grouping keys for an item in the population, the 
               <termref def="dt-expression">expression</termref> contained in the <code nobreak="false">group-by</code> 
               or <code nobreak="false">group-adjacent</code> attribute is evaluated with that 
               item as the <termref def="dt-context-item">context item</termref>, with its position in 
               <termref def="dt-population-order">population order</termref> as the 
               <termref def="dt-context-position">context position</termref>, and with the size of the
               population as the <termref def="dt-context-size">context size</termref>.</p><p>If the <code nobreak="false">group-by</code> attribute is present, and if
                  the <code nobreak="false">composite</code> attribute is omitted or takes the value
                  <code nobreak="false">no</code>, then an item in the population <rfc2119>may</rfc2119>
               have multiple grouping keys: that is, the <code nobreak="false">group-by</code> expression evaluates
               to a sequence, and each item in the sequence is treated as
                  a separate grouping key.  The item is included in as many groups as there
               are distinct grouping keys (which may be zero).</p><p>If the <code nobreak="false">group-adjacent</code> attribute is used, and
                  if the <code nobreak="false">composite</code> attribute is omitted or takes the value
                     <code nobreak="false">no</code>, then each item in the population
                  <rfc2119>must</rfc2119> have exactly one grouping key value.</p><p>
               <error spec="XT" type="type" class="TE" code="1100"><p>It is a <termref def="dt-type-error">type error</termref> if the result of
                     evaluating the <code nobreak="false">group-adjacent</code> expression is the empty sequence or a
                     sequence containing more than one item, unless
                           <code nobreak="false">composite="yes"</code> is specified.</p></error>
            </p><p diff="chg" at="2022-01-01">
               Atomic <termref def="dt-grouping-key">grouping keys</termref> are compared using
               the rules of the <function>distinct-values</function> function, using the relevant collation.
               The relevant collation is the collation specified as the 
               <termref def="dt-effective-value">effective value</termref> of the <code nobreak="false">collation</code>
               attribute, resolved if relative against the base URI of the
               <elcode>xsl:for-each-group</elcode> element; if there is no <code nobreak="false">collation</code>
               attribute then the <termref def="dt-default-collation">default collation</termref> is
               used. Given this collation, two grouping keys <var>K1</var> and <var>K2</var>
               are considered equal if <code nobreak="false">count(distinct-values(($K1, $K2), $collation)) = 1</code>.
            </p><p diff="add" at="2023-10-10">Composite grouping keys are equal if they contain the same number
            of items and the items are pairwise equal when compared according to the rules in the previous
            paragraph.</p><p>
               <error spec="XT" type="dynamic" class="DE" code="1110"><p>It is a <termref def="dt-dynamic-error"> dynamic error</termref> if the collation URI
                     specified to <elcode>xsl:for-each-group</elcode> (after resolving against the
                     base URI) is a collation that is not recognized by the implementation. (For
                     notes, <errorref class="DE" code="1035"/>.)</p></error>
            </p><p>For more information on collations, see <specref ref="collating-sequences"/>.</p><p>The way in which an <elcode>xsl:for-each-group</elcode> element is
               evaluated depends on which of the six group-defining attributes is present:</p><ulist><item><p>If the <code nobreak="false">group-by</code> attribute is present, the items in the <termref def="dt-population">population</termref> are examined, in population order.
                     For each item <var>J</var>, the expression in the <code nobreak="false">group-by</code>
                     attribute is evaluated to produce a sequence of zero or more <termref def="dt-grouping-key">grouping key</termref> values. If <code nobreak="false">composite="yes"</code> is specified, there will be a single
                        grouping key, which will in general be a sequence of zero or more atomic
                        items; otherwise, there will be zero or more grouping keys, each of which
                        will be a single atomic item. For each one of these <termref def="dt-grouping-key">grouping keys</termref>, if there is already a group
                     created to hold items having that grouping key value, <var>J</var> is appended to that group; otherwise a new group is
                     created for items with that grouping key value, and <var>J</var> becomes its
                     first member.</p><p>An item in the population may thus be appended to zero, one, or many groups. An item will never be
                        appended more than once to the same
                     group; if two or more grouping keys for the same item are equal, then the
                     duplicates are ignored. An <emph>item</emph> here means the item at a
                     particular position within the population—if the
                     population contains the same node at several different positions in the
                     sequence then a group may indeed contain duplicate nodes.</p><p>The number of groups will be the same as the number of distinct grouping key
                     values present in the <termref def="dt-population">population</termref>. </p><p diff="del" at="2022-01-01">If the population contains values of different numeric types that differ from
                     each other by small amounts, then the <code nobreak="false">eq</code> operator is not
                     transitive, because of rounding effects occurring during type promotion. The
                     effect of this is described in <specref ref="non-transitivity"/>.</p></item><item><p>If the <code nobreak="false">group-adjacent</code> attribute is present, the items in the
                        <termref def="dt-population">population</termref> are examined, in
                     population order. If an item has the same value for the <termref def="dt-grouping-key">grouping key</termref> as its preceding item within
                     the <termref def="dt-population">population</termref> (in <termref def="dt-population-order">population order</termref>), then it is appended to the same group as its preceding item;
                     otherwise a new group is created and the item becomes its first member.</p></item><item><p>If the <code nobreak="false">group-starting-with</code> attribute is present, then its value
                        <rfc2119>must</rfc2119> be a <nt xmlns:xlink="http://www.w3.org/1999/xlink" def="doc-xslt40-Pattern" xlink:type="simple">pattern</nt>. </p><p>The items in the <termref def="dt-population">population</termref> are examined in <termref def="dt-population-order">population order</termref>. If an item matches the pattern, or is the first item in the population, then a new group is
                     created and the item becomes its first
                     member. Otherwise, the item is appended to the same group as its preceding
                        item within the population.</p></item><item><p>If the <code nobreak="false">group-ending-with</code> attribute is present, then its value
                        <rfc2119>must</rfc2119> be a <nt xmlns:xlink="http://www.w3.org/1999/xlink" def="doc-xslt40-Pattern" xlink:type="simple">pattern</nt>. </p><p>The items in the <termref def="dt-population">population</termref> are examined in <termref def="dt-population-order">population order</termref>. If an item is the first item in the population, or if the previous item in the population matches the pattern, then a new group
                     is created and the item becomes its first
                     member. Otherwise, the item is appended to the same group as its preceding
                        item within the population.</p></item><item diff="add" at="2022-01-01"><p>If the <code nobreak="false">split-when</code> attribute is present, then its value
                     <rfc2119>must</rfc2119> be an expression.
                     This expression is evaluated once for every item in the <termref def="dt-population"/>
                     except the first. The context item is that item, the context position is its position
                     in the <termref def="dt-population"/>, and the context size is the size of the population.
                     The expression is supplied with two variables: <code nobreak="false">$group</code> is set to the 
                     contents of the current group being constructed, and <code nobreak="false">$next</code> is the next item in the population. 
                     If the <xtermref ref="dt-ebv" spec="XP40">effective boolean value</xtermref>
                     of the expression is <code nobreak="false">true</code>, then this
                  item forms the start of a new group; if it is <code nobreak="false">false</code>, the item is added to the existing
                  group.</p><ulist><item><p>The variable <code nobreak="false">$group</code> is implicitly declared, and <termref def="dt-shadows"/> any other variable
                           of the same name. Its name is in no namespace. Its scope is the <code nobreak="false">split-when</code>
                           expression, and its type is <code nobreak="false">item()+</code>.</p></item><item><p>The variable <code nobreak="false">$next</code> is implicitly declared, and <termref def="dt-shadows"/> any other variable
                           of the same name. Its name is in no namespace. Its scope is the <code nobreak="false">split-when</code>
                           expression, and its type is <code nobreak="false">item()</code>.</p></item></ulist><p>For example:</p><ulist><item><p><code nobreak="false">split-when="count($group) = 3"</code> starts a new
                     group whenever the existing group has exactly three members; that is, it partitions the
                     population into groups of size 3 (with the last group being smaller if necessary).</p></item><item><p><code nobreak="false">split-when="$next[self::h1]"</code> starts a new
                        group whenever an <code nobreak="false">h1</code> element is encountered. The effect is the
                     same as specifying <code nobreak="false">group-starting-with="h1"</code></p></item><item><p><code nobreak="false">split-when="foot($group)/@continued='no'"</code> starts a new
                        group immediately after any element having <code nobreak="false">@continued="no"</code>. The effect is the
                        same as specifying <code nobreak="false">group-ending-with="*[@continued='no']"</code></p></item><item><p><code nobreak="false">split-when="node-name($group[last()] != node-name($next)"</code> 
                        starts a new group whenever the name of an item differs from the name of the previous
                     item. The effect is the same as specifying <code nobreak="false">group-adjacent="node-name(.)"</code>.</p></item><item><p><code nobreak="false">split-when="foot($group)[self::hr] or $next[self::hr]"</code> 
                        starts a new group immediately before and immediately after every <code nobreak="false">hr</code>
                        element. (That is, <code nobreak="false">hr</code> elements become singleton groups.)</p></item><item><p><code nobreak="false">split-when="$next ne foot($group) + 1"</code> 
                        starts a new group whenever the current item is not equal to the previous item
                     plus one. For example <code nobreak="false">1, 2, 5, 6, 7, 10, 11</code> is grouped as <code nobreak="false">(1, 2), (5, 6, 7),
                     (10, 11)</code>.</p></item><item><p><code nobreak="false">split-when="sum($group/string-length()) gt 40"</code> starts a new
                     group when the sum of the string lengths of the items in the current group exceeds 40.</p></item><item><p><code nobreak="false">split-when="ends-with(foot($group), '.') and matches($next, '^\p{Lu}')"</code> 
                        starts a new group when the last item in the current group ends with <code nobreak="false">"."</code> and the
                        next item starts with a capital letter.</p></item><item><p><code nobreak="false">split-when="deep-equal(slice($group, -2 to -1), ('', ''))"</code> 
                        starts a new group after two consecutive zero-length strings.</p></item><item><p><code nobreak="false">split-when="count($group) gt 1 and head($group)/@name = foot($group)/@name"</code> 
                        starts a new group if the last item in the current group has the same value for <code nobreak="false">@name</code>
                        as the first item in that group (provided they are not the same item).</p></item></ulist></item><item><p>If the <code nobreak="false">merge-when</code> attribute is present, then its value
                        <rfc2119>must</rfc2119> be an expression that is a sequence comparator.
                        <termdef id="dt-sequence-comparator" term="">A <term>sequence
                           comparator</term> is an expression that evaluates two sequences of items
                        and results in a true or false value. </termdef></p><p>The sequence comparator is
                     supplied with two variables: <code nobreak="false">$group-a</code> and <code nobreak="false">$group-b</code>.
                     Each of these variables is implicitly declared, and <termref def="dt-shadows"/> any other variable
                           of the same name. Its name is in no namespace. Its scope is the <code nobreak="false">merge-when</code>
                           expression, and its type is <code nobreak="false">item()+</code>.</p><p>The sequence comparator is evaluated not item by item (as with
                        <code nobreak="false">split-when</code>) but group by group. The context item is <termref def="dt-absent">absent</termref>, the context position is the position of
                     the first sequence (<code nobreak="false">$group-a</code>) within the sequence of groups being
                     constructed, and the context size is the number of groups at the moment of
                     evaluation.</p><p>The process begins by creating singleton groups. For each item in the <termref def="dt-population">population</termref> a group is created, with that
                     item's position as its grouping key, and the item as its only member.</p><p>After the groups are created, they are evaluated pairwise against the <termref def="dt-sequence-comparator">sequence comparator</termref>. The pairwise
                     comparison begins with the first two groups, then the first and third groups,
                     and so on until the first and last groups, then pairwise comparison moves to
                     the second and third groups, then the second and fourth groups, and so forth.
                     Pairwise comparison proceeds until the next-to-last and last groups are
                     evaluated.</p><p><code nobreak="false">$group-a</code> is set to the items in the first group in a pair of 
                     groups, <var>G1</var>, and <code nobreak="false">$group-b</code> to the second group, 
                     <var>G2</var>.</p><p>If the <xtermref ref="dt-ebv" spec="XP40">effective boolean value</xtermref> of
                     the sequence comparator is <code nobreak="false">true</code>, then all items in <var>G2</var>
                     are merged with the items in <var>G1</var>, preserving original sequence order,
                     and the grouping keys of <var>G2</var> are merged with those of <var>G1</var>,
                     sorted in ascending order. The process of merging two groups is identical to
                     the process described in <specref ref="merging"/> to merge sequences. Pairwise
                     comparison then restarts from the beginning with the first pair of groups, as
                     described above. </p><p>The process is repeated until it is the case that there is no pair of groups
                     for which the <termref def="dt-sequence-comparator">sequence
                        comparator</termref> evaluates to <code nobreak="false">true</code>, or there is only one
                     group.</p><p>Every item in the population will be appended to exactly one group. </p><p>Unlike other grouping methods, a group created by <code nobreak="false">merge-when</code> may
                     have more than one grouping key. Although those grouping keys are not
                     significant for the semantics of the grouping operation, they can be used to
                     examine the original population, and they are useful for the merge
                     operation.</p><p><code nobreak="false">merge-when</code> is most effective for building clusters or
                     networks. For example:</p><ulist><item><p>
                           <code nobreak="false">merge-when="$group-a/(@id | is-related-to) = $group-b/(@id |
                              is-related-to)"</code> creates groups of elements. In a group with
                           more than one item, each item has at least one other item that it relates
                           to, or that relates to the same item it relates to. That is, each group
                           represents a kind of network cluster.</p></item><item><p>Suppose we have elements containing text units where word tokens of
                           significance are wrapped in children <code nobreak="false">tok</code> elements.
                              <code nobreak="false">merge-when="every $a in $group-a, $b in $group-b satisfies
                              count($a/tok[. = $b/tok]) ge 3"</code> creates groups of possibly
                           related texts. In groups of more than one item, any pair of texts has
                           at least three common word-tokens. </p></item><item><p><code nobreak="false">merge-when="some $a in $group-a, $b in $group-b satisfies
                              count($a/tok[. = $b/tok]) ge 3"</code> creates groups of related
                           texts, likely less cohesive than in the previous example. In groups of
                           more than one item, every text has at least one other text with which it
                           has three word-tokens in common. 
                        </p></item><item><p><code nobreak="false">merge-when="not($group-a = $group-b)"</code> creates maximal groups
                           of distinct values. For example, <code nobreak="false">4, 1, 5, 1, 9, 4, 1</code> is
                           grouped as <code nobreak="false">4, 1, 5, 9</code> (with grouping keys <code nobreak="false">1, 2, 3,
                              5</code>), <code nobreak="false">1, 4</code> (with grouping keys <code nobreak="false">4, 6</code>),
                           and <code nobreak="false">1</code> (with grouping key <code nobreak="false">7</code>). Note, the first
                           group is always the result of the <xfunction>distinct-values</xfunction>
                           function, and the final group always contains the items that appear most
                           frequently in the original population. </p></item><item><p> In <code nobreak="false">merge-when="count($group-a) le 3 and
                              count(distinct-values(($group-a, $group-b) ! node-name(.))) eq 1"</code> no
                           group has more than three items. Within each group, every item has the
                           same node name. The effect is the same as specifying
                           <code nobreak="false">group-by="node-name(.)"</code> then subgrouping with 
                           <code nobreak="false">split-when="count($group) = 3"</code>.</p></item><item><p><code nobreak="false">merge-when="some $a in $group-a, $b in $group-b satisfies
                              tokenize($a/@class) = tokenize($b/@class)"</code> creates groups of
                           elements. In a group with multiple items, every item has at least one
                           other item that has at least one of its tokens in <code nobreak="false">@class</code>.</p></item><item><p><code nobreak="false">merge-when="some $a in $group-a, $b in $group-b satisfies abs($a -
                              $b) le 2"</code> creates groups of numerals. Each numeral has at least
                           one other numeral where the two differ by two or less. For example,
                              <code nobreak="false">3, 9, 4, 1, 10, 6</code> is grouped as <code nobreak="false">(3, 4, 1, 6)</code>
                           (with grouping keys <code nobreak="false">1, 3, 4, 6</code>) and <code nobreak="false">(9, 10)</code> (with
                           grouping keys <code nobreak="false">2, 5</code>).</p></item><item><p><code nobreak="false">merge-when="some $a in $group-a, $b in $group-b satisfies abs($a -
                              $b) le xs:dayTimeDuration('PT2H')"</code> creates groups of time
                           values. Within groups of more than one item, each time value has at least
                           one other time value that is two hours or less apart. For example,
                              <code nobreak="false">xs:time("11:12:00Z"), xs:time("13:24:55Z"),
                              xs:time("09:44:10Z"), xs:time("14:09:22Z"),
                              xs:time("08:16:30Z")</code> is grouped as <code nobreak="false">(xs:time("11:12:00Z"),
                              xs:time("09:44:10Z"), xs:time("08:16:30Z"))</code> (with grouping keys
                              <code nobreak="false">1, 3, 5</code>) and <code nobreak="false">(xs:time("13:24:55Z"),
                              xs:time("14:09:22Z"))</code> (with grouping keys <code nobreak="false">2,
                           4</code>).</p></item><item><p>
                           <code nobreak="false">merge-when="every $a in $group-a, $b in $group-b satisfies
                              (string-to-codepoints($a) = string-to-codepoints($b))"</code> creates
                           groups of strings. In groups with more than one member, each member
                           shares at least one codepoint with every other member. For example,
                              <code nobreak="false">("animal", "bison", "cat", "dog", "zebra")</code> is grouped as
                              <code nobreak="false">("animal", "bison", "zebra")</code> (linking letters are a, i,
                           n, and b), <code nobreak="false">("cat")</code> (although it shares letter a with
                           "animal," the group has already been merged with "bison," which has no
                           common letter with "cat"), and <code nobreak="false">("dog")</code>. The grouping keys
                           are <code nobreak="false">1, 2, 5</code>, <code nobreak="false">3</code>, and <code nobreak="false">4</code>,
                           respectively.</p></item></ulist></item></ulist><p>In all cases the order of items within each group is predictable,
               and reflects the original <termref def="dt-population-order">population
                  order</termref>, in that the items are processed in population order and each item
               is appended at the end of zero or more groups.</p><note><p>As always, a different algorithm may be used if it achieves the same effect.</p></note><p>
               <termdef id="dt-initial-item" term="initial item">For each <termref def="dt-group">group</termref>, the item within the group that is first in <termref def="dt-population-order">population order</termref> is known as the
                     <term>initial item</term> of the group.</termdef>
            </p><p>The <termref def="dt-sequence-constructor"/> contained in the
                  <elcode>xsl:for-each-group</elcode> element is evaluated once for each of the
                  <termref def="dt-group">groups</termref>, in <termref def="dt-processing-order">processing order</termref>. The sequences that result are concatenated, in
                  <termref def="dt-processing-order">processing order</termref>, to form the result
               of the <elcode>xsl:for-each-group</elcode> element. Within the <termref def="dt-sequence-constructor">sequence constructor</termref>, the <termref def="dt-context-item">context item</termref> is the <termref def="dt-initial-item">initial item</termref> of the relevant group, the <termref def="dt-context-position">context position</termref> is the position of this
                  group in the <termref def="dt-processing-order">processing order</termref> of the groups, and the <termref def="dt-context-size">context size</termref> is the number of groups This has the effect
               that within the <termref def="dt-sequence-constructor"/>, a call on
                  <code nobreak="false">position()</code> takes successive values <code nobreak="false">1, 2, ... last()</code>.</p></div2><div2 id="information-about-group"><head>Accessing Information about the Current Group Value</head><p>Two pieces of information are available during the processing of each group (that is,
               while evaluating the sequence constructor contained in the
                  <elcode>xsl:for-each-group</elcode> instruction, and also while evaluating the
               sort key of a group as expressed by the <code nobreak="false">select</code> attribute or sequence
               constructor of an <elcode>xsl:sort</elcode> child of the
                  <elcode>xsl:for-each-group</elcode> element):</p><ulist><item><p><termdef id="dt-current-group" term="current group">The <term>current
                           group</term> is the <termref def="dt-group">group</termref> itself, as a
                        sequence of items</termdef>.</p></item><item><p><termdef id="dt-current-grouping-key" term="current grouping key">The
                           <term>current grouping key</term> is a single atomic item, or in the
                        case of a composite key, a sequence of atomic items, containing the
                           <termref def="dt-grouping-key"/> of the items in the <termref def="dt-current-group"/>.</termdef></p></item></ulist><p>Information about the <termref def="dt-current-group"/>
               and the <termref def="dt-current-grouping-key"/> is held in the dynamic context, and
               is available using the <function>current-group</function> and
                  <function>current-grouping-key</function> functions respectively.</p><p>In XSLT 2.0, the <termref def="dt-current-group"/> and the
                  <termref def="dt-current-grouping-key"/> were passed unchanged through calls of
                  <elcode>xsl:apply-templates</elcode> and <elcode>xsl:call-template</elcode>, and
               also <elcode>xsl:apply-imports</elcode> and <elcode>xsl:next-match</elcode>. This
               behavior is retained in XSLT 3.0 except in the case where streaming is in use:
               specifically, if the <elcode>xsl:apply-templates</elcode>,
                  <elcode>xsl:call-template</elcode>, <elcode>xsl:apply-imports</elcode>, or
                  <elcode>xsl:next-match</elcode> instruction occurs within a <xtermref spec="SG40" ref="dt-declared-streamable"/> construct (typically, within an
                  <elcode>xsl:source-document</elcode> instruction, or within a streamable <termref def="dt-template-rule"/>), then the current group and current grouping key are set
               to <termref def="dt-absent"/> in the called template. The reason for this is to allow
               the streamability of an <elcode>xsl:for-each-group</elcode> instruction to be
               assessed statically, as described in <xspecref spec="SG40" ref="streamability-xsl-for-each-group"/>.</p><div3 id="func-current-group"><head>fn:current-group</head><changes><change issue="407" PR="2274" date="2026-01-06">In XSLT 4.0, the function item <code nobreak="false">current-group#0</code> retains the value of the current
         group within its captured context.</change></changes><glist><gitem><label>Summary</label><def><p>Returns the group currently being processed by an <elcode>xsl:for-each-group</elcode>
             instruction.</p></def></gitem><gitem><label>Signature</label><def><example role="signature"><proto isOp="no" prefix="fn" name="current-group" return-type="item()*" returnEmptyOk="no" returnSeq="no" returnVaries="no" isSchema="no" isDatatype="no" isSpecial="no"/></example></def></gitem><gitem><label>Properties</label><def><p>This function is <xtermref spec="FO40" ref="dt-deterministic">deterministic</xtermref>, <xtermref spec="FO40" ref="dt-context-dependent">context-dependent</xtermref>,  and <xtermref spec="FO40" ref="dt-focus-independent">focus-independent</xtermref>. </p></def></gitem><gitem><label>Rules</label><def><p> The evaluation context for XPath <termref def="dt-expression">expressions</termref>
            includes a component called the <termref def="dt-current-group">current group</termref>,
            which is a sequence. </p><p>The function <function>current-group</function> returns the sequence
            of items making up the current group.</p><p>The current group is bound during evaluation of the
               <elcode>xsl:for-each-group</elcode> instruction. If no
               <elcode>xsl:for-each-group</elcode> instruction is being evaluated, the current group
            will be <termref def="dt-absent"/>: that is, any reference to it will cause a dynamic
            error.</p><p>The effect of <termref def="dt-invocation-construct">invocation constructs</termref> on the <termref def="dt-current-group"/> is as
            follows:</p><ulist><item><p>If the <termref def="dt-invocation-construct"/> is contained within a <xtermref spec="SG40" ref="dt-declared-streamable"/>
                  <xtermref spec="SG40" ref="dt-construct"/> (for example, if it is within an
                     <elcode>xsl:source-document</elcode> instruction with the attribute <code nobreak="false">streamable="yes"</code>, 
                  or within a streamable template), then the
                  invocation construct sets the current group to <termref def="dt-absent"/>. In this
                  situation the scope of the current group is effectively static; it can only be
                  referenced within the body of the <elcode>xsl:for-each-group</elcode> instruction
                  to which it applies.</p></item><item><p>If the <termref def="dt-invocation-construct"/> is a (static or dynamic) function
                  call, then the invocation construct sets the current group to <termref def="dt-absent"/>.</p></item><item><p>Otherwise the <termref def="dt-invocation-construct"/> leaves the current group
                  unchanged. In this situation the scope of the current group is effectively
                  dynamic: it can be referenced within called templates and attribute sets.</p></item></ulist><p>The current group is initially <termref def="dt-absent"/>
            during the evaluation of global variables and stylesheet parameters, during the
         evaluation of the <code nobreak="false">use</code> attribute or contained sequence constructor of <elcode>xsl:key</elcode>,
         and during the evaluation of the <code nobreak="false">initial-value</code> attribute of <elcode>xsl:accumulator</elcode>
         and the <code nobreak="false">select</code> attribute of contained sequence constructor of <elcode>xsl:accumulator-rule</elcode>.</p></def></gitem><gitem><label>Error Conditions</label><def><p>
            <error spec="XT" type="static" class="SE" code="1060"><p>It is a <termref def="dt-static-error">static error</termref> if the
                     <function>current-group</function> function is used within a <termref def="dt-pattern">pattern</termref>.</p></error>
         </p><p>
            <error spec="XT" type="dynamic" class="DE" code="1061"><p>It is a <termref def="dt-dynamic-error">dynamic error</termref> if the
                     <function>current-group</function> function is used when the current group is
                     <termref def="dt-absent">absent</termref>
                  , or when it is invoked in the course of evaluating a
                     pattern. The error <rfc2119>may</rfc2119> be reported statically if it
                  can be detected statically.</p></error>
         </p></def></gitem></glist></div3><div3 id="func-current-grouping-key"><head>fn:current-grouping-key</head><changes><change issue="407" PR="2274" date="2026-01-06">In XSLT 4.0, the function item <code nobreak="false">current-grouping-key#0</code> retains the value of the current
         grouping key within its captured context.</change></changes><glist><gitem><label>Summary</label><def><p>Returns the grouping key of the group currently being processed using the
               <elcode>xsl:for-each-group</elcode>
             instruction.</p></def></gitem><gitem><label>Signature</label><def><example role="signature"><proto isOp="no" prefix="fn" name="current-grouping-key" return-type="xs:anyAtomicType*" returnEmptyOk="no" returnSeq="no" returnVaries="no" isSchema="no" isDatatype="no" isSpecial="no"/></example></def></gitem><gitem><label>Properties</label><def><p>This function is <xtermref spec="FO40" ref="dt-deterministic">deterministic</xtermref>, <xtermref spec="FO40" ref="dt-context-dependent">context-dependent</xtermref>,  and <xtermref spec="FO40" ref="dt-focus-independent">focus-independent</xtermref>. </p></def></gitem><gitem><label>Rules</label><def><p> The evaluation context for XPath <termref def="dt-expression">expressions</termref>
            includes a component called the <termref def="dt-current-grouping-key">current grouping
               key</termref>, which is a sequence of atomic
               items. The current grouping key is the <termref def="dt-grouping-key">grouping key</termref> 
            shared in common by all the items within the <termref def="dt-current-group">current group</termref>. </p><p>The function <function>current-grouping-key</function> returns the <termref def="dt-current-grouping-key">current grouping key</termref>.</p><p>The current grouping key is bound during evaluation of an
               <elcode>xsl:for-each-group</elcode> instruction that has a <code nobreak="false">group-by</code>, 
               <code nobreak="false">group-adjacent</code>, or <code nobreak="false">merge-when</code> attribute. If <phrase>no
                  <elcode>xsl:for-each-group</elcode> instruction is being evaluated, the current
               grouping key will be <termref def="dt-absent"/>, which means that any reference to it
               causes a dynamic error. The current grouping key is also set to <termref def="dt-absent"/> during the evaluation of an <elcode>xsl:for-each-group</elcode>
               instruction with a <code nobreak="false">group-starting-with</code>, <code nobreak="false">group-ending-with</code>,
               or <code nobreak="false">split-when</code> attribute</phrase>.</p><p>The effect of <termref def="dt-invocation-construct">invocation constructs</termref> on the <termref def="dt-current-grouping-key"/> is
            as follows:</p><ulist><item><p>If the <termref def="dt-invocation-construct"/> is contained within a <xtermref spec="SG40" ref="dt-declared-streamable"/>
                  <xtermref spec="SG40" ref="dt-construct"/> (for example, if it is within an
                     <elcode>xsl:source-document</elcode> instruction with the attribute <code nobreak="false">streamable="yes"</code>, 
                  or within a streamable template), then the
                  invocation construct sets the current grouping key to <termref def="dt-absent"/>.
                  In this situation the scope of the current group is effectively static; it can
                  only be referenced within the body of the <elcode>xsl:for-each-group</elcode>
                  instruction to which it applies.</p></item><item><p>If the <termref def="dt-invocation-construct"/> is a (static or dynamic) function
                  call, then the invocation construct sets the current grouping key to <termref def="dt-absent"/>.</p></item><item><p>Otherwise the <termref def="dt-invocation-construct"/> leaves the current grouping
                  key unchanged. In this situation the scope of the current group is effectively
                  dynamic: it can be referenced within called templates and attribute sets.</p></item></ulist><p>The current grouping key is initially <termref def="dt-absent"/>
            during the evaluation of global variables and stylesheet parameters, during the
            evaluation of the <code nobreak="false">use</code> attribute or contained sequence constructor of <elcode>xsl:key</elcode>,
            and during the evaluation of the <code nobreak="false">initial-value</code> attribute of <elcode>xsl:accumulator</elcode>
            and the <code nobreak="false">select</code> attribute of contained sequence constructor of <elcode>xsl:accumulator-rule</elcode>.</p><p>While an <elcode>xsl:for-each-group</elcode> instruction with a <code nobreak="false">group-by</code> or
               <code nobreak="false">group-adjacent</code> attribute is being evaluated, the
            <termref def="dt-current-grouping-key">current grouping key</termref> will be a single atomic
            item if <code nobreak="false">composite="no"</code> is specified (explicitly
               or implicitly), or a sequence of atomic items if <code nobreak="false">composite="yes"</code> is
               specified.
         </p><p>While an <elcode>xsl:for-each-group</elcode> instruction with a <code nobreak="false">merge-when</code> 
            attribute is being evaluated, the
            <termref def="dt-current-grouping-key">current grouping key</termref> will be a sequence of 
            integers, indicating the positions of the items within the original sequence.
         </p><p>At other times, the current grouping key will be <termref def="dt-absent">absent</termref>.</p><p>The <termref def="dt-grouping-key">grouping keys</termref> of
               all items in a group are not necessarily identical. For example, one might be an
                  <code nobreak="false">xs:float</code> while another is a numerically equal
               <code nobreak="false">xs:decimal</code>. The <function>current-grouping-key</function>
            function returns the grouping key of the <termref def="dt-initial-item">initial item</termref> in the group, after atomization and
            casting of <code nobreak="false">xs:untypedAtomic</code> items to <code nobreak="false">xs:string</code>.</p><p>The function takes no arguments.</p></def></gitem><gitem><label>Error Conditions</label><def><p>
            <error spec="XT" type="static" class="SE" code="1070"><p>It is a <termref def="dt-static-error">static error</termref> if the
                     <function>current-grouping-key</function> function is used within a <termref def="dt-pattern">pattern</termref>.</p></error>
         </p><p>
            <error spec="XT" type="dynamic" class="DE" code="1071"><p>It is a <termref def="dt-dynamic-error">dynamic error</termref> if the
                     <function>current-grouping-key</function> function is used when the current
                  grouping key is <termref def="dt-absent">absent</termref>, or when it is invoked in the course of evaluating a pattern.
                  The error <rfc2119>may</rfc2119> be reported statically if it can be detected
                  statically.</p></error>
         </p></def></gitem></glist></div3></div2><div2 id="order-of-groups"><head>Ordering among Groups</head><p>
               <termdef id="dt-first-appearance" term="order of first appearance">There is a total ordering among <termref def="dt-group">groups</termref> referred to as the <term>order of first appearance</term>. A
                  group <var>G</var> is defined to precede a group <var>H</var> in order of first
                  appearance if the <termref def="dt-initial-item">initial item</termref> of
                     <var>G</var> precedes the initial item of <var>H</var> in population order. If
                  two groups <var>G</var> and <var>H</var> have the same initial item (because the
                  item is in both groups) then <var>G</var> precedes <var>H</var> if the <termref def="dt-grouping-key">grouping key</termref> of <var>G</var> precedes the
                  grouping key of <var>H</var> in the sequence that results from evaluating the
                     <code nobreak="false">group-by</code> expression of this initial item.</termdef>
            </p><p>
               <termdef id="dt-processing-order" term="processing order">There is another total ordering among groups referred to as
                     <term>processing order</term>. If group <var>R</var> precedes group
                     <var>S</var> in processing order, then in the result sequence returned by the
                     <elcode>xsl:for-each-group</elcode> instruction the items generated by
                  processing group <var>R</var> will precede the items generated by processing group
                     <var>S</var>.</termdef>
            </p><p>If there are no <elcode>xsl:sort</elcode> elements immediately within the
                  <elcode>xsl:for-each-group</elcode> element, the <termref def="dt-processing-order">processing order</termref> of the <termref def="dt-group">groups</termref> is the <termref def="dt-first-appearance">order of
                  first appearance</termref>.</p><p>Otherwise, the <elcode>xsl:sort</elcode> elements immediately within the
                  <elcode>xsl:for-each-group</elcode> element define the processing order of the
                  <termref def="dt-group">groups</termref> (see <specref ref="sorting"/>). They do
               not affect the order of items within each group. Multiple <termref def="dt-sort-key-component">sort key components</termref> are allowed, and are
               evaluated in major-to-minor order. If two groups have the same values for all their
               sort key components, they are processed in <termref def="dt-first-appearance"/> if
               the <termref def="dt-sort-key-specification">sort key specification</termref> is
                  <termref def="dt-stable">stable</termref>, otherwise in an <termref def="dt-implementation-dependent">implementation-dependent</termref> order.</p><p>The <code nobreak="false">select</code>
               <termref def="dt-expression">expression</termref> of an <elcode>xsl:sort</elcode>
               element is evaluated once for each <termref def="dt-group">group</termref>. During
               this evaluation, the <termref def="dt-context-item">context item</termref> is the
                  <termref def="dt-initial-item">initial item</termref> of the group, the <termref def="dt-context-position">context position</termref> is the position of this item
               within the set of initial items (that is, one item for each group in the <termref def="dt-population">population</termref>) in <termref def="dt-population-order">population order</termref>, the <termref def="dt-context-size">context
                  size</termref> is the number of groups, the <termref def="dt-current-group"/> is
               the group whose <termref def="dt-sort-key-value">sort key value</termref> is being
               determined, and the <termref def="dt-current-grouping-key"/> is the grouping key for
               that group. If the <elcode>xsl:for-each-group</elcode> instruction uses the
               <code nobreak="false">group-starting-with</code>, <code nobreak="false">group-ending-with</code><phrase diff="add" at="2023-10-10">,
                  or <code nobreak="false">split-when</code></phrase>
               attributes, then the <termref def="dt-current-grouping-key"/> is <termref def="dt-absent"/>.</p><example><head>Sorting Groups</head><p>For example, this means that if the <termref def="dt-grouping-key">grouping
                     key</termref> is <code nobreak="false">@category</code>, you can sort the groups in order of
                  their grouping key by writing <code nobreak="false">&lt;xsl:sort
                     select="current-grouping-key()"/&gt;</code>; or you can sort the groups in
                  order of size by writing <code nobreak="false">&lt;xsl:sort
                     select="count(current-group())"/&gt;</code>
               </p></example></div2><div2 id="grouping-examples"><head>Examples of Grouping</head><example><head>Grouping Nodes based on Common Values</head><p>The following example groups a list of nodes based on common values. The resulting
                  groups are numbered and sorted, and a
                  total is calculated for each group. </p><p>Source XML document:</p><eg xml:space="preserve" role="xml">&lt;cities&gt;
  &lt;city name="Milano"  country="Italia"      pop="5"/&gt;
  &lt;city name="Paris"   country="France"      pop="7"/&gt;
  &lt;city name="München" country="Deutschland" pop="4"/&gt;
  &lt;city name="Lyon"    country="France"      pop="2"/&gt;
  &lt;city name="Venezia" country="Italia"      pop="1"/&gt;
&lt;/cities&gt;</eg><p>More specifically, the aim is to produce a four-column table, containing one row
                  for each distinct country. The four columns are to contain first, a sequence
                  number giving the number of the row; second, the name of the country, third, a
                  comma-separated alphabetical list of the city names within that country, and
                  fourth, the sum of the <code nobreak="false">pop</code> attribute for the cities in that
                  country.</p><p>Desired output:</p><eg xml:space="preserve" role="xml">&lt;table&gt;
  &lt;tr&gt;
    &lt;th&gt;Position&lt;/th&gt;
    &lt;th&gt;Country&lt;/th&gt;
    &lt;th&gt;List of Cities&lt;/th&gt;
    &lt;th&gt;Population&lt;/th&gt;
  &lt;/tr&gt;
  &lt;tr&gt;
    &lt;td&gt;1&lt;/td&gt;
    &lt;td&gt;Italia&lt;/td&gt;
    &lt;td&gt;Milano, Venezia&lt;/td&gt;
    &lt;td&gt;6&lt;/td&gt;
  &lt;/tr&gt;
  &lt;tr&gt;
    &lt;td&gt;2&lt;/td&gt;
    &lt;td&gt;France&lt;/td&gt;
    &lt;td&gt;Lyon, Paris&lt;/td&gt;
    &lt;td&gt;9&lt;/td&gt;
  &lt;/tr&gt;  
  &lt;tr&gt;
    &lt;td&gt;3&lt;/td&gt;
    &lt;td&gt;Deutschland&lt;/td&gt;
    &lt;td&gt;München&lt;/td&gt;
    &lt;td&gt;4&lt;/td&gt;
  &lt;/tr&gt;  
&lt;/table&gt;</eg><p>Solution:</p><eg xml:space="preserve" role="xml">&lt;table xsl:version="3.0" xsl:expand-text="yes"
        xmlns:xsl="http://www.w3.org/1999/XSL/Transform"&gt;
  &lt;tr&gt;
    &lt;th&gt;Position&lt;/th&gt;
    &lt;th&gt;Country&lt;/th&gt;
    &lt;th&gt;City List&lt;/th&gt;
    &lt;th&gt;Population&lt;/th&gt;
  &lt;/tr&gt;
  &lt;xsl:for-each-group select="cities/city" group-by="@country"&gt;
    &lt;tr&gt;
      &lt;td&gt;{position()}&lt;/td&gt;
      &lt;td&gt;{current-grouping-key()}&lt;/td&gt;
      &lt;td&gt;
        &lt;xsl:for-each select="current-group()/@name"&gt;
          &lt;xsl:sort select="."/&gt;
          &lt;xsl:if test="position() ne 1"&gt;, &lt;/xsl:if&gt;
          {.}
        &lt;/xsl:for-each&gt;  
      &lt;/td&gt;
      &lt;td&gt;{sum(current-group()/@pop)}&lt;/td&gt;
    &lt;/tr&gt;
  &lt;/xsl:for-each-group&gt;
&lt;/table&gt;</eg></example><example><head>A Composite Grouping Key</head><p>Sometimes it is necessary to use a composite grouping key: for example, suppose
                  the source document is similar to the one used in the previous examples, but
                  allows multiple entries for the same country and city, such as:</p><eg xml:space="preserve" role="xml">&lt;cities&gt;
  &lt;city name="Milano"  country="Italia"  year="1950"   pop="5.23"/&gt;
  &lt;city name="Milano"  country="Italia"  year="1960"   pop="5.29"/&gt;  
  &lt;city name="Padova"  country="Italia"  year="1950"   pop="0.69"/&gt;
  &lt;city name="Padova"  country="Italia"  year="1960"   pop="0.93"/&gt;    
  &lt;city name="Paris"   country="France"  year="1951"   pop="7.2"/&gt;
  &lt;city name="Paris"   country="France"  year="1961"   pop="7.6"/&gt;
&lt;/cities&gt;</eg><p>Now suppose we want to list the average value of <code nobreak="false">@pop</code> for each
                  (country, name) combination. One way to handle this is to concatenate the parts of
                  the key, for example <code nobreak="false">&lt;xsl:for-each-group select="concat(@country, '/',
                     @name)"&gt;</code>. A second solution is to nest one
                     <elcode>xsl:for-each-group</elcode> element directly inside another. XSLT 3.0
                  introduces a third option, which is to define the grouping key as composite:</p><eg xml:space="preserve" role="xslt-instruction">
&lt;xsl:for-each-group select="cities/city" 
                    group -by="@name, @country" 
                    composite="yes"
                    expand-text="yes"&gt;
  &lt;p&gt;{current-grouping-key()[1]}, {current-grouping-key()[2]}: {avg(current-group()/@pop)"/&gt;
  &lt;/p&gt;
&lt;/xsl:for-each-group&gt;</eg></example><example><head>Identifying a Group by its Initial Element</head><p>The next example identifies a group not by the presence of a common value, but
                  rather by adjacency in document order. A group consists of an <code nobreak="false">h2</code>
                  element, followed by all the <code nobreak="false">p</code> elements up to the next
                     <code nobreak="false">h2</code> element.</p><p>Source XML document:</p><eg xml:space="preserve" role="xml">&lt;body&gt;
  &lt;h2&gt;Introduction&lt;/h2&gt;
  &lt;p&gt;XSLT is used to write stylesheets.&lt;/p&gt;
  &lt;p&gt;XQuery is used to query XML databases.&lt;/p&gt;
  &lt;h2&gt;What is a stylesheet?&lt;/h2&gt;
  &lt;p&gt;A stylesheet is an XML document used to define a transformation.&lt;/p&gt;
  &lt;p&gt;Stylesheets may be written in XSLT.&lt;/p&gt;
  &lt;p&gt;XSLT 2.0 introduces new grouping constructs.&lt;/p&gt;
&lt;/body&gt;</eg><p>Desired output:</p><eg xml:space="preserve" role="xml">&lt;chapter&gt;
  &lt;section title="Introduction"&gt;
    &lt;para&gt;XSLT is used to write stylesheets.&lt;/para&gt;
    &lt;para&gt;XQuery is used to query XML databases.&lt;/para&gt;
  &lt;/section&gt; 
  &lt;section title="What is a stylesheet?"&gt;
    &lt;para&gt;A stylesheet is used to define a transformation.&lt;/para&gt;
    &lt;para&gt;Stylesheets may be written in XSLT.&lt;/para&gt;
    &lt;para&gt;XSLT 2.0 introduces new grouping constructs.&lt;/para&gt;
  &lt;/section&gt;
&lt;/chapter&gt;</eg><p>Solution:</p><eg xml:space="preserve" role="xslt-declaration">&lt;xsl:template match="body"&gt;
  &lt;chapter&gt;
    &lt;xsl:for-each-group select="*" group-starting-with="h2"&gt;
      &lt;section title="{self::h2}"&gt;
        &lt;xsl:for-each select="current-group()[self::p]"&gt;
          &lt;para&gt;&lt;xsl:value-of select="."/&gt;&lt;/para&gt;
        &lt;/xsl:for-each&gt; 
      &lt;/section&gt;
    &lt;/xsl:for-each-group&gt;
  &lt;/chapter&gt;
&lt;/xsl:template&gt;</eg><p>The use of <code nobreak="false">title="{self::h2}"</code> rather than <code nobreak="false">title="{.}"</code> is
                  to handle the case where the first element is not an <code nobreak="false">h2</code> element.</p></example><example><head>Identifying a Group by its Final Element</head><p>The next example illustrates how a group of related elements can be identified by
                  the last element in the group, rather than the first. Here the absence of the
                  attribute <code nobreak="false">continued="yes"</code> indicates the end of the group.</p><p>Source XML document:</p><eg xml:space="preserve" role="xml">&lt;doc&gt;
  &lt;page continued="yes"&gt;Some text&lt;/page&gt;
  &lt;page continued="yes"&gt;More text&lt;/page&gt;    
  &lt;page&gt;Yet more text&lt;/page&gt;
  &lt;page continued="yes"&gt;Some words&lt;/page&gt;
  &lt;page continued="yes"&gt;More words&lt;/page&gt;    
  &lt;page&gt;Yet more words&lt;/page&gt;        
&lt;/doc&gt;</eg><p>Desired output:</p><eg xml:space="preserve" role="xml">&lt;doc&gt;
  &lt;pageset&gt;
    &lt;page&gt;Some text&lt;/page&gt;
    &lt;page&gt;More text&lt;/page&gt;    
    &lt;page&gt;Yet more text&lt;/page&gt;
  &lt;/pageset&gt;
  &lt;pageset&gt;
    &lt;page&gt;Some words&lt;/page&gt;
    &lt;page&gt;More words&lt;/page&gt;    
    &lt;page&gt;Yet more words&lt;/page&gt;
  &lt;/pageset&gt;
&lt;/doc&gt;</eg><p>Solution:</p><eg xml:space="preserve" role="xslt-declaration">&lt;xsl:template match="doc"&gt;
&lt;doc&gt;
  &lt;xsl:for-each-group select="*" 
                      group-ending-with="page[not(@continued='yes')]"&gt;
    &lt;pageset&gt;
      &lt;xsl:for-each select="current-group()"&gt;
        &lt;page&gt;&lt;xsl:value-of select="."/&gt;&lt;/page&gt;
      &lt;/xsl:for-each&gt; 
    &lt;/pageset&gt;
  &lt;/xsl:for-each-group&gt;
&lt;/doc&gt;
&lt;/xsl:template&gt;</eg></example><example><head>Adding an Element to Several Groups</head><p>The next example shows how an item can be added to multiple groups. Book titles
                  will be added to one group for each indexing term marked up within the title.</p><p>Source XML document:</p><eg xml:space="preserve" role="xml">&lt;titles&gt;
    &lt;title&gt;A Beginner's Guide to &lt;ix&gt;Java&lt;/ix&gt;&lt;/title&gt;
    &lt;title&gt;Learning &lt;ix&gt;XML&lt;/ix&gt;&lt;/title&gt;
    &lt;title&gt;Using &lt;ix&gt;XML&lt;/ix&gt; with &lt;ix&gt;Java&lt;/ix&gt;&lt;/title&gt;
&lt;/titles&gt;</eg><p>Desired output:</p><eg xml:space="preserve" role="xml">&lt;h2&gt;Java&lt;/h2&gt;
    &lt;p&gt;A Beginner's Guide to Java&lt;/p&gt;
    &lt;p&gt;Using XML with Java&lt;/p&gt;
&lt;h2&gt;XML&lt;/h2&gt;
    &lt;p&gt;Learning XML&lt;/p&gt;
    &lt;p&gt;Using XML with Java&lt;/p&gt;</eg><p>Solution:</p><eg xml:space="preserve" role="xslt-declaration">&lt;xsl:template match="titles"&gt;
    &lt;xsl:for-each-group select="title" group-by="ix"&gt;
      &lt;h2&gt;&lt;xsl:value-of select="current-grouping-key()"/&gt;&lt;/h2&gt;
      &lt;xsl:for-each select="current-group()"&gt;
        &lt;p&gt;&lt;xsl:value-of select="."/&gt;&lt;/p&gt;
      &lt;/xsl:for-each&gt;
    &lt;/xsl:for-each-group&gt;
&lt;/xsl:template&gt;</eg></example><example><head>Grouping Alternating Sequences of Elements</head><p>In this example, the membership of a node within a group is based both on
                  adjacency of the nodes in document order, and on common values. In this case, the
                  grouping key is a boolean condition, <code nobreak="false">true</code> or <code nobreak="false">false</code>, so the effect is that a
                  grouping establishes a maximal sequence of nodes for which the condition is true,
                  followed by a maximal sequence for which it is false, and so on.</p><p>Source XML document:</p><eg xml:space="preserve" role="xml">&lt;p&gt;Do &lt;em&gt;not&lt;/em&gt;:
    &lt;ul&gt;
    &lt;li&gt;talk,&lt;/li&gt;
    &lt;li&gt;eat, or&lt;/li&gt;
    &lt;li&gt;use your mobile telephone&lt;/li&gt;
    &lt;/ul&gt;
    while you are in the cinema.&lt;/p&gt;</eg><p>Desired output:</p><eg xml:space="preserve" role="xml">&lt;p&gt;Do &lt;em&gt;not&lt;/em&gt;:&lt;/p&gt;
    &lt;ul&gt;
    &lt;li&gt;talk,&lt;/li&gt;
    &lt;li&gt;eat, or&lt;/li&gt;
    &lt;li&gt;use your mobile telephone&lt;/li&gt;
    &lt;/ul&gt;
    &lt;p&gt;while you are in the cinema.&lt;/p&gt;</eg><p>Solution:</p><p>This requires creating a <code nobreak="false">p</code> element around the maximal sequence of
                  sibling nodes that does not include a <code nobreak="false">ul</code> or <code nobreak="false">ol</code>
                  element.</p><p>This can be done by using <code nobreak="false">group-adjacent</code>, with a grouping key that is
                  <code nobreak="false">true</code> if the element is a <code nobreak="false">ul</code> or <code nobreak="false">ol</code> element, and <code nobreak="false">false</code>
                  otherwise:</p><eg xml:space="preserve" role="xslt-declaration">&lt;xsl:template match="p"&gt;
    &lt;xsl:for-each-group select="node()" 
            group-adjacent="self::ul or self::ol"&gt;
        &lt;xsl:choose&gt;
            &lt;xsl:when test="current-grouping-key()"&gt;
                &lt;xsl:copy-of select="current-group()"/&gt;  
            &lt;/xsl:when&gt;
            &lt;xsl:otherwise&gt;
                &lt;p&gt;
                    &lt;xsl:copy-of select="current-group()"/&gt;
                &lt;/p&gt;
            &lt;/xsl:otherwise&gt;  
        &lt;/xsl:choose&gt;
    &lt;/xsl:for-each-group&gt;
&lt;/xsl:template&gt;</eg></example><example diff="add" at="2022-01-01"><head>Grouping entries in a Map</head><p>Consider a map with composite keys that might appear in a JSON document as:</p><eg xml:space="preserve">{
   "Africa/Abidjan": { "offset": "+00:00", "DST-offset": "+00:00" },
   "Africa/Algiers": { "offset": "+01:00", "DST-offset": "+01:00" },
   "Africa/Nairobi": { "offset": "+03:00", "DST-offset": "+03:00" },
   "America/Anchorage": { "offset": "-09:00", "DST-offset": "-08:00" },
   "America/Los_Angeles": { "offset": "-08:00", "DST-offset": "-07:00" },
   "Asia/Dubai": { "offset": "+04:00", "DST-offset": "+04:00" },
   "Asia/Kolkata": { "offset": "+05:30", "DST-offset": "+05:30" }                 
}</eg><p>And suppose we wish to group this into a two-level map, thus:</p><eg xml:space="preserve">{
  "Africa": {
    "Abidjan": { "offset": "+00:00", "DST-offset": "+00:00" },
    "Algiers": { "offset": "+01:00", "DST-offset": "+01:00" },
    "Nairobi": { "offset": "+03:00", "DST-offset": "+03:00" }
  },
  "America": {
    "Anchorage": { "offset": "-09:00", "DST-offset": "-08:00" },
    "Los_Angeles": { "offset": "-08:00", "DST-offset": "-07:00" }
  },
  "Asia": {
    "Dubai": { "offset": "+04:00", "DST-offset": "+04:00" },
    "Kolkata": { "offset": "+05:30", "DST-offset": "+05:30" }
  }
}</eg><p>This can be achieved as follows:</p><eg xml:space="preserve">&lt;xsl:map&gt;
   &lt;xsl:for-each-group select="json-doc('tz.json') =&gt; map:pairs()" 
                       group-by="substring-before(?key, '/')"&gt;
     &lt;xsl:map-entry key="current-grouping-key()"&gt;
       &lt;xsl:map&gt;
         &lt;xsl:for-each select="current-group()"&gt;
           &lt;xsl:map-entry key="substring-after(?key, '/')" select="?value"/&gt;
         &lt;/xsl:for-each&gt;
       &lt;/xsl:map&gt;
     &lt;/xsl:map-entry&gt;
   &lt;/xsl:for-each-group&gt;
&lt;/xsl:map&gt;</eg></example><example><head>Grouping Items by Proximity (Merging)</head><p>Consider a sequence of atomic items that we wish to group according to cluster.
                  For the sake of illustration we restrict ourselves to integers. For each integer,
                  the group it is in should include every other integer of proximate distance two or
                  less.</p><eg xml:space="preserve" role="xslt-instruction">&lt;xsl:variable name="ages" as="xs:integer*" select="5, 24, 9, 5, 6, 8, 36, 38, 28"&gt;</eg><p>We want to return the following four groups:</p><eg xml:space="preserve" role="non-xml">map { 1 : (5, 9, 5, 6, 8), 2 : (24), 3 : (36, 38), 4 : (28)}</eg><p>Solution:</p><eg xml:space="preserve" role="xslt-declaration">&lt;xsl:map&gt;
  &lt;xsl:for-each-group select="$ages" merge-when="function($a, $b){abs($a - $b) le 2}"&gt;
    &lt;xsl:map-entry key="position()" select="current-group()"/&gt;
  &lt;/xsl:for-each-group&gt;
&lt;/xsl:map&gt;</eg></example><example><head>Collating Text Versions (Merging)</head><p>The next example shows how the component parts of multiple versions of a text can
                  be collated when they refer to overlapping reference systems. Suppose we have a
                  text, with various commentaries and glosses, and we wish to collate them by text
                  cluster, for online presentation.</p><eg xml:space="preserve" role="xml">&lt;body type="source"&gt;
  &lt;div ref="7a1"&gt;[text]&lt;/div&gt;
  &lt;div ref="7a2"&gt;[text]&lt;/div&gt;
  &lt;div ref="7a3"&gt;[text]&lt;/div&gt;
  &lt;div ref="7a4"&gt;[text]&lt;/div&gt;
  &lt;!-- . . . --&gt;
&lt;/body&gt;</eg><eg xml:space="preserve" role="xml">&lt;body type="commentary"&gt;
  &lt;div ref="7a1 7a2"&gt;[commentary A]&lt;/div&gt;
  &lt;!-- . . . --&gt;
&lt;/body&gt;</eg><eg xml:space="preserve" role="xml">&lt;body type="commentary"&gt;
  &lt;div ref="7a2 7a3"&gt;[commentary B]&lt;/div&gt;
  &lt;!-- . . . --&gt;
&lt;/body&gt;</eg><eg xml:space="preserve" role="xml">&lt;body type="gloss"&gt;
  &lt;div ref="7a1"&gt;[gloss A]&lt;/div&gt;
  &lt;!-- . . . --&gt;
&lt;/body&gt;</eg><eg xml:space="preserve" role="xml">&lt;body type="gloss"&gt;
  &lt;div ref="7a4"&gt;[gloss B]&lt;/div&gt;
  &lt;!-- . . . --&gt;
&lt;/body&gt;</eg><p>We wish to collate text portions, and display the grouped clusters in an HTML fragment:</p><eg xml:space="preserve" role="xml">&lt;div class="edition"&gt;
  &lt;div class="text-cluster"&gt;
    &lt;div class="ref"&gt;7a1&lt;/div&gt;
    &lt;div class="ref"&gt;7a2&lt;/div&gt;
    &lt;div class="ref"&gt;7a3&lt;/div&gt;
    &lt;div class="source"&gt;[text]&lt;/div&gt;
    &lt;div class="commentary"&gt;[commentary A]&lt;/div&gt;
    &lt;div class="commentary"&gt;[commentary B]&lt;/div&gt;
    &lt;div class="gloss"&gt;[gloss A]&lt;/div&gt;
  &lt;/div&gt;
  &lt;div class="text-cluster"&gt;
    &lt;div class="ref"&gt;7a4&lt;/div&gt;
    &lt;div class="source"&gt;[text]&lt;/div&gt;
    &lt;div class="gloss"&gt;[gloss B]&lt;/div&gt;
  &lt;/div&gt;
&lt;/div&gt;</eg><p>In this solution, we bind all the texts to a variable, <code nobreak="false">$versions</code>, 
               and we pass a template copy of the desired HTML output through a designated XSLT mode. 
               At the appropriate place, we collate the versions by using <code nobreak="false">group-by-cluster</code>:</p><eg xml:space="preserve" role="xslt-declaration">&lt;xsl:template match="html:div[@class eq 'edition']" mode="collate-versions"&gt;
  &lt;xsl:copy&gt;
    &lt;xsl:copy-of select="@*"/&gt;
    &lt;xsl:for-each-group select="$versions//body/div" merge-when="function($a, $b){tokenize($a/@ref) = tokenize($b/@ref)}"&gt;
      &lt;div class="text-cluster"&gt;
        &lt;xsl:for-each select="distinct-values(current-group() ! tokenize(@ref))"&gt;
          &lt;div class="ref"&gt;
            &lt;xsl:value-of select="."/&gt;
          &lt;/div&gt;
        &lt;/xsl:for-each&gt;
        &lt;xsl:for-each-group select="current-group()" group-by="../@type"&gt;
          &lt;div&gt;
            &lt;xsl:attribute name="class" select="current-grouping-key()"/&gt;
            &lt;xsl:apply-templates mode="#current"/&gt;
          &lt;/div&gt;
        &lt;/xsl:for-each-group&gt; 
      &lt;/div&gt;
    &lt;/xsl:for-each-group&gt;
  &lt;/xsl:copy&gt;
&lt;/xsl:template&gt;</eg></example></div2><div2 id="non-transitivity" diff="del" at="2022-01-01"><head>Non-Transitivity</head><p>If the population contains values of different numeric types that differ from each
               other by small amounts, then the <code nobreak="false">eq</code> operator is not transitive, because
               of rounding effects occurring during type promotion. It is thus possible to have
               three values <var>A</var>, <var>B</var>, and <var>C</var> among the grouping keys of
               the population such that <code nobreak="false">A eq B</code>, <code nobreak="false">B eq C</code>, but <code nobreak="false">A ne
                  C</code>.</p><p>For example, this arises when computing</p><eg xml:space="preserve" role="xslt-instruction">
      &lt;xsl:for-each-group group-by="." select="
             xs:float('1.0'),
             xs:decimal('1.0000000000100000000001'),
             xs:double('1.00000000001')"/&gt;</eg><p>because the values of type <code nobreak="false">xs:float</code> and <code nobreak="false">xs:double</code> both
               compare equal to the value of type <code nobreak="false">xs:decimal</code> but not equal to each
               other.</p><p>In this situation the results <rfc2119>must</rfc2119> be equivalent to the results
               obtained by the following algorithm:</p><ulist><item><p>For each item <var>J</var> in the <termref def="dt-population">population</termref> in <termref def="dt-population-order">population
                        order</termref>, for each of the <termref def="dt-grouping-key">grouping
                        keys</termref>
                     <var>K</var> for that item in sequence, the processor identifies those existing
                     groups <var>G</var> such that the grouping key of the <termref def="dt-initial-item">initial item</termref> of <var>G</var> is equal to
                        <var>K</var>.</p></item><item><p>If there is exactly one group <var>G</var>, then <var>J</var> is added to this
                     group, unless <var>J</var> is already a member of this group.</p></item><item><p>If there is no group <var>G</var>, then a new group is created with
                        <var>J</var> as its first item.</p></item><item><p>If there is more than one group <var>G</var> (which can only happen in
                     exceptional circumstances involving non-transitivity), then one of these groups
                     is selected in an implementation-dependent way, and <var>J</var> is added to
                     this group, unless <var>J</var> is already a member of this group.</p></item></ulist><p>The effect of these rules is that (a) every item in a non-singleton group has a
               grouping key that is equal to that of at least one other item in that group, (b) for
               any two distinct groups, there is at least one pair of items (one from each group)
               whose grouping keys are not equal to each other.</p></div2></div1><div1 id="merging"><head>Merging</head><changes><change issue="1684" PR="1689" date="2025-01-09">
               Composite merge keys are now allowed.
            </change></changes><p>The <elcode>xsl:merge</elcode> instruction allows a sorted sequence of items to be
            constructed by merging several input sequences. Each
            input sequence <rfc2119>must</rfc2119> have a merge key (one or more
            atomic items that can be computed as a function of the items in the sequence); the
            input sequence <rfc2119>must</rfc2119> either already be sorted on the value of
            its merge keys, or pre-sorting on these values must be requested. 
            The merge keys for the different input sequences <rfc2119>must</rfc2119> be compatible in the sense that key
               values from an item in one sequence are always comparable with key values from an
               item in a different sequence.</p><p>For example, if two log files contain details of events sorted by date and time, then
            the <elcode>xsl:merge</elcode> instruction can be used to combine these into a single
            sequence that is also sorted by date and time.</p><p>The data written to the output sequence can be computed in an arbitrary way from the
            data in the input sequences, provided it follows the ordering of the input
            sequences.</p><p>The <elcode>xsl:merge</elcode> instruction can be used to merge several sequences of
            items that all have the same structure (more precisely, sequences whose merge keys are
            computed in the same way): for example, log files created by the same application
            running on different machines in a server farm. Alternatively,
               <elcode>xsl:merge</elcode> can be used to merge sequences that have different
            structure (sequences whose merge keys are computed in different ways), provided that the
            computed merge keys are compatible: an example might be two log files created by
            different applications, using different XML vocabularies, that both contain timestamped
            events but represent the timestamp in different ways. The
               <elcode>xsl:merge-source</elcode> element represents a set
               of input sequences that follow common rules, including the rules for
            computing the merge key. The <elcode>xsl:merge</elcode> operation may take any number of
               <elcode>xsl:merge-source</elcode> elements representing different rules for input sequences, and each <elcode>xsl:merge-source</elcode>
            element may describe any number (zero or more) of input sequences. The number of input
            sequences to the merging operation is thus fixed only at the
               time the <elcode>xsl:merge</elcode> instruction is evaluated, and
                  <rfc2119>may</rfc2119> vary from one evaluation to another.</p><p>The following examples illustrate some of the possibilities. The detailed explanation of
            the constructs used follows later in this section.</p><example><head>Merging All the Files in a Collection</head><p>This example takes as input a homogeneous collection of XML log files each of which
               contains a sorted sequence of <code nobreak="false">event</code> elements with a
                  <code nobreak="false">timestamp</code> attribute validated as an instance of
                  <code nobreak="false">xs:dateTime</code>. It merges the events from the input files into a single
               sorted output file.</p><eg role="xslt-instruction" xml:space="preserve">
&lt;xsl:result-document href="merged-events.xml"&gt;
  &lt;events&gt;
    &lt;xsl:merge&gt;
      &lt;xsl:merge-source for-each-source="uri-collection('log-files')"
                        select="events/event"&gt;
        &lt;xsl:merge-key select="@timestamp"/&gt;
      &lt;/xsl:merge-source&gt;
      &lt;xsl:merge-action&gt;
        &lt;xsl:copy-of select="current-merge-group()"/&gt;
      &lt;/xsl:merge-action&gt;
    &lt;/xsl:merge&gt;
  &lt;/events&gt;
&lt;/xsl:result-document&gt;
</eg><p>The example assumes that there are several input files each
                  of which has a structure similar to the following, in which the
                  <code nobreak="false">timestamp</code> attribute has a typed value that is an instance of
                  <code nobreak="false">xs:dateTime</code>:</p><eg role="xml" xml:space="preserve">
&lt;events&gt;
   &lt;event timestamp="2009-08-20T12:01:01Z"&gt;Transaction T1234 started&lt;/event&gt;
   &lt;event timestamp="2009-08-20T12:01:08Z"&gt;Transaction T1235 started&lt;/event&gt;
   &lt;event timestamp="2009-08-20T12:01:12Z"&gt;Transaction T1235 ended&lt;/event&gt;
   &lt;event timestamp="2009-08-20T12:01:15Z"&gt;Transaction T1234 ended&lt;/event&gt;
&lt;/events&gt;</eg><p>The output file will have the same structure, and will contain copies of all the
                  <code nobreak="false">event</code> elements from all of the input files, in sorted order. Note that multiple events with the same timestamp can occur
                  either within a single file or across multiple files: the order of appearance of
                  these events in the output file corresponds to the order of the log files within
                  the collection (which might or might not be predictable, depending on the
                  implementation).</p></example><example><head>Merging Two Heterogeneous Files</head><p>This example takes as input two log files with different structure, producing a
               single merged output in which the entries have a common structure:</p><eg role="xslt-instruction" xml:space="preserve">
&lt;xsl:result-document href="merged-events.xml"&gt;
  &lt;events&gt;
    &lt;xsl:merge&gt;
      &lt;xsl:merge-source select="doc('log-file-1.xml')/events/event"&gt;
        &lt;xsl:merge-key select="@timestamp"/&gt;
      &lt;/xsl:merge-source&gt;
      &lt;xsl:merge-source select="doc('log-files-2.xml')/log/day/record"&gt;
        &lt;xsl:merge-key select="dateTime(../@date, time)"/&gt;
      &lt;/xsl:merge-source&gt;
      &lt;xsl:merge-action&gt;
        &lt;xsl:apply-templates select="current-merge-group()" 
                             mode="standardize-log-entry"/&gt;
      &lt;/xsl:merge-action&gt;
    &lt;/xsl:merge&gt;
  &lt;/events&gt;
&lt;/xsl:result-document&gt;
</eg><p>Here the first input file has a structure similar to that shown in the previous
               example, while the second input has a different structure, of the form:</p><eg role="xml" xml:space="preserve">
&lt;log&gt;
  &lt;day date="2009-08-20"&gt;
    &lt;record&gt;
      &lt;time&gt;12:01:09-05:00&lt;/time&gt;
      &lt;message&gt;Temperature 15.4C&lt;/message&gt;
    &lt;/record&gt;
    &lt;record&gt;
      &lt;time&gt;12:03:00-05:00&lt;/time&gt;
      &lt;message&gt;Temperature 18.2C&lt;/message&gt;
    &lt;/record&gt;
  &lt;/day&gt;
&lt;/log&gt;</eg><p>The templates in mode <code nobreak="false">standardize-log-entry</code> convert the log entries to a
               common output format, for example:</p><eg role="xslt-declaration" xml:space="preserve">
&lt;xsl:template match="event" mode="standardize-log-entry" 
                            as="schema-element(event)"&gt;
  &lt;xsl:copy-of select="." validation="preserve"/&gt;
&lt;/xsl:template&gt;
  
&lt;xsl:template match="record" mode="standardize-log-entry" 
                             as="schema-element(event)"&gt;
  &lt;event timestamp="{dateTime(../@date, time)}" xsl:validation="strict"&gt;
    &lt;xsl:value-of select="message"/&gt;
  &lt;/event&gt;
&lt;/xsl:template&gt;</eg></example><note><p>The <elcode>xsl:merge</elcode> instruction is designed to enable streaming of data,
               so that there is no need to allocate memory to hold the input sequences. However, it can also be used in cases where streamed
                  processing is not possible, for example when the input needs to be
               sorted.</p></note><div2 id="merge-terminology"><head>Terminology for Merging</head><p><termdef id="dt-merge-source-definition" term="merge source definition">A <term>merge
                     source definition</term> is the definition of one kind of input to the merge
                  operation. It selects zero or more <termref def="dt-merge-input-sequence">merge
                     input sequences</termref>, and it includes a 
               <termref def="dt-merge-key-specification">merge key specification</termref> to define
                  how the <termref def="dt-merge-key-value">merge key
                        values</termref> are computed for each such merge input
                  sequence.</termdef> A merge source definition corresponds to an
                  <elcode>xsl:merge-source</elcode> element in the stylesheet.</p><p><termdef id="dt-merge-input-sequence" term="merge input sequence">A <term>merge input
                     sequence</term> is an arbitrary <xtermref spec="DM40" ref="dt-sequence">sequence</xtermref> of items which is already sorted according to the <termref def="dt-merge-key-specification">merge key specification</termref> for the
                  corresponding <termref def="dt-merge-source-definition">merge source
                     definition</termref>.</termdef></p><p><termdef id="dt-merge-key-specification" term="merge key specification">A <term>merge
                     key specification</term> consists of one or more adjacent
                     <elcode>xsl:merge-key</elcode> elements which together define how the 
               <termref def="dt-merge-input-sequence">merge input sequences</termref> selected by a
                     <termref def="dt-merge-source-definition">merge source definition</termref> are
                  sorted. Each <elcode>xsl:merge-key</elcode> element defines one 
               <termref def="dt-merge-key-component">merge key component</termref>.</termdef> For
               example, a merge key specification for a log file might specify two merge key
               components, <code nobreak="false">date</code> and <code nobreak="false">time</code>.</p><p><termdef id="dt-merge-key-component" term="merge key component">A <term>merge key
                     component</term> specifies one component of a <termref def="dt-merge-key-specification">merge key specification</termref>; it
                  corresponds to a single <elcode>xsl:merge-key</elcode> element in the
                  stylesheet.</termdef></p><p><termdef id="dt-merge-key-value" term="merge key value"> For each item in a 
               <termref def="dt-merge-input-sequence">merge input sequence</termref>, a value is
                  computed for each <termref def="dt-merge-key-component">merge key
                     component</termref> within the <termref def="dt-merge-key-specification">merge
                     key specification</termref>. The value computed for an item by using the
                     <var>N</var>th <termref def="dt-merge-key-component"/> is referred to as the
                     <var>N</var>th <term>merge key value</term> of that item.</termdef>
               A merge key value may be any sequence of atomic items (including the empty sequence).</p><p><termdef id="dt-combined-merge-key-value" term="combined merge key value"> The
                  ordered collection of <termref def="dt-merge-key-value">merge key values</termref>
                  computed for one item in a <termref def="dt-merge-input-sequence">merge input
                     sequence</termref> (one for each <termref def="dt-merge-key-component">merge
                     key component</termref> within the 
                     <termref def="dt-merge-key-specification">merge key specification</termref>) 
                     is referred to as a <term>combined merge key value</term>.</termdef>
                  Since each merge key value is (in general) a sequence of atomic items, the
                  combined merge key value is modeled as an array of such sequences.</p><p><termdef id="dt-merge-activation" term="merge activation">A <term>merge
                     activation</term> is a single evaluation of the sequence constructor contained
                  within the <elcode>xsl:merge-action</elcode> element, which occurs once for each
                  distinct <termref def="dt-combined-merge-key-value"/>.</termdef></p></div2><div2 id="merge-instruction"><head>The <elcode>xsl:merge</elcode> Instruction</head><e:element-syntax xmlns:e="http://www.w3.org/1999/XSL/Spec/ElementSyntax" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" name="merge">
      <e:in-category name="instruction"/>
      <e:sequence>
         <e:element repeat="one-or-more" name="merge-source"/>
         <e:element name="merge-action"/>
         <e:element repeat="zero-or-more" name="fallback"/>
      </e:sequence>
      <e:allowed-parents>
         <e:parent-category name="sequence-constructor"/>
      </e:allowed-parents>
   </e:element-syntax><p>The effect of the <elcode>xsl:merge</elcode> instruction is to produce a sorted
               result sequence from a number of input sequences.</p><p>The input sequences to the merge operation are defined by the
                  <elcode>xsl:merge-source</elcode> child elements, as described in the next
               section.</p><p>The sequence constructor contained in the
                  <elcode>xsl:merge-action</elcode> element is evaluated once for each distinct
                  <termref def="dt-combined-merge-key-value"/> to form a partial result sequence.
               The result of the <elcode>xsl:merge</elcode> instruction is the concatenation of
               these partial result sequences. For example, the action might be to copy the items
               from all the input sequences to the result sequence without change; or it might be to
               select the items from one input sequence in preference to the others. In the general
               case, the items in the partial result sequence are produced by an arbitrary
               computation that has access to the items (from the various input sequences) that
               share the same value for the composite merge key.</p><p>The <elcode>xsl:merge-source</elcode> and
                  <elcode>xsl:merge-action</elcode> elements are described in the following
               sections.</p><p>Any <elcode>xsl:fallback</elcode> children of the <elcode>xsl:merge</elcode>
               instruction are ignored by an XSLT 3.0 processor, but are used by an XSLT 1.0 or XSLT
               2.0 processor to perform fallback processing.</p><note><p>An <elcode>xsl:merge</elcode> instruction that has no input sequences returns an
                  empty sequence. An <elcode>xsl:merge</elcode> instruction with a single input
                  sequence performs processing that is very similar in concept to
                     <elcode>xsl:for-each-group</elcode> with the <code nobreak="false">group-adjacent</code>
                  attribute, except that it requires the input to be sorted on the grouping key.</p></note></div2><div2 id="merge-input-sequences"><head>Selecting the Sequences to be Merged</head><e:element-syntax xmlns:e="http://www.w3.org/1999/XSL/Spec/ElementSyntax" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" name="merge-source">
      <e:attribute name="name" required="no">
         <e:data-type name="ncname"/>
      </e:attribute>
      <e:attribute name="for-each-item" required="no">
         <e:data-type name="expression"/>
      </e:attribute>
      <e:attribute name="for-each-source" required="no">
         <e:data-type name="expression"/>
      </e:attribute>
      <e:attribute name="select" required="yes">
         <e:data-type name="expression"/>
      </e:attribute>
      <e:attribute name="streamable" required="no">
         <e:data-type name="boolean"/>
      </e:attribute>
      <e:attribute name="use-accumulators" default="''">
         <e:data-type name="tokens"/>
      </e:attribute>
      <e:attribute name="sort-before-merge" required="no" default="'no'">
         <e:data-type name="boolean"/>
      </e:attribute>
      <e:attribute name="validation">
         <e:constant value="strict"/>
         <e:constant value="lax"/>
         <e:constant value="preserve"/>
         <e:constant value="strip"/>
      </e:attribute>
      <e:attribute name="type">
         <e:data-type name="eqname"/>
      </e:attribute>
      <e:element repeat="one-or-more" name="merge-key"/>
      <e:allowed-parents>
         <e:parent name="merge"/>
      </e:allowed-parents>
   </e:element-syntax><p>Each <elcode>xsl:merge-source</elcode> element defines one or more <termref def="dt-merge-input-sequence">merge input sequences</termref>.</p><p>The <code nobreak="false">name</code> attribute provides a means of
               distinguishing items from different merge sources within the
                  <elcode>xsl:merge-action</elcode> instructions. If the <code nobreak="false">name</code> attribute
               is present on an <elcode>xsl:merge-source</elcode> element, then it must not be equal
               to the <code nobreak="false">name</code> attribute of any sibling <elcode>xsl:merge-source</elcode>
               element. If the <code nobreak="false">name</code> attribute is absent, then an <termref def="dt-implementation-dependent"/> name, different from all explicitly specified
               names, is allocated to the merge source.</p><p><error spec="XT" class="SE" type="static" code="3195"><p>If the <code nobreak="false">for-each-item</code> attribute is present then the
                        <code nobreak="false">for-each-source</code>, <code nobreak="false">use-accumulators</code>, and <code nobreak="false">streamable</code> attributes
                     must all be absent. If <phrase diff="chg" at="2022-01-01">either or both of the
                        <code nobreak="false">use-accumulators</code> or <code nobreak="false">streamable</code> attributes is present </phrase>
                     then the <code nobreak="false">for-each-source</code> attribute must be present. If the
                        <code nobreak="false">for-each-source</code> attribute is present then the
                     <code nobreak="false">for-each-item</code> attribute must be absent. 
                     </p></error></p><p>The <code nobreak="false">use-accumulators</code> attribute defines the
               set of accumulators that are applicable to the streamed document, as explained in
                  <specref ref="applicability-of-accumulators"/>.</p><p>If neither of
                     <code nobreak="false">for-each-item</code> and <code nobreak="false">for-each-source</code> is
               present, the <elcode>xsl:merge-source</elcode> element defines a single
               merge input sequence. This sequence is the result of evaluating the expression in the
                  <code nobreak="false">select</code> attribute. This is evaluated using the dynamic context of the
               containing <elcode>xsl:merge</elcode> instruction. This sequence will be merged with
               the sequences defined by other <elcode>xsl:merge-source</elcode> elements, if
               present.</p><p>When the <code nobreak="false">for-each-item</code>
               attribute is present, the <elcode>xsl:merge-source</elcode> element defines a
               collection of merge input sequences. The selection of items in these input sequences
               is a two-stage process: the <code nobreak="false">for-each-item</code> attribute of the
                  <elcode>xsl:merge-source</elcode> element is an expression that selects a sequence
               of <emph>anchor items</emph>, and for each anchor item, the <code nobreak="false">select</code>
               attribute is evaluated to select the items that make up one merge input sequence. The
                  <code nobreak="false">for-each-item</code> expression is evaluated with
               the dynamic context of the containing <elcode>xsl:merge</elcode> instruction, while
               the <code nobreak="false">select</code> attribute is evaluated with the <termref def="dt-focus">focus</termref> for the evaluation as follows:</p><ulist><item><p>The <termref def="dt-context-item">context item</termref> is the anchor
                     item</p></item><item><p>The <termref def="dt-context-position">context position</termref> is the
                     position of the anchor item within the sequence of anchor items</p></item><item><p>The <termref def="dt-context-size">context size</termref> is the number of
                     anchor items.</p></item></ulist><p>When the <code nobreak="false">for-each-source</code> attribute is
               present, its value must be an expression that returns a sequence of URIs. 
               The expression is evaluated with the same
               dynamic context as the containing <elcode>xsl:merge</elcode> instruction. The
               expected type of the expression is <code nobreak="false">xs:string*</code>, and the actual result of
               the expression is converted to this type using the <termref def="dt-coercion-rules"/>. Each of these URIs is used to obtain a
               document node. Each <rfc2119>must</rfc2119> be a valid URI reference. If it is an
               absolute URI reference, it is used as is; if it is a relative URI reference, it is
               made absolute by resolving it against the base URI of the
                  <elcode>xsl:merge-source</elcode> element. The process of obtaining a document
               node given a URI is the same as for the <xfunction>doc</xfunction> function, and may trigger the same error conditions.
               However, unlike the <xfunction>doc</xfunction> function, the
                  <elcode>xsl:merge</elcode> instruction offers no guarantee that the resulting
               document will be stable (that is, that multiple calls specifying the same URI will
               return the same document). The resulting document nodes act as the <term>anchor
                  items</term>. These anchor items are then used in the same way as a sequence of
               anchor items selected directly using the <code nobreak="false">for-each-item</code> attribute:
               in particular, the <termref def="dt-focus"/> is
               determined in the same way.</p><note><p>Examples of expressions that return a sequence of URIs are:</p><ulist><item><p><code nobreak="false">for-each-source="'inputA.xml', 'inputB.xml'"</code></p></item><item><p><code nobreak="false">for-each-source="(1 to $N) ! ('input' || $N || '.xml')"</code></p></item><item><p><code nobreak="false">for-each-source="uri-collection('input/dir/')</code></p></item></ulist><p>Relative URIs are resolved relative to the base URI of the
                     <elcode>xsl:merge-source</elcode> element.</p></note><p>The attributes <code nobreak="false">validation</code> and
                  <code nobreak="false">type</code> are used to control schema validation of documents read by
               virtue of their appearance in the result of the <code nobreak="false">for-each-source</code>
               expression. These attributes are mutually exclusive <errorref spec="XT" class="SE" code="1505"/>. 
               <phrase diff="del" at="2022-01-01">The rules are the same as for an <elcode>xsl:source-document</elcode>
               instruction specifying <code nobreak="false">streamable="yes"</code>. </phrase>
               If the <code nobreak="false">for-each-source</code> attribute is absent, then the
                  <code nobreak="false">validation</code> and <code nobreak="false">type</code> attributes <rfc2119>must</rfc2119>
               both be absent. <phrase diff="add" at="2022-01-01">The process of validation follows
               the rules defined in <specref ref="validation"/>.</phrase></p><p>If the <code nobreak="false">sort-before-merge</code> attribute is absent or has
               the value <code nobreak="false">no</code>, then each merge input sequence <rfc2119>must</rfc2119> already
               be in the correct order for merging (a dynamic error occurs if it is not). If the
               attribute is present with the value <code nobreak="false">yes</code>, then each input sequence will
               first be sorted to ensure that it is in the correct order. <phrase diff="add" at="2022-01-01">
                  The sorting is carried out as if by evaluating an <elcode>xsl:perform-sort</elcode> 
                  instruction with <elcode>xsl:sort</elcode> children corresponding one-to-one with 
                  the <elcode>xsl:merge-key</elcode> children of the <elcode>xsl:merge-source</elcode> 
                  element, differing only (a) in the change of element name, 
                  and (b) in the addition of the attribute <code nobreak="false">stable="yes"</code> to the first such element.
                  
               </phrase></p><example><head>Merging Several Documents with the Same Structure</head><p>The following <elcode>xsl:merge-source</elcode> element selects two anchor items
                  (the root nodes of two documents), and for each of these it selects an input
                  sequence consisting of selected <code nobreak="false">event</code> elements within the relevant
                  document.</p><eg role="xslt-fragment" xml:space="preserve">
&lt;xsl:merge-source for-each-source="'log-A.xml', 'log-B.xml'"
                  streamable="yes"
                  select="events/event"&gt;
   &lt;xsl:merge-key select="@timestamp" order="ascending"/&gt;
&lt;/xsl:merge-source&gt;</eg><p>This example can be extended to merge any number of input documents with the same
                  structure:</p><eg role="xslt-fragment" xml:space="preserve">
&lt;xsl:merge-source for-each-source="uri-collection('log-collection')"
                  streamable="yes"
                  select="events/event"&gt;
   &lt;xsl:merge-key select="@time" order="ascending"/&gt;
&lt;/xsl:merge-source&gt;</eg><p>In both the above examples the anchor items are document nodes, and the items in
                  the input sequence are elements within the document that is rooted at this node.
                  This is a common usage pattern, but by no means the only way in which the
                  construct can be used.</p></example><p>The number of anchor items selected by an <elcode>xsl:merge-source</elcode> element,
               and therefore the number of input sequences, is variable, but the input sequences
               selected by one <elcode>xsl:merge-source</elcode> element must all use the same
               expressions to select the items in the input sequence and to compute their merge
               keys. If different expressions are needed for different input sequences, then
               multiple <elcode>xsl:merge-source</elcode> elements can be used.</p><example><head>Merging Two Documents with Different Structure</head><p>The following code merges two log files having different internal structure:</p><eg role="xslt-fragment" xml:space="preserve">
&lt;xsl:merge-source for-each-source="'event-log.xml'" 
                  streamable="yes" select="/*/event"&gt;
  &lt;xsl:merge-key select="@timestamp"/&gt;
&lt;/xsl:merge-source&gt;
&lt;xsl:merge-source for-each-source="'error-log.xml'" 
                  streamable="yes" select="/*/error"&gt;
  &lt;xsl:merge-key select="dateTime(@date, @time)"/&gt;
&lt;/xsl:merge-source&gt;</eg><p>Although the merge keys are computed in different ways for the two input
                  sequences, the keys must be compatible across the two sequences: in this case they
                  are both atomic items of type <code nobreak="false">xs:dateTime</code>.</p></example><p>In the common case where there is only one input sequence of a particular kind, the
                  <code nobreak="false">for-each-item</code> attribute of
                  <elcode>xsl:merge-source</elcode> may be omitted; the <code nobreak="false">select</code>
               expression is then evaluated relative to the <termref def="dt-focus">focus</termref>
               of the <elcode>xsl:merge</elcode> instruction itself.</p><example><head>Sorting before Merging</head><p>Where one or more of the inputs to the merging process is not pre-sorted, a sort
                  can be requested using the <code nobreak="false">sort-before-merge</code> attribute. For
                  example:</p><eg role="xslt-fragment" xml:space="preserve">
&lt;xsl:merge-source select="doc('event-log.xml')/*/event"&gt;
  &lt;xsl:merge-key select="@timestamp"/&gt;
&lt;/xsl:merge-source&gt;
&lt;xsl:merge-source select="doc('error-log.xml')//error" 
                  sort-before-merge="yes"&gt;
  &lt;xsl:merge-key select="dateTime(current-date(), @time)"/&gt;
&lt;/xsl:merge-source&gt;
</eg></example><p>
               <error spec="XT" type="static" class="SE" code="3190"><p>It is a <termref def="dt-static-error">static error</termref> if two sibling
                        <elcode>xsl:merge-source</elcode> elements have the same name.</p></error>
            </p></div2><div2 id="merge-keys"><head>Defining the Merge Keys</head><p>The keys on which the input sequences are sorted are referred to as merge keys. If
               the attribute <code nobreak="false">sort-before-merge</code> has the value <code nobreak="false">yes</code>, the
               input sequences will be sorted into the correct sequence before the merge operation
               takes place (alternatively, the processor <rfc2119>may</rfc2119> use an algorithm
               that has the same effect as sorting followed by merging). If the attribute is absent
               or has the value <code nobreak="false">no</code>, then the input sequences <rfc2119>must</rfc2119>
               already be in the correct order.</p><p>The merge key for each type of input sequence (that is, for each
                  <elcode>xsl:merge-source</elcode> element) is defined by a sequence of
                  <elcode>xsl:merge-key</elcode> element children of the
                  <elcode>xsl:merge-source</elcode> element. Each <elcode>xsl:merge-key</elcode>
               element defines one merge key component. The syntax and semantics of an
                  <elcode>xsl:merge-key</elcode> element are closely based on the rules for the
                  <elcode>xsl:sort</elcode> element (<phrase diff="chg" at="2022-01-01">with minor exceptions
                  noted below; the only difference in syntax is</phrase> the absence of the
                  <code nobreak="false">stable</code> attribute); the <phrase diff="add" at="2022-01-01">main</phrase> difference is that
                  <elcode>xsl:merge-key</elcode> elements do not cause a sort to take place, they
               merely declare the existing sort order of the input sequence. 
               </p><e:element-syntax xmlns:e="http://www.w3.org/1999/XSL/Spec/ElementSyntax" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" name="merge-key">
      <e:attribute name="select">
         <e:data-type name="expression"/>
      </e:attribute>
      <e:attribute name="lang">
         <e:attribute-value-template>
            <e:data-type name="language"/>
         </e:attribute-value-template>
      </e:attribute>
      <e:attribute name="order" default="'ascending'">
         <e:attribute-value-template>
            <e:constant value="ascending"/>
            <e:constant value="descending"/>
         </e:attribute-value-template>
      </e:attribute>
      <e:attribute name="collation">
         <e:attribute-value-template>
            <e:data-type name="uri"/>
         </e:attribute-value-template>
      </e:attribute>
      <e:attribute name="case-order">
         <e:attribute-value-template>
            <e:constant value="upper-first"/>
            <e:constant value="lower-first"/>
         </e:attribute-value-template>
      </e:attribute>
      <e:attribute name="data-type">
         <e:attribute-value-template>
            <e:constant value="text"/>
            <e:constant value="number"/>
            <e:data-type name="eqname"/>
         </e:attribute-value-template>
      </e:attribute>
      <e:model name="sequence-constructor"/>
      <e:allowed-parents>
         <e:parent name="merge-source"/>
      </e:allowed-parents>
   </e:element-syntax><p>The <code nobreak="false">select</code> attribute and the contained <termref def="dt-sequence-constructor">sequence constructor</termref> are mutually
               exclusive:</p><p>
               <error spec="XT" type="static" class="SE" code="3200"><p>It is a <termref def="dt-static-error">static error</termref> if an
                        <elcode>xsl:merge-key</elcode> element with a <code nobreak="false">select</code> attribute
                     has non-empty content.</p></error>
            </p><note><p>From XSLT 4.0, the <code nobreak="false">select</code> expression or contained sequence constructor
            may evaluate (after atomization) to an arbitrary sequence of atomic items. Previously,
            only a singleton atomic item or the empty sequence was allowed.</p></note><p diff="chg" at="2022-01-01">The value of <var>N</var>th item in the merge key of an item
               <var>J</var> in a <termref def="dt-merge-input-sequence">merge input
                  sequence</termref>
               <var>S</var> is computed as follows, where <var>K</var> is the <var>N</var>th
               <elcode>xsl:merge-key</elcode> element of the relevant <elcode>xsl:merge-source</elcode>:</p><olist diff="chg" at="2022-01-01"><item><p>If <var>K</var> has a <code nobreak="false">select</code> attribute, then the result 
                  of evaluating and atomizing that <code nobreak="false">select</code> expression;</p></item><item><p>If <var>K</var> contains a non-empty sequence constructor, then the 
                  result of evaluating and atomizing that sequence constructor;</p></item><item><p>Otherwise, the result of atomizing the context item.</p></item></olist><p diff="chg" at="2022-01-01">In each case the evaluation uses a <termref def="dt-singleton-focus"/> 
               based on <var>J</var>, or, if <code nobreak="false">streamable="yes"</code> is specified on the
               <elcode>xsl:merge-source</elcode> element, a <termref def="dt-singleton-focus"/> based on 
               a snapshot of <var>J</var> (see <xspecref spec="SG40" ref="streamable-merging"/>). 
               </p><note><p>This means that <code nobreak="false">position()</code> and <code nobreak="false">last()</code> return 1 (one).
                  This differs from the way <elcode>xsl:sort</elcode> keys are evaluated, where
                  <code nobreak="false">position()</code> is the position in the unsorted sequence, and
                  <code nobreak="false">last()</code> is the size of the unsorted sequence.</p></note><p>The effect of the <elcode>xsl:merge-key</elcode> elements is defined in terms of the
               rules for an equivalent sequence of <elcode>xsl:sort</elcode> elements: if the rules
               for sorting (see <specref ref="sorting-process"/>) with <code nobreak="false">stable="yes"</code>
               would place an item <var>A</var> before an item <var>B</var> in the <termref def="dt-sorted-sequence">sorted sequence</termref> produced by the sorting
               process, then <var>A</var> must precede <var>B</var> in the input sequence to the
               merging process.</p><p>The merge keys of the various input sequences to a merge operation must be compatible
               with each other, since the merge operation will decide the ordering of the result
               sequence by comparing merge key values across input sequences. This means that across
               all the <elcode>xsl:merge-source</elcode> children of an <elcode>xsl:merge</elcode>
               instruction:</p><ulist><item><p>Each <elcode>xsl:merge-source</elcode> element <rfc2119>must</rfc2119> have the
                     same number of <elcode>xsl:merge-key</elcode> child elements; let this number
                     be <var>N</var>.</p></item><item diff="chg" at="2022-01-01"><p>For each integer <var>J</var> in 1..<var>N</var>, consider the set <var>S</var> of
                        <elcode>xsl:merge-key</elcode> elements that are in position <var>J</var>
                     among the <elcode>xsl:merge-key</elcode> children of their parent
                        <elcode>xsl:merge-source</elcode> element. 
                     For each attribute <var>A</var> in the set <code nobreak="false">lang</code>, <code nobreak="false">order</code>, <code nobreak="false">collation</code>,
                     <code nobreak="false">case-order</code>, and <code nobreak="false">data-type</code> it must be the case that for
                     any two elements <var>s1</var> and <var>s2</var> in <var>S</var>, the
                     <termref def="dt-effective-value"/> of attribute <var>A</var> on <var>s1</var>
                     is the same as the <termref def="dt-effective-value"/> of attribute <var>A</var> on <var>s2</var>,
                     where two attributes are said to have the same effective value if either (a) both attributes
                     are absent, or (b) both attributes are present and the results of evaluating them 
                     (they are attribute value templates) are codepoint-equal. Furthermore, in the case
                     of the <code nobreak="false">collation</code> attribute, the absolute collation URI must be the same
                     after resolving against the base URI.</p></item></ulist><p>If any of the attributes <code nobreak="false">lang</code>, <code nobreak="false">order</code>,
                  <code nobreak="false">collation</code>, <code nobreak="false">case-order</code>, or <code nobreak="false">data-type</code> are
                  <termref def="dt-attribute-value-template">attribute value templates</termref>,
               then their <termref def="dt-effective-value">effective values</termref> are evaluated
               using the <termref def="dt-focus">focus</termref> of the containing
                  <elcode>xsl:merge</elcode> instruction.</p><p>
               <error spec="XT" type="static" class="SE" code="2200"><p>It is a <termref def="dt-static-error">static error</termref> if the number of
                        <elcode>xsl:merge-key</elcode> children of a
                        <elcode>xsl:merge-source</elcode> element is not equal to the number of
                        <elcode>xsl:merge-key</elcode> children of another
                        <elcode>xsl:merge-source</elcode> child of the same
                        <elcode>xsl:merge</elcode> instruction.</p></error>
            </p><p>
               <error spec="XT" type="dynamic" class="DE" code="2210"><p>It is a <termref def="dt-dynamic-error">dynamic
                        error</termref> if there are two <elcode>xsl:merge-key</elcode> elements
                     that occupy corresponding positions among the <elcode>xsl:merge-key</elcode>
                     children of two different <elcode>xsl:merge-source</elcode> elements and that
                     have differing <termref def="dt-effective-value">effective values</termref> for
                     any of the attributes <code nobreak="false">lang</code>, <code nobreak="false">order</code>,
                        <code nobreak="false">collation</code>, <code nobreak="false">case-order</code>, or <code nobreak="false">data-type</code>.
                     Values are considered to differ if <phrase diff="del" at="2023-04-18">the attribute is present on one element and
                     not on the other, or if it is present on both elements with</phrase> 
                     they have different <termref def="dt-effective-value">effective values</termref>. 
                     In the case of the <code nobreak="false">collation</code> attribute, the values are
                     compared as absolute URIs after resolving against the base URI. The error
                        <rfc2119>may</rfc2119> be raised statically if it is detected
                     statically.</p></error>
            </p><p>
               <error spec="XT" type="dynamic" class="DE" code="2220"><p>It is a <termref def="dt-dynamic-error">dynamic error</termref> if any input
                     sequence to an <elcode>xsl:merge</elcode> instruction contains two items that
                     are not correctly sorted according to the merge key values defined on the
                        <elcode>xsl:merge-key</elcode> children of the corresponding
                        <elcode>xsl:merge-source</elcode> element, when compared using the collation
                     rules defined by the attributes of the corresponding
                        <elcode>xsl:merge-key</elcode> children of the <elcode>xsl:merge</elcode>
                     instruction, unless the attribute <code nobreak="false">sort-before-merge</code> is present
                     with the value <code nobreak="false">yes</code>.</p></error>
            </p><p>
               <error spec="XT" type="type" class="TE" code="2230"><p>It is a <termref def="dt-type-error">type error</termref> if some item selected
                     by a particular merge key in one input sequence is not comparable using the
                     XPath <code nobreak="false">le</code> operator with the corresponding item selected by the corresponding
                     sort key in another input sequence.</p></error>
            </p></div2><div2 id="current-merge-group-and-key"><head>The Current Merge Group and Key</head><p>During processing of an <elcode>xsl:merge</elcode> instruction, two additional values
               are available within the dynamic context:</p><ulist><item><p><termdef id="dt-current-merge-group" term="current merge group">The
                           <term>current merge group</term> is a map. During
                        evaluation of an <elcode>xsl:merge</elcode> instruction, as each group of
                        items with equal <termref def="dt-combined-merge-key-value">combined merge
                           key values</termref> is processed, the current merge group is set to a
                        map whose keys are the names of the various merge sources, and whose
                        associated values are the items from each merge source having the relevant
                        composite merge key value.</termdef></p></item><item><p><termdef id="dt-current-merge-key" term="current merge key">The <term>current
                           merge key</term> is a an array, whose members are sequences of atomic items.
                     There is one member in the array for each <elcode>xsl:merge-key</elcode> element
                     in the <termref def="dt-merge-key-specification"/>.
                     During evaluation of an
                           <elcode>xsl:merge</elcode> instruction, as each group of items with equal
                           <termref def="dt-combined-merge-key-value">combined merge key
                           values</termref> is processed, the current merge key is set to the
                        combined merge key value that these items have in common.</termdef></p></item></ulist><p>These values are made available through the functions
                  <function>current-merge-group</function>, <function>current-merge-key-array</function> and
                  <function>current-merge-key</function>.</p><p>The <termref def="dt-current-merge-group"/> and <termref def="dt-current-merge-key"/> are available within the sequence
            constructor contained by an <elcode>xsl:merge-action</elcode> element. The values are initially
            <termref def="dt-absent"/> during the evaluation of global variables and stylesheet parameters,
            during the evaluation of the <code nobreak="false">use</code> attribute or contained sequence constructor of
            <elcode>xsl:key</elcode>, and during the evaluation of the <code nobreak="false">initial-value</code> attribute of
            <elcode>xsl:accumulator</elcode> and the <code nobreak="false">select</code> attribute of contained sequence constructor of
            <elcode>xsl:accumulator-rule</elcode>. All <termref def="dt-invocation-construct">invocation constructs</termref>
               set the <termref def="dt-current-merge-group"/> and <termref def="dt-current-merge-key"/> to <termref def="dt-absent"/>. </p><note><p>Taken together, these rules mean that any invocation of
            <function>current-merge-group</function>, <function>current-merge-key-array</function>, 
               or <function>current-merge-key</function> that is not lexically scoped by an
            <elcode>xsl:merge-action</elcode> element will raise a dynamic error.</p></note><p>When an inner <elcode>xsl:merge</elcode> instruction is lexically nested within the
            <elcode>xsl:merge-action</elcode> element of an outer <elcode>xsl:merge</elcode> instruction, any use of
            <function>current-merge-group</function> or <function>current-merge-key</function> that appears within the
            <elcode>xsl:merge-action</elcode> of the inner <elcode>xsl:merge</elcode> instruction is a reference to the
               <termref def="dt-current-merge-group"/> or <termref def="dt-current-merge-key"/> of the inner
               <elcode>xsl:merge</elcode> instruction, while any such
            reference that appears within the outer <elcode>xsl:merge-action</elcode> element, but not
               within the inner <elcode>xsl:merge-action</elcode>, is a reference to the <termref def="dt-current-merge-group"/> or <termref def="dt-current-merge-key"/>
             of the outer <elcode>xsl:merge</elcode> instruction. This means, for example, that a
            reference to the current merge group of the outer <elcode>xsl:merge</elcode> can appear in the
            <code nobreak="false">select</code> attribute of an <elcode>xsl:merge-source</elcode> child of the inner <elcode>xsl:merge</elcode>.</p><p>On completion of the evaluation of the <elcode>xsl:merge-action</elcode> sequence constructor, 
               the <termref def="dt-current-merge-group"/>
               and <termref def="dt-current-merge-key"/> revert to their previous values.</p><div3 id="func-current-merge-group"><head>fn:current-merge-group</head><changes><change issue="407" PR="2274" date="2026-01-06">In XSLT 4.0, the function item <code nobreak="false">current-merge-group</code> retains the value of the current
         merge-key within its captured context.</change></changes><glist><gitem><label>Summary</label><def><p>Returns the group of items currently being processed by an <elcode>xsl:merge</elcode>
            instruction.</p></def></gitem><gitem><label>Signature</label><def><example role="signature"><proto isOp="no" prefix="fn" name="current-merge-group" return-type="item()*" returnEmptyOk="no" returnSeq="no" returnVaries="no" isSchema="no" isDatatype="no" isSpecial="no"><arg name="source" type="xs:string?" default="()"/></proto></example></def></gitem><gitem><label>Properties</label><def><p>This function is <xtermref spec="FO40" ref="dt-deterministic">deterministic</xtermref>, <xtermref spec="FO40" ref="dt-context-dependent">context-dependent</xtermref>,  and <xtermref spec="FO40" ref="dt-focus-independent">focus-independent</xtermref>. </p></def></gitem><gitem><label>Rules</label><def><p>The <termref def="dt-current-merge-group"/> is bound during evaluation of the
               <elcode>xsl:merge-action</elcode> child of an <elcode>xsl:merge</elcode> instruction. 
            If no <elcode>xsl:merge-action</elcode> is being
            evaluated, then the current merge group is <termref def="dt-absent"/>, in which case the
            function raises a dynamic error (see below).</p><p>The <termref def="dt-current-merge-group"/> (if not absent) is a map. 
            It contains the set of items, from all merge inputs, that share a common value for
            the merge key. This is structured as a map so that the items from each merge source can
            be identified. The key in the map is the value of the <code nobreak="false">name</code> attribute of the
            corresponding <elcode>xsl:merge-source</elcode> element (or an invented name, in its
            absence), and the associated value is the set of items contributed by that merge
            group.</p><p>The map itself is not made visible, but this function returns values derived from the
            map. Specifically, if the map is denoted by <var>$G</var>:</p><ulist><item><p><phrase diff="add" at="2023-02-16">If <code nobreak="false">$source</code> is supplied
               and is non-empty, the</phrase> function returns the value of the expression
                     <code nobreak="false">if (map:contains($source)) then $G($source) else error()</code>.
                  Informally, if there is an <elcode>xsl:merge-source</elcode> element whose
                     <code nobreak="false">name</code> attribute matches <code nobreak="false">$source</code>, the function returns
                  the items in the current merge group that are contributed by this merge source;
                  otherwise it raises a dynamic error (see below).</p></item><item><p><phrase diff="add" at="2023-02-16">Otherwise (when <code nobreak="false">$source</code> is absent or empty)</phrase>
                  the function returns the value of the expression
                     <code nobreak="false">sort(map:keys($G))!$G(.)</code>, where the <code nobreak="false">sort()</code> function
                  sorts the names of <elcode>xsl:merge-source</elcode> elements into the document
                  order of the <elcode>xsl:merge-source</elcode> elements in the stylesheet.
                  Informally, it returns all the items in the current merge group regardless of
                  which merge source they derive from.</p></item></ulist><p>Within the <termref def="dt-current-merge-group"/>, the ordering of items from the input
            sequences is as follows, in major-to-minor order:</p><ulist><item><p>Items are first ordered by the <elcode>xsl:merge-source</elcode> element that
                  defined the input sequence from which the item was taken; items from
                     <elcode>xsl:merge-source</elcode>
                  <var>A</var> precede items from <elcode>xsl:merge-source</elcode>
                  <var>B</var> if <var>A</var> precedes <var>B</var> in document order within the
                  stylesheet.</p></item><item><p>Items from different input sequences selected by the same
                     <elcode>xsl:merge-source</elcode> element are then ordered based on the order
                  of the anchor items in the sequence selected by evaluating the <code nobreak="false">select</code>
                  attribute of the <elcode>xsl:merge-source</elcode> element.</p></item><item><p>Finally, duplicate items from the same input sequence retain their order from the
                  input sequence.</p></item></ulist><p>Duplicates are not eliminated: for example, if the same node is
            selected in more than one input sequence, it may appear twice in the current 
            merge group.</p></def></gitem><gitem><label>Error Conditions</label><def><p>
            <error spec="XT" type="static" class="SE" code="3470"><p>It is a <termref def="dt-static-error">static error</termref> if the
                     <function>current-merge-group</function> function is used within a <termref def="dt-pattern">pattern</termref>.</p></error>
         </p><p>
            <error spec="XT" type="dynamic" class="DE" code="3480"><p>It is a <termref def="dt-dynamic-error">dynamic error</termref> if the
                     <function>current-merge-group</function> function is used when the current
                  merge group is <termref def="dt-absent">absent</termref>. The error
                     <rfc2119>may</rfc2119> be reported statically if it can be detected
                  statically.</p></error>
         </p><p>
            <error spec="XT" type="dynamic" class="DE" code="3490"><p>It is a <termref def="dt-dynamic-error">dynamic error</termref> if the
                     <code nobreak="false">$source</code> argument of the <function>current-merge-group</function>
                  function <phrase diff="add" at="2023-02-16">(when supplied)</phrase>
                  does not match the <code nobreak="false">name</code> attribute of any
                     <elcode>xsl:merge-source</elcode> element for the current merge operation. The
                  error <rfc2119>may</rfc2119> be reported statically if it can be detected
                  statically.</p></error>
         </p></def></gitem><gitem><label>Notes</label><def><note><p>Because the <termref def="dt-current-merge-group"/> is cleared by function calls and
            template calls, the <function>current-merge-group</function> function only has useful
            effect when the call appears as a descendant of an <elcode>xsl:merge-action</elcode>
            element.</p><p>If an <elcode>xsl:merge-source</elcode> element has no <code nobreak="false">name</code> attribute, then
            it is not possible to discover the items in the current merge group that derive
            specifically from that source, but these items will still be present in the current
            merge group, and will be included in the result when the function is called with no
            arguments.</p></note></def></gitem></glist></div3><div3 id="func-current-merge-key-array"><head>fn:current-merge-key-array</head><changes><change issue="1684" PR="1689" date="2025-01-14">New in 4.0</change></changes><glist><gitem><label>Summary</label><def><p>Returns the merge key of the 
            merge group currently being processed using the
               <elcode>xsl:merge</elcode> instruction.</p></def></gitem><gitem><label>Signature</label><def><example role="signature"><proto isOp="no" prefix="fn" name="current-merge-key-array" return-type="array(xs:anyAtomicType*)" returnEmptyOk="no" returnSeq="no" returnVaries="no" isSchema="no" isDatatype="no" isSpecial="no"/></example></def></gitem><gitem><label>Properties</label><def><p>This function is <xtermref spec="FO40" ref="dt-deterministic">deterministic</xtermref>, <xtermref spec="FO40" ref="dt-context-dependent">context-dependent</xtermref>,  and <xtermref spec="FO40" ref="dt-focus-independent">focus-independent</xtermref>. </p></def></gitem><gitem><label>Rules</label><def><p>The evaluation context for XPath <termref def="dt-expression">expressions</termref>
            includes a component called the <termref def="dt-current-merge-key"/>, which is an
            array whose members are sequence of atomic items. 
            The current merge key is the <termref def="dt-combined-merge-key-value">combined merge key value</termref> shared in common by all
            the items within the <termref def="dt-current-merge-group">current merge
            group</termref>. </p><p>The function <function>current-merge-key-array</function> returns the 
            <termref def="dt-current-merge-key">current merge key</termref> as an array.</p><p>While the <elcode>xsl:merge-action</elcode> child of an 
            <elcode>xsl:merge</elcode> instruction is being evaluated, the 
            <termref def="dt-current-merge-key"/> will be an array with one member
            for each <elcode>xsl:merge-key</elcode> element, where the value 
            of that member is the result of evaluating and atomizing the
            <code nobreak="false">select</code> expression, or the contained sequence constructor,
            or the context item, as appropriate.</p><p>At other times, the current merge key will be <termref def="dt-absent">absent</termref>.</p><p>The <termref def="dt-combined-merge-key-value">merge keys</termref> of
               all items in a group are not necessarily identical. For example, one might be an
                  <code nobreak="false">xs:float</code> while another is a numerically equal
            <code nobreak="false">xs:decimal</code>. The <function>current-merge-key-array</function>
            function returns the combined merge key of the 
            first item in the group, after atomization and
            casting of <code nobreak="false">xs:untypedAtomic</code> items to <code nobreak="false">xs:string</code>.</p></def></gitem><gitem><label>Error Conditions</label><def><p>
            <error spec="XT" type="static" class="SE" code="3500"><p>It is a <termref def="dt-static-error">static error</termref> if the
                     <function>current-merge-key-array</function> or
                  <function>current-merge-key</function> function 
                  is used within a <termref def="dt-pattern">pattern</termref>.</p></error>
         </p><p>
            <error spec="XT" type="dynamic" class="DE" code="3510"><p>It is a <termref def="dt-dynamic-error">dynamic error</termref> if the
                     <function>current-merge-key-array</function> or 
                  <function>current-merge-key</function> function is used when the current
                  merge key is <termref def="dt-absent">absent</termref>, or when it is invoked
                  in the course of evaluating a pattern. The error <rfc2119>may</rfc2119> be
                  reported statically if it can be detected statically.</p></error>
         </p></def></gitem></glist></div3><div3 id="func-current-merge-key"><head>fn:current-merge-key</head><changes><change issue="407" PR="2274" date="2026-01-06">In XSLT 4.0, the function item <code nobreak="false">current-merge-key#0</code> retains the value of the current
         group within its captured context.</change></changes><glist><gitem><label>Summary</label><def><p>Returns the merge key of the 
            merge group currently being processed using the
               <elcode>xsl:merge</elcode> instruction.</p></def></gitem><gitem><label>Signature</label><def><example role="signature"><proto isOp="no" prefix="fn" name="current-merge-key" return-type="xs:anyAtomicType*" returnEmptyOk="no" returnSeq="no" returnVaries="no" isSchema="no" isDatatype="no" isSpecial="no"/></example></def></gitem><gitem><label>Properties</label><def><p>This function is <xtermref spec="FO40" ref="dt-deterministic">deterministic</xtermref>, <xtermref spec="FO40" ref="dt-context-dependent">context-dependent</xtermref>,  and <xtermref spec="FO40" ref="dt-focus-independent">focus-independent</xtermref>. </p></def></gitem><gitem><label>Rules</label><def><p>The function returns the result of the expression
         <code nobreak="false">current-merge-key-array()?*</code>, that is, the result
         of flattening the contents of the current merge key into
         a sequence of atomic items.</p></def></gitem><gitem><label>Error Conditions</label><def><p>The same error conditions apply as for the <function>current-merge-key-array</function>
         function.</p></def></gitem><gitem><label>Notes</label><def><note><p>This function is retained from XSLT 3.0 both for backwards compatibility,
            and for convenience. It is useful in the common case where there is a single
            merge key whose value is a single atomic item; it is also usable if there
            are multiple merge keys whose values are single atomic items. In the general
         case where there are multiple merge keys each of which may contain zero or more
         atomic items, the function <function>current-merge-key-array</function>
         is needed.</p></note></def></gitem></glist></div3></div2><div2 id="merge-action"><head>The <elcode>xsl:merge-action</elcode> Element</head><p>The <elcode>xsl:merge-action</elcode> child of an <elcode>xsl:merge</elcode>
               instruction defines the processing to be applied for each distinct 
               <termref def="dt-combined-merge-key-value"/> found in the input sequences to the
                  <elcode>xsl:merge</elcode> instruction.</p><e:element-syntax xmlns:e="http://www.w3.org/1999/XSL/Spec/ElementSyntax" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" name="merge-action">
      <e:model name="sequence-constructor"/>
      <e:allowed-parents>
         <e:parent name="merge"/>
      </e:allowed-parents>
   </e:element-syntax><p>The merge key values for each item in an input sequence are calculated based on the
               corresponding <elcode>xsl:merge-key</elcode> elements, in the same way as <termref def="dt-sort-key-value">sort key values</termref> are calculated using a sequence
               of <elcode>xsl:sort</elcode> elements (see <specref ref="sorting-process"/>). If
               several items from the same or from different input sequences have the same values
               for all their merge keys (comparing pairwise), then they are considered to form a
               group. The sequence constructor contained in the <elcode>xsl:merge-action</elcode>
               element is evaluated once for each such group of items, and the result of the
                  <elcode>xsl:merge</elcode> instruction is the concatenation of the results
               obtained by processing each group in turn.</p><p>The groups are processed one by one, based on the values of
                  the merge keys for the group. If group <var>G</var> has a set of merge
               key values <var>M</var>, while group <var>H</var> has a set of merge key values
                  <var>N</var>, then in the result of the <elcode>xsl:merge</elcode> instruction,
               the result of processing group <var>G</var> will precede the result of processing
                  <var>H</var> if and only if <var>M</var> precedes <var>N</var> in the sort order
               defined by the <code nobreak="false">lang</code>, <code nobreak="false">order</code>, <code nobreak="false">collation</code>,
                  <code nobreak="false">case-order</code>, and <code nobreak="false">data-type</code> attributes of the merge key
               definitions.</p><p><phrase diff="chg" at="2022-01-01">Comparison of merge key values follows the rules for 
               <elcode>xsl:sort</elcode> given in <specref ref="comparing-sort-keys"/>. 
               This means that except for special cases such as empty sequences and <code nobreak="false">NaN</code></phrase>, 
               two sets of merge key values are distinct if any corresponding items in
               the two sets of values do not compare equal under the rules for the XPath
                  <code nobreak="false">eq</code> operator, under the collating rules for the corresponding merge
               key definition. In rare cases, when considering more than two sets of merge key
               values, ambiguities may arise because of the non-transitivity of the <code nobreak="false">eq</code>
               operator when applied across different numeric types. In this situation, the
               partitioning of items into sets having distinct key values is handled in the same way
               as for <elcode>xsl:for-each-group</elcode> (see <specref ref="non-transitivity"/>),
               and is to some extent <termref def="dt-implementation-dependent">implementation-dependent</termref>. 
            
            </p><p>The <termref def="dt-focus">focus</termref> for evaluation of the sequence
               constructor contained in the <elcode>xsl:merge-action</elcode> element is as
               follows:</p><ulist><item><p>The <termref def="dt-context-item">context item</termref> is the first item in
                     the group being processed, that is
                           <code nobreak="false">current-merge-group()[1]</code></p></item><item><p>The <termref def="dt-context-position">context position</termref> is the
                     position of the current group within the sequence of groups (so the first
                     evaluation of <elcode>xsl:merge-action</elcode> has <code nobreak="false">position()=1</code>,
                     the second has <code nobreak="false">position()=2</code>, and so on).</p></item><item><p>The <termref def="dt-context-size">context size</termref> is as follows:</p><ulist><item><p>If any of the <elcode>xsl:merge-source</elcode> elements within the <elcode>xsl:merge</elcode> instruction specifies 
                        <code nobreak="false">streamable="yes"</code> (explicitly or implicitly), then absent.</p><note><p>This means that within the <elcode>xsl:merge-action</elcode> of a streamable <elcode>xsl:merge</elcode>, 
                           calling <code nobreak="false">last()</code> raises error <xerrorref spec="XP40" class="DY" code="0002"/>.</p></note></item><item><p>Otherwise, the number of groups, that is, the number of distinct sets of merge key values.
                        </p></item></ulist></item></ulist><example><head>Selective Processing of Merge Inputs</head><p>Consider a situation where there are two merge sources, named <code nobreak="false">"master"</code> and
                  <code nobreak="false">"update"</code>; the master source identifies a single merge input file (the master
                  file), while the update source identifies a set of <var>N</var> update files,
                  perhaps one for each day of the week. The required logic is that if a merge key is
                  present only in the master file, then the corresponding item should be copied to
                  the output; if it is present in a single update file then that item replaces the
                  corresponding item from the master file; if it is present in several update files,
                  then an error is raised. This can be achieved as follows:</p><eg role="xslt-instruction" xml:space="preserve">&lt;xsl:merge&gt;
  &lt;xsl:merge-source name="master" 
                    for-each-source="'master.xml'"
                    streamable="yes"
                    select="/events/event"&gt;
      &lt;xsl:merge-key select="@key"/&gt;
  &lt;/xsl:merge-source&gt;
  &lt;xsl:merge-source name="updates" 
                    for-each-source="uri-collection('updates')"
                    streamable="yes"
                    select="/events/event-change"&gt;
      &lt;xsl:merge-key select="@affected-key"/&gt;
  &lt;/xsl:merge-source&gt;
  &lt;xsl:merge-action&gt;
    &lt;xsl:choose&gt;
      &lt;xsl:when test="empty(current-merge-group('master'))"&gt;
        &lt;xsl:message&gt;
           Error: update is present with no matching master record!
        &lt;/xsl:message&gt;
      &lt;/xsl:when&gt;
      &lt;xsl:when test="empty(current-merge-group('updates'))"&gt;
        &lt;xsl:copy-of select="current-merge-group('master')"/&gt;
      &lt;/xsl:when&gt;
      &lt;xsl:when test="count(current-merge-group('updates')) = 1"&gt;
        &lt;xsl:copy-of select="current-merge-group('updates')"/&gt;
      &lt;/xsl:when&gt;
      &lt;xsl:otherwise&gt;
        &lt;xsl:message&gt;
           Conflict: multiple updates for the same master record!
        &lt;/xsl:message&gt;
      &lt;/xsl:otherwise&gt;
    &lt;/xsl:choose&gt;
  &lt;/xsl:merge-action&gt;
&lt;/xsl:merge&gt;
            </eg><p>Some words of explanation:</p><ulist><item><p>Error messages are produced if there is an update element
                        whose key does not correspond to any element in the master source, or if
                        there is more than one update element corresponding to the same master
                        element.</p></item><item><p>In the absence of errors, if there is a single update
                        element then it is copied to the output; if there is none, then the master
                        element is copied.</p></item></ulist></example></div2><div2 id="merge-examples"><head>Examples of xsl:merge</head><p>Previous sections introduced examples designed to illustrate some specific features
               of the <elcode>xsl:merge</elcode> instruction. This section provides some further
               examples to illustrate different ways in which the instruction can be used.</p><example><head>Applying Transactions to a Master File</head><p>This example applies transactions from a transaction file to a master file.
                  Records in the master file for which there is no corresponding transaction are
                  copied unchanged. The transaction file contains instructions to delete, replace,
                  or insert records identified by an ID value. The master file is known to be sorted
                  on the ID value; the transaction file is unsorted.</p><p>Master file document structure:</p><eg xml:space="preserve" role="xml">&lt;data&gt;
  &lt;record ID="A0001"&gt;...&lt;/record&gt;
  &lt;record ID="A0002"&gt;...&lt;/record&gt;
  &lt;record ID="A0003"&gt;...&lt;/record&gt;
&lt;/data&gt;</eg><p>Transaction file document structure:</p><eg xml:space="preserve" role="xml">&lt;transactions&gt;
  &lt;update record="A0004" action="insert"&gt;...&lt;/update&gt;
  &lt;update record="A0002" action="delete"/&gt;
  &lt;update record="A0003" action="replace"&gt;...&lt;/update&gt;
&lt;/transactions&gt;</eg><p>Solution:</p><eg xml:space="preserve" role="xslt-instruction">
 &lt;xsl:merge&gt;
  &lt;xsl:merge-source name="master" 
                    select="doc('master.xml')/data/record"&gt;
      &lt;xsl:merge-key select="@ID"/&gt;
  &lt;/xsl:merge-source&gt;
  &lt;xsl:merge-source name="updates"
                    sort-before-merge="yes"
                    select="doc('transactions.xml')/transactions/update"&gt;     
      &lt;xsl:merge-key select="@record"/&gt;
  &lt;/xsl:merge-source&gt;
  &lt;xsl:merge-action&gt;
    &lt;xsl:choose&gt;
      &lt;xsl:when test="empty(current-merge-group('updates'))"&gt;
        &lt;xsl:copy-of select="current-merge-group('master')"/&gt;
      &lt;/xsl:when&gt;
      &lt;xsl:when test="current-merge-group('updates')/@action=('insert', 'replace')"&gt;
        &lt;record ID="{current-merge-key()}"&gt;
          &lt;xsl:copy-of select="current-merge-group('updates')/*"/&gt;
        &lt;/record&gt;
      &lt;/xsl:when&gt;
      &lt;xsl:when test="current-merge-group('updates')/@action='delete'"/&gt;
    &lt;/xsl:choose&gt;
  &lt;/xsl:merge-action&gt;
  &lt;/xsl:merge&gt;</eg></example><example><head>Merging Two Sequences of Numbers</head><p>The <elcode>xsl:merge</elcode> instruction can be used to determine the union,
                  intersection, or difference of two sequences of numbers (or other atomic items).
                  This code gives the union:</p><eg role="xslt-instruction" xml:space="preserve">&lt;xsl:merge&gt;
  &lt;xsl:merge-source select="1 to 30"&gt;
      &lt;xsl:merge-key select="."/&gt;
  &lt;/xsl:merge-source&gt;
  &lt;xsl:merge-source select="20 to 40"&gt;
      &lt;xsl:merge-key select="."/&gt;
  &lt;/xsl:merge-source&gt;
  &lt;xsl:merge-action&gt;
    &lt;xsl:sequence select="current-merge-key()"/&gt;
  &lt;/xsl:merge-action&gt;
&lt;/xsl:merge&gt;
               </eg><p>While this gives the intersection:</p><eg role="xslt-instruction" xml:space="preserve">&lt;xsl:merge&gt;
  &lt;xsl:merge-source select="1 to 30"&gt;
      &lt;xsl:merge-key select="."/&gt;
  &lt;/xsl:merge-source&gt;
  &lt;xsl:merge-source select="20 to 40"&gt;
      &lt;xsl:merge-key select="."/&gt;
  &lt;/xsl:merge-source&gt;
  &lt;xsl:merge-action&gt;
    &lt;xsl:if test="count(current-merge-group()) eq 2"&gt;
      &lt;xsl:sequence select="current-merge-key()"/&gt;
    &lt;/xsl:if&gt;
  &lt;/xsl:merge-action&gt;
&lt;/xsl:merge&gt;
               </eg></example></div2></div1><div1 id="splitting"><head>Splitting</head><p>Sometimes it is convenient to be able to compute multiple results during a single scan
            of the input data. For example, a transformation may wish to rename selected elements,
            and also to output a count of how many elements have been renamed. Traditionally in a
            functional language this means computing two separate functions of the input sequence,
            which (in the absence of sophisticated optimization) will result in the input being
            scanned twice. This is inconsistent with streaming, where the input is only available to
            be scanned once, and it can also lead to poor performance in non-streaming
            applications.</p><p>To meet this requirement, XSLT 3.0 introduces the instruction <elcode>xsl:fork</elcode>.
            The content of this instruction is a restricted form
               of
            <termref def="dt-sequence-constructor">sequence constructor</termref>, and in a formal
            sense the effect of the instruction is simply to return the result of evaluating the
            sequence constructor. However, the presence of the instruction affects the analysis of
            streamability (see <xspecref spec="SG40" ref="streamability"/>). In particular, when
               <elcode>xsl:fork</elcode> is used in a context where streaming is required, each
            independent instruction within the sequence constructor must be streamable, but the
            analysis assumes that these instructions can all be evaluated during a single pass of
            the streamed input document.</p><note><p>The semantics of the instruction require a number of result sequences to be computed
               during a single pass of the input. A processor may interpret this as a request to use
               multiple threads. However, implementations using a single thread are feasible, and
               this instruction is not intended primarily as a means for stylesheet authors to
               express their intentions with regard to multi-threaded execution.</p></note><note><p>Because multiple results are computed during a single pass of the input, and then
               concatenated into a single sequence, this instruction will generally involve some
               buffering of results. The amount of memory used should not exceed that needed to hold
               the results of the instruction. However, within this principle, implementations may
               adopt a variety of strategies for evaluation; for example, there may be cases where
               buffering of the input is more efficient than buffering of output.</p><p>Generally, stylesheet authors indicate that buffering of input is the preferred
               strategy by using the <function>copy-of</function> or <function>snapshot</function>
               functions, and indicate that buffering of output is preferred by using
                  <elcode>xsl:fork</elcode>. However, conformant processors are not constrained in
               their choice of evaluation strategies.</p></note><p>The content model of the <elcode>xsl:fork</elcode>
            instruction (given that an XSLT 3.0 processor ignores <elcode>xsl:fallback</elcode>)
            takes two possible forms:</p><olist><item><p>A sequence of <elcode>xsl:sequence</elcode> instructions</p></item><item><p>A single <elcode>xsl:for-each-group</elcode> instruction. This will normally use
                  the <code nobreak="false">group-by</code> attribute, because in all other cases the containing
                     <elcode>xsl:fork</elcode> instruction has no useful effect.</p></item></olist><p>The first form is appropriate when splitting a single input
            stream into a fixed number of output streams, known statically: for example, one output
            stream for credit transactions, a second for debit transactions. The second form is
            appropriate when the number of output streams depends on the data: for example, one
            output stream for each distinct city name found in the input data.</p><p>The following section describes the <elcode>xsl:fork</elcode> instruction more
            formally.</p><div2 id="fork-instruction"><head>The <code nobreak="false">xsl:fork</code> Instruction</head><e:element-syntax xmlns:e="http://www.w3.org/1999/XSL/Spec/ElementSyntax" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" name="fork">
      <e:in-category name="instruction"/>
      <e:sequence>
         <e:element name="fallback" repeat="zero-or-more"/>
         <e:choice>
            <e:sequence repeat="zero-or-more">
               <e:element name="sequence"/>
               <e:element name="fallback" repeat="zero-or-more"/>
            </e:sequence>
            <e:sequence>
               <e:element name="for-each-group"/>
               <e:element name="fallback" repeat="zero-or-more"/>
            </e:sequence>
         </e:choice>
      </e:sequence>
      <e:allowed-parents>
         <e:parent-category name="sequence-constructor"/>
      </e:allowed-parents>
   </e:element-syntax><note><p>The content model can be described as follows: there is either a single
                     <elcode>xsl:for-each-group</elcode> instruction, or a sequence of zero or more
                     <elcode>xsl:sequence</elcode> instructions; in addition,
                     <elcode>xsl:fallback</elcode> instructions may be added anywhere.</p></note><p>The result of the <elcode>xsl:fork</elcode> instruction is the sequence formed by
               concatenating the results of evaluating each of its contained  instructions, in order.
               That is, the result can be determined by treating the content as a <termref def="dt-sequence-constructor">sequence constructor</termref> and evaluating it as
               such.</p><note><p>Any <elcode>xsl:fallback</elcode> children will be ignored by an XSLT 3.0
                  processor.</p></note><p>By using the <elcode>xsl:fork</elcode> instruction, the
               stylesheet author is suggesting to the <termref def="dt-processor">processor</termref> that buffering of output is acceptable even though this might
               use unbounded memory and thus violate the normal expectations of streamable
               processing</p><p>The presence of an <elcode>xsl:fork</elcode> instruction affects the analysis of
               streamability, as described in <xspecref spec="SG40" ref="streamability"/>.</p></div2><div2 id="splitting-examples"><head>Examples of Splitting with Streamed Data</head><p>This section gives examples of how splitting using <elcode>xsl:fork</elcode> can be
               used to enable streaming of input documents in cases where several results need to be
               computed during a single pass over the input data.</p><example><head>Splitting a Transaction File into Credits and Debits</head><p>Consider a transaction file that contains a sequence of debits and credits:</p><eg role="xml" xml:space="preserve">&lt;transactions&gt;
  &lt;transaction value="5.60"/&gt;
  &lt;transaction value="11.20"/&gt;
  &lt;transaction value="-3.40"/&gt;
  &lt;transaction value="8.90"/&gt;
  &lt;transaction value="-1.99"/&gt;
&lt;/transactions&gt;</eg><p>where the requirement is to split this into two separate files containing credits
                  and debits respectively.</p><p>This can be achieved in <xtermref spec="SG40" ref="dt-guaranteed-streamable"/> code as
                  follows:</p><eg role="xslt-instruction" xml:space="preserve">
&lt;xsl:source-document streamable="yes" href="transactions.xml"&gt;
  &lt;xsl:fork&gt;
    &lt;xsl:sequence&gt;
      &lt;xsl:result-document href="credits.xml"&gt;
        &lt;credits&gt;
          &lt;xsl:for-each select="transactions/transaction[@value &amp;gt;= 0]"&gt;
            &lt;xsl:copy-of select="."/&gt;
          &lt;/xsl:for-each&gt;
        &lt;/credits&gt;
      &lt;/xsl:result-document&gt;
    &lt;/xsl:sequence&gt;
    &lt;xsl:sequence&gt;
      &lt;xsl:result-document href="debits.xml"&gt;
        &lt;debits&gt;
          &lt;xsl:for-each select="transactions/transaction[@value &amp;lt; 0]"&gt;
            &lt;xsl:copy-of select="."/&gt;
          &lt;/xsl:for-each&gt;
        &lt;/debits&gt;
      &lt;/xsl:result-document&gt;
    &lt;/xsl:sequence&gt;  
  &lt;/xsl:fork&gt;
&lt;/xsl:source-document&gt;
               </eg><p>In the absence of the <elcode>xsl:fork</elcode> instruction, this would not be
                  streamable, because the sequence constructor includes two 
                  <xtermref spec="SG40" ref="dt-consuming"/> instructions. With the addition of the
                     <elcode>xsl:fork</elcode> instruction, however, each
                     <elcode>xsl:result-document</elcode> instruction is allowed to make a downwards
                  selection. </p><p>One possible implementation model for this is as follows: a single thread reads
                  the source document, and sends parsing events such as start-element and
                  end-element to two other threads, each of which is writing one of the two result
                  documents. Each of these implements the downwards-selecting path expression using
                  a process that waits until the next <code nobreak="false">transaction</code> start-element event
                  is received; when this event is received, the process examines the
                     <code nobreak="false">@value</code> attribute to determine whether or not this transaction is
                  to be copied; if it is, then all events until the matching
                     <code nobreak="false">transaction</code> end-element event are copied to the serializer for the
                  result document; otherwise, these events are discarded.</p></example><example><head>Splitting a Transaction File by Customer Account</head><p>Consider a transaction file that contains a sequence of debits and credits:</p><eg role="xml" xml:space="preserve">&lt;transactions&gt;
  &lt;transaction value="5.60" account="01826370"/&gt;
  &lt;transaction value="11.20" account="92741838"/&gt;
  &lt;transaction value="-3.40" account="01826370"/&gt;
  &lt;transaction value="8.90" account="92741838"/&gt;
  &lt;transaction value="-1.99" account="43861562"/&gt;
&lt;/transactions&gt;</eg><p>where the requirement is to split this into a number of separate files, one for
                  each account number found in the input.</p><p>This can be achieved in <xtermref spec="SG40" ref="dt-guaranteed-streamable"/> code as
                  follows:</p><eg role="xslt-instruction" xml:space="preserve">
&lt;xsl:source-document streamable="yes" href="transactions.xml"&gt;
  &lt;xsl:fork&gt;
    &lt;xsl:for-each-group select="transactions/transaction" group-by="@account"&gt;
      &lt;xsl:result-document href="account{current-grouping-key()}.xml"&gt;
        &lt;transactions account="{current-grouping-key()}"&gt;
          &lt;xsl:copy-of select="current-group()"/&gt;
        &lt;/transactions&gt;
      &lt;/xsl:result-document&gt;
    &lt;/xsl:for-each-group&gt;
  &lt;/xsl:fork&gt;
&lt;/xsl:source-document&gt;
               </eg><p>In the absence of the <elcode>xsl:fork</elcode> instruction, this would not be
                  streamable, because in the general case the output of
                     <elcode>xsl:for-each-group</elcode> with a <code nobreak="false">group-by</code> attribute
                  needs to be buffered. (The streamability rules do not recognize an
                     <elcode>xsl:for-each-group</elcode> whose body comprises an
                     <elcode>xsl:result-document</elcode> instruction as a special case.) With the
                  addition of the <elcode>xsl:fork</elcode> instruction, however, the code becomes
                  guaranteed streamable. </p><p>One possible implementation model for this is as follows: the processor opens a
                  new serializer each time a new account number is encountered in the input, and
                  writes the <code nobreak="false">&lt;transactions&gt;</code> start tag to the serializer. When a
                     <code nobreak="false">transaction</code> element is encountered in the input, it is copied to
                  the relevant serializer, according to the value of the <code nobreak="false">account</code>
                  attribute. At the end of the input, a <code nobreak="false">&lt;transactions&gt;</code> end tag is
                  written to each of the serializers, and each output file is closed.</p><p>In the more general case, where the body of the
                     <elcode>xsl:for-each-group</elcode> instruction contributes output to the
                  principal result document, the output generated by processing each group needs to
                  be buffered in memory. The requirement to use <elcode>xsl:fork</elcode> exists so
                  that this use of (potentially unbounded) memory has to be a conscious decision by
                  the stylesheet author.</p></example><example><head>Arithmetic using Multiple Child Elements as Operands</head><p>The rules for streamability do not allow two instructions in a sequence
                  constructor to both read child or descendant elements of the context node, which
                  makes it tricky to perform a calculation in which multiple child elements act as
                  operands. This restriction can be avoided by using <elcode>xsl:fork</elcode>, as
                  shown below, where each of the two branches of the <elcode>xsl:fork</elcode>
                  instruction selects children of the context node.</p><eg role="xslt-declaration" xml:space="preserve">
&lt;xsl:template match="order" mode="a-streamable-mode"&gt;                  
  &lt;xsl:variable name="price-and-discount" as="xs:decimal+"&gt;
    &lt;xsl:fork&gt;
      &lt;xsl:sequence select="xs:decimal(price)"/&gt;
      &lt;xsl:sequence select="xs:decimal(discount)"/&gt;
    &lt;/xsl:fork&gt;
  &lt;/xsl:variable&gt;
  &lt;xsl:value-of select="$price-and-discount[1] - $price-and-discount[2]"/&gt;
  &lt;/xsl:template&gt;</eg><p>A possible implementation strategy here is for events from the XML parser to be
                  sent to two separate agents (perhaps but not necessarily running in different
                  threads), one of which computes <code nobreak="false">xs:decimal(price)</code> and the other
                     <code nobreak="false">xs:decimal(discount)</code>; on completion the results computed by the
                  two agents are appended to the sequence that forms the value of the variable.</p><p>With this strategy, the processor would require sufficient memory to hold the
                  results of evaluating each branch of the fork. If these results (unlike this
                  example) are large, this could defeat the purpose of streaming by requiring large
                  amounts of memory; nevertheless, this code is treated as streamable.</p><note><p>An alternative solution to this requirement is to use map constructors: see
                        <xspecref spec="XP40" ref="id-map-constructors"/>.</p></note></example><example><head>Deleting Elements, and Counting Deletions</head><p>In this example the input is a narrative document containing <code nobreak="false">note</code>
                  elements at any level of nesting. The requirement is to output a copy of the input
                  document in which (a) the <code nobreak="false">note</code> elements have been removed, and (b) a
                     <code nobreak="false">footnote</code> is added at the end indicating how many <code nobreak="false">note</code>
                  elements have been deleted.</p><eg role="xslt-declaration" xml:space="preserve">&lt;xsl:mode on-no-match="shallow-copy" streamable="yes"/&gt;

&lt;xsl:template match="note"/&gt;

&lt;xsl:template match="/*"&gt;
  &lt;xsl:fork&gt;
    &lt;xsl:sequence&gt;
      &lt;xsl:apply-templates/&gt;
    &lt;/xsl:sequence&gt;
    &lt;xsl:sequence&gt;
      &lt;footnote&gt;
        &lt;p&gt;Removed &lt;xsl:value-of select="count(.//note)"/&gt; 
                 note elements.&lt;/p&gt;
      &lt;/footnote&gt;
    &lt;/xsl:sequence&gt;  
  &lt;/xsl:fork&gt;
&lt;/xsl:template&gt;
               </eg><p>The <elcode>xsl:fork</elcode> instruction contains two independent branches. These
                  can therefore be evaluated in the same pass over the input data. The first branch
                  (the <elcode>xsl:apply-templates</elcode> instruction) causes everything except
                  the <code nobreak="false">note</code> elements to be copied to the result; the second instruction
                  (the literal result element <code nobreak="false">footnote</code>) outputs a count of the number
                  of descendant <code nobreak="false">note</code> elements.</p><p>Note that although the processing makes a single pass over the input stream, there
                  is some buffering of results required, because the results of the instructions
                  within the <elcode>xsl:fork</elcode> instruction need to be concatenated. In this
                  case an intelligent implementation might be able to restrict the buffered data to
                  a single integer.</p><p>In a formal sense, however, the result is exactly the same as if the
                     <elcode>xsl:fork</elcode> element were not there.</p><p>An alternative way of solving this example problem would be to
                  count the number of <code nobreak="false">note</code> elements using an accumulator: see <specref ref="accumulators"/>.</p></example></div2></div1><div1 id="regular-expressions"><head>Regular Expressions</head><p>The function library for XPath 3.0
            defines several functions that make use of
            regular expressions:</p><ulist><item><p>
                  <xfunction>matches</xfunction> returns a boolean result that indicates whether or
                  not a string matches a given regular expression.</p></item><item><p>
                  <xfunction>replace</xfunction> takes a string as input and returns a string
                  obtained by replacing all substrings that match a given regular expression with a
                  replacement string.</p></item><item><p>
                  <xfunction>tokenize</xfunction> returns a sequence of strings formed by breaking a
                  supplied input string at any separator that matches a given regular
                  expression.</p></item><item><p>
                  <xfunction>analyze-string</xfunction> returns a tree of nodes that effectively add
                  markup to a string indicating the parts of the string that matched the regular
                  expression, as well as its captured groups.</p></item></ulist><p>These functions are described in <bibref ref="xpath-functions-40"/>.</p><p>Supplementing these functions, XSLT provides
            an instruction <elcode>xsl:analyze-string</elcode>, which is defined in this
            section.</p><note><p>The <elcode>xsl:analyze-string</elcode> instruction predates the
                  <xfunction>analyze-string</xfunction> function, and provides very similar
               functionality, though in a different way.</p></note><p>The regular expressions used by this instruction, and the flags that control the
            interpretation of these regular expressions, <rfc2119>must</rfc2119> conform to the
            syntax defined in <bibref ref="xpath-functions-40"/> (see <xspecref spec="FO40" ref="regex-syntax"/>), 
            which is itself based on the syntax defined in <bibref ref="xmlschema-2"/>.</p><p>As described in <xspecref spec="FO40" ref="regex-syntax"/>, the effect of processing a string
         using a regular expression is a sequence of non-overlapping matching segments, each of which is
         associated with a set of captured groups, represented as a map from a group number to a segment
         of the input string. The term <term>segment</term> here means a contiguous (and possibly empty)
         subsequence of characters from the input string, characterized by a starting position and ending
         position within that string.</p><div2 id="analyze-string"><head>The <code nobreak="false">xsl:analyze-string</code> Instruction</head><changes><change issue="443" PR="489" date="2023-05-16">
                  The <elcode>xsl:matching-substring</elcode> and <elcode>xsl:non-matching-substring</elcode>
                  elements within <elcode>xsl:analyze-string</elcode> may now take a <code nobreak="false">select</code> attribute
                  in place of a contained sequence constructor.
               </change><change issue="998" PR="1856" date="2025-03-18">
                  The rules for <elcode>xsl:analyze-string</elcode> have been adjusted to allow for new capabilities in regular expressions, such as
                  zero-width assertions.
               </change></changes><e:element-syntax xmlns:e="http://www.w3.org/1999/XSL/Spec/ElementSyntax" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" name="analyze-string">
      <e:in-category name="instruction"/>
      <e:attribute name="select" required="yes">
         <e:data-type name="expression"/>
      </e:attribute>
      <e:attribute name="regex" required="yes">
         <e:attribute-value-template>
            <e:data-type name="string"/>
         </e:attribute-value-template>
      </e:attribute>
      <e:attribute name="flags" required="no" default="''">
         <e:attribute-value-template>
            <e:data-type name="string"/>
         </e:attribute-value-template>
      </e:attribute>
      <e:sequence>
         <e:element repeat="zero-or-one" name="matching-substring"/>
         <e:element repeat="zero-or-one" name="non-matching-substring"/>
         <e:element repeat="zero-or-more" name="fallback"/>
      </e:sequence>
      <e:allowed-parents>
         <e:parent-category name="sequence-constructor"/>
      </e:allowed-parents>
   </e:element-syntax><e:element-syntax xmlns:e="http://www.w3.org/1999/XSL/Spec/ElementSyntax" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" name="matching-substring">
      <e:attribute name="select" required="no">
         <e:data-type name="expression"/>
      </e:attribute>
      <e:model name="sequence-constructor"/>
      <e:allowed-parents>
         <e:parent name="analyze-string"/>
      </e:allowed-parents>
   </e:element-syntax><e:element-syntax xmlns:e="http://www.w3.org/1999/XSL/Spec/ElementSyntax" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" name="non-matching-substring">
      <e:attribute name="select" required="no">
         <e:data-type name="expression"/>
      </e:attribute>
      <e:model name="sequence-constructor"/>
      <e:allowed-parents>
         <e:parent name="analyze-string"/>
      </e:allowed-parents>
   </e:element-syntax><p>The <elcode>xsl:analyze-string</elcode> instruction takes as input a string (the
               result of evaluating the expression in the <code nobreak="false">select</code> attribute), a
               regular expression (the <termref def="dt-effective-value"/> of the <code nobreak="false">regex</code> attribute),
            and a set of flags.</p><p>If the result of evaluating the <code nobreak="false">select</code> expression is the empty sequence, 
               it is treated as a zero-length string.
                  If the value is not a string, it is converted to a string by applying the
                  <termref def="dt-coercion-rules"/>.</p><p>The <code nobreak="false">flags</code> attribute may be used to control the interpretation of the
               regular expression. If the attribute is omitted, the effect is the same as supplying
               a zero-length string. This is interpreted in the same way as the <code nobreak="false">$flags</code>
               attribute of the functions <xfunction>matches</xfunction>,
                  <xfunction>replace</xfunction>, and <xfunction>tokenize</xfunction>. Specifically,
               if it contains the letter <code nobreak="false">m</code>, the match operates in multiline mode. If it
               contains the letter <code nobreak="false">s</code>, it operates in dot-all mode. If it contains the
               letter <code nobreak="false">i</code>, it operates in case-insensitive mode. If it contains the
               letter <code nobreak="false">x</code>, then whitespace within the regular expression is ignored. For
               more detailed specifications of these modes, see <bibref ref="xpath-functions-40"/>
                  (<xspecref ref="flags" spec="FO40"/>).</p><note><p>Because the <code nobreak="false">regex</code> attribute is an attribute value template, curly
                  brackets within the regular expression must be doubled. For example, to match a
                  sequence of one to five characters, write <code nobreak="false">regex=".{{1,5}}"</code>. For
                  regular expressions containing many curly brackets it may be more convenient to
                  use a notation such as <code nobreak="false">regex="{'[0-9]{1,5}[a-z]{3}[0-9]{1,2}'}"</code>, or
                  to use a variable:</p><eg xml:space="preserve">&lt;xsl:variable name="regex" 
               expand-text="no"&gt;[0-9]{1,5}[a-z]{3}[0-9]{1,2}&lt;/xsl:variable&gt;
&lt;xsl:analyze-string regex="{$regex}"....  </eg></note><p>The <elcode>xsl:analyze-string</elcode> instruction may have two child elements:
                  <elcode>xsl:matching-substring</elcode> and
                  <elcode>xsl:non-matching-substring</elcode>. Both elements are optional, and
               neither may appear more than once. At least one of them must be present. If both are
               present, the <elcode>xsl:matching-substring</elcode> element must come first.</p><p>The content of the <elcode>xsl:analyze-string</elcode> instruction must take one of
               the following forms:</p><olist><item><p>A single <elcode>xsl:matching-substring</elcode> instruction, followed by zero
                     or more <elcode>xsl:fallback</elcode> instructions</p></item><item><p>A single <elcode>xsl:non-matching-substring</elcode> instruction, followed by
                     zero or more <elcode>xsl:fallback</elcode> instructions</p></item><item><p>A single <elcode>xsl:matching-substring</elcode> instruction, followed by a
                     single <elcode>xsl:non-matching-substring</elcode> instruction, followed by
                     zero or more <elcode>xsl:fallback</elcode> instructions</p></item></olist><p>
               <error spec="XT" type="static" class="SE" code="1130"><p>It is a <termref def="dt-static-error">static error</termref> if the
                        <elcode>xsl:analyze-string</elcode> instruction contains neither an
                        <elcode>xsl:matching-substring</elcode> nor an
                        <elcode>xsl:non-matching-substring</elcode> element.</p></error>
            </p><p>Any <elcode>xsl:fallback</elcode> elements among the children of the
                  <elcode>xsl:analyze-string</elcode> instruction are ignored by an 
               processor supporting XSLT 2.0 or later, but allow fallback behavior to be
               defined when the stylesheet is used with an XSLT 1.0 processor operating with
               forwards-compatible behavior.</p><p diff="add" at="2023-05-10">For the <elcode>xsl:matching-substring</elcode> and
               <elcode>xsl:non-matching-substring</elcode> elements, the <code nobreak="false">select</code> 
               attribute and the contained sequence
               constructor are mutually exclusive <errorref spec="XT" class="SE" code="3185"/>.</p><p>This instruction is designed to process all the non-overlapping substrings of the
               input string that match the regular expression supplied: that is,
            the <xtermref spec="FO40" ref="dt-disjoint-matching-segments"/> that result from
            processing the input string using the supplied regular expression and the supplied flags.</p><p>
               <error spec="XT" type="dynamic" class="DE" code="1140"><p>It is a <termref def="dt-dynamic-error"> dynamic error</termref> if the <termref def="dt-effective-value"/>
                     of the <code nobreak="false">regex</code>
                     attribute <error.extra>of the <elcode>xsl:analyze-string</elcode>
                        instruction</error.extra> does not conform to the
                        <rfc2119>required</rfc2119> syntax for regular expressions, as specified in
                        <bibref ref="xpath-functions-40"/>. If the regular expression is known
                     statically (for example, if the attribute does not contain any <termref def="dt-expression">expressions</termref> enclosed in curly brackets) then
                     the processor <rfc2119>may</rfc2119> raise the error as a <termref def="dt-static-error">static error</termref>. </p></error>
            </p><p>
               <error spec="XT" type="dynamic" class="DE" code="1145"><p>It is a <termref def="dt-dynamic-error"> dynamic error</termref> if the <termref def="dt-effective-value"/> of the <code nobreak="false">flags</code>
                     attribute <error.extra>of the <elcode>xsl:analyze-string</elcode>
                        instruction</error.extra> has a value other than the values defined in
                        <bibref ref="xpath-functions-40"/>. If the value of the attribute is known
                     statically (for example, if the attribute does not contain any <termref def="dt-expression">expressions</termref> enclosed in curly brackets) then
                     the processor <rfc2119>may</rfc2119> raise the error as a <termref def="dt-static-error">static error</termref>. </p></error>
            </p><p>Processing proceeds as follows.
               Let <var>M</var> be the sequence of 
               <xtermref spec="FO40" ref="dt-disjoint-matching-segments">disjoint matching 
               segments</xtermref> that results from
            applying the regular expression to the input string, with the given flags, in order of their
            start position. Between any two adjacent matching segments <var>M1</var> and <var>M2</var>, 
            if the end position of <var>M1</var> is not the same as the start position of <var>M2</var>,
            insert a non-matching segment comprising the characters from the input string between the
            end of <var>M1</var> and the start of <var>M2</var>. Similarly, insert a non-matching segment
               at the start of the sequence if the first matching segment is not positioned at the start of the input, 
               and insert a non-matching segment at the end if the last matching segment is not positioned
               at the end of the input. The result is a sequence consisting of matching and non-matching segments,
               that together define a partitioning of the input string.</p><p>The instruction then processes each of these segments in turn. For a matching segment, it evaluates
               the <elcode>xsl:matching-substring</elcode> child if it exists.
               For a non-matching segment, it evaluates the <elcode>xsl:non-matching-substring</elcode>
               if it exists. The child <elcode>xsl:matching-substring</elcode> or 
               <elcode>xsl:non-matching-substring</elcode> is evaluated by evaluating its <code nobreak="false">select</code>
               attribute or its contained sequence constructor. The context item for this evaluation
               is the string value of the matching or non-matching segment (as an instance of <code nobreak="false">xs:string</code>); 
               the context position is the
               position of this segment within the sequence of matching and non-matching segments, and
               the context size is the number of segments.</p><p>If the <elcode>xsl:matching-substring</elcode> or <elcode>xsl:non-matching-substring</elcode>
               child is absent, then processing proceeds as if the element were present with empty content
               and no <code nobreak="false">select</code> attribute. That is, the corresponding segment produces no output.</p></div2><div2 id="func-regex-group-functions"><head>Captured Groups</head><p>Two functions are available for processing the values of captured groups associated
            with a matching segment.</p><p>Examples of the use of these functions can be found in <specref ref="regex-examples"/>.</p><div3 id="func-regex-groups"><head>fn:regex-groups</head><changes><change issue="2233" PR="2246" date="2025-11-18">New in 4.0</change></changes><glist><gitem><label>Summary</label><def><p>Returns the set of captured groups associated with a matching segment
            during evaluation of the <elcode>xsl:analyze-string</elcode> instruction.</p></def></gitem><gitem><label>Signature</label><def><example role="signature"><proto isOp="no" prefix="fn" name="regex-groups" return-type="map(xs:integer, record(value as xs:string, position as xs:integer))" returnEmptyOk="no" returnSeq="no" returnVaries="no" isSchema="no" isDatatype="no" isSpecial="no"/></example></def></gitem><gitem><label>Properties</label><def><p>This function is <xtermref spec="FO40" ref="dt-deterministic">deterministic</xtermref>, <xtermref spec="FO40" ref="dt-context-dependent">context-dependent</xtermref>,  and <xtermref spec="FO40" ref="dt-focus-independent">focus-independent</xtermref>. </p></def></gitem><gitem><label>Rules</label><def><p>
            <termdef id="dt-current-captured-groups" term="current captured groups">While
               the <elcode>xsl:matching-substring</elcode> instruction is active, a set of
                  <term>current captured groups</term> is available, corresponding to the
               capturing subexpressions of the regular expression.</termdef> These captured
            groups are accessible using the <function>regex-groups</function>
            and <function>regex-group</function> functions. </p><p>The <function>regex-groups</function> function returns this information as a map.</p><p>The <var>N</var>th captured group (where <var>N</var> &gt; 0) is the segment of the input string matched
            by the subexpression contained by the <var>N</var>th left parenthesis in the regex,
               excluding any non-capturing parenthesized expressions. The zeroth captured substring is the segment
               of the input string that matches the entire regex. In both cases, a segment
               is identified by a record containing both the captured string itself (as <code nobreak="false">value</code>)
            and the start position (1-based) of the
               captured group within the input string (as <code nobreak="false">position</code>).</p><note><p>This means that the string value of group zero is
            the same as the value of <code nobreak="false">.</code> (dot).</p></note><p>The result map contains no entry for a number <var>N</var> if there is no captured group with the
            number <var>N</var>. This can occur for a number of reasons:</p><olist><item><p><var>N</var> is negative.</p></item><item><p>The regular expression contains fewer than <var>N</var> capturing subexpressions.</p></item><item><p>The <var>N</var>th capturing subexpression exists, but did not match any part of the input
                  string.</p></item></olist><p>The string value of a captured group may be the empty string.</p><p>The set of captured groups is a context variable with dynamic scope. It is initially
            an empty sequence. During the evaluation of an <elcode>xsl:matching-substring</elcode>
            instruction it is set to the sequence of matched segments for that regex match. During
            the evaluation of an <elcode>xsl:non-matching-substring</elcode> instruction or a
               <termref def="dt-pattern">pattern</termref> or a <termref def="dt-stylesheet-function">stylesheet function</termref> it is set to an empty
            sequence. On completion of an instruction that changes the value, the variable reverts
            to its previous value.</p><p>The value of the <termref def="dt-current-captured-groups"/> is unaffected through calls of
               <elcode>xsl:apply-templates</elcode>, <elcode>xsl:call-template</elcode>,
               <elcode>xsl:apply-imports</elcode> or <elcode>xsl:next-match</elcode>, or by
            expansion of named <termref def="dt-attribute-set">attribute sets</termref>.</p></def></gitem><gitem><label>Notes</label><def><note><p>The <function>regex-groups</function> function provides additional information that is
         not available via <function>regex-group</function>:</p><ulist><item><p>It distinguishes capturing subexpressions that matched an empty string from
            capturing subexpressions that did not match anything.</p></item><item><p>It identifies not just the string that was captured, but its position within the input.</p></item></ulist><p>In 4.0 regular expressions may contain capturing subexpressions within a lookahead. In this
         situation a segment returned in the result of <function>regex-groups</function> may be positioned
         beyond the end of the corresponding matching segment.</p></note></def></gitem></glist></div3><div3 id="func-regex-group"><head>fn:regex-group</head><changes><change issue="407" PR="2274" date="2026-01-06">In XSLT 4.0, the function item <code nobreak="false">regex-group#1</code> retains the value of the current
         captured substrings within its captured context.</change></changes><glist><gitem><label>Summary</label><def><p>Returns the string captured by a capturing subexpression of the regular expression
            used during evaluation of the <elcode>xsl:analyze-string</elcode> instruction.</p></def></gitem><gitem><label>Signature</label><def><example role="signature"><proto isOp="no" prefix="fn" name="regex-group" return-type="xs:string" returnEmptyOk="no" returnSeq="no" returnVaries="no" isSchema="no" isDatatype="no" isSpecial="no"><arg name="number" type="xs:integer"/></proto></example></def></gitem><gitem><label>Properties</label><def><p>This function is <xtermref spec="FO40" ref="dt-deterministic">deterministic</xtermref>, <xtermref spec="FO40" ref="dt-context-dependent">context-dependent</xtermref>,  and <xtermref spec="FO40" ref="dt-focus-independent">focus-independent</xtermref>. </p></def></gitem><gitem><label>Rules</label><def><p>The function <function>regex-group</function> is retained for backwards compatibility.
         The function call <code nobreak="false">regex-group(<var>N</var>)</code> returns the result of the
         expression <code nobreak="false">regex-groups()?<var>N</var>?value otherwise ""</code>.</p></def></gitem><gitem><label>Notes</label><def><note><p>The function may return a zero-length string for a number of reasons:</p><olist><item><p><code nobreak="false">$number</code> is negative.</p></item><item><p>The regular expression does not contain a capturing subexpression with the
                  given number.</p></item><item><p>The capturing subexpression exists, and did not match any part of the input
                  string.</p></item><item><p>The capturing subexpression exists, and matched a zero-length substring of
                  the input string.</p></item></olist><p>The set of captured groups is a context variable with dynamic scope. It is initially
            an empty sequence. During the evaluation of an <elcode>xsl:matching-substring</elcode>
            instruction it is set to the sequence of matched substrings for that regex match. During
            the evaluation of an <elcode>xsl:non-matching-substring</elcode> instruction or a
               <termref def="dt-pattern">pattern</termref> or a <termref def="dt-stylesheet-function">stylesheet function</termref> it is set to an empty
            sequence. On completion of an instruction that changes the value, the variable reverts
            to its previous value.</p><p>The value of the <xtermref spec="FO40" ref="dt-current-captured-substrings"/> is unaffected through calls of
               <elcode>xsl:apply-templates</elcode>, <elcode>xsl:call-template</elcode>,
               <elcode>xsl:apply-imports</elcode> or <elcode>xsl:next-match</elcode>, or by
            expansion of named <termref def="dt-attribute-set">attribute sets</termref>.</p></note></def></gitem></glist></div3></div2><div2 id="regex-examples"><head>Examples of Regular Expression Matching</head><p>The examples in this section assume that the stylesheet specifies <code nobreak="false">expand-text="yes"</code>
            to enable the use of <termref def="dt-text-value-template">text value templates</termref>.</p><example><head>Replacing Characters by Elements</head><p>Task: replace all newline characters in the <code nobreak="false">abstract</code> element by
                  empty <code nobreak="false">br</code> elements:</p><p>Solution:</p><eg xml:space="preserve" role="xslt-instruction">&lt;xsl:analyze-string select="abstract" regex="\n"&gt;
  &lt;xsl:matching-substring&gt;&lt;br/&gt;&lt;/xsl:matching-substring&gt;
  &lt;xsl:non-matching-substring&gt;{.}&lt;/xsl:non-matching-substring&gt;
&lt;/xsl:analyze-string&gt;</eg></example><example><head>Recognizing non-XML Markup Structure</head><p>Task: replace all occurrences of <code nobreak="false">[...]</code> in the <code nobreak="false">body</code> by
                     <code nobreak="false">cite</code> elements, retaining the content between the square brackets
                  as the content of the new element.</p><p>Solution:</p><eg xml:space="preserve" role="xslt-instruction">&lt;xsl:analyze-string select="body" regex="\[(.*?)\]"&gt;
  &lt;xsl:matching-substring&gt;
    &lt;cite&gt;{regex-group(1)}&lt;/cite&gt;
  &lt;/xsl:matching-substring&gt;
  &lt;xsl:non-matching-substring&gt;{.}&lt;/xsl:non-matching-substring&gt;
&lt;/xsl:analyze-string&gt;</eg><p>Note that this simple approach fails if the <code nobreak="false">body</code> element contains
                  markup that needs to be retained. In this case it is necessary to apply the
                  regular expression processing to each text node individually. If the
                     <code nobreak="false">[...]</code> constructs span multiple text nodes (for example, because
                  there are elements within the square brackets) then it probably becomes necessary
                  to make two or more passes over the data.</p></example><example><head>Parsing a Date</head><p>Task: the input string contains a date such as <code nobreak="false">23 March 2002</code>.
                  Convert it to the form <code nobreak="false">2002-03-23</code>.</p><p>Solution (with no error handling if the input format is incorrect):</p><eg xml:space="preserve" role="xslt-instruction">&lt;xsl:variable name="months" 
        select="'January', 'February', 'March', ..."/&gt;

&lt;xsl:analyze-string select="normalize-space($input)" 
    regex="([0-9]{{1,2}})\s([A-Z][a-z]+)\s([0-9]{{4}})"&gt;
    &lt;xsl:matching-substring&gt;
        &lt;xsl:number value="regex-group(3)" format="0001"/&gt;;          
        &lt;xsl:text&gt;-&lt;/xsl:text&gt;
        &lt;xsl:number value="index-of($months, regex-group(2))" format="01"/&gt;
        &lt;xsl:text&gt;-&lt;/xsl:text&gt;
        &lt;xsl:number value="regex-group(1)" format="01"/&gt;
    &lt;/xsl:matching-substring&gt;
&lt;/xsl:analyze-string&gt;</eg><p>Note the use of <code nobreak="false">normalize-space</code> to simplify the work done by the
                  regular expression, and the use of doubled curly brackets because the
                     <code nobreak="false">regex</code> attribute is an attribute value template.</p></example><example><head>Matching Zero-Length Strings</head><p>Task: remove all empty and whitespace-only lines from a file.</p><eg role="xslt-instruction" xml:space="preserve">
&lt;xsl:analyze-string select="unparsed-text('in.txt')"
                    regex="^[\t ]*$" flags="m"&gt;
  &lt;xsl:non-matching-substring&gt;{.}&lt;/xsl:non-matching-substring&gt;
&lt;/xsl:analyze-string&gt;</eg></example><example><head>Captured Groups within Lookahead</head><p>Task: extract a chapter or appendix number from a string such
                  as <code nobreak="false">Chapter 5</code> or <code nobreak="false">Appendix A</code>.</p><eg role="xslt-instruction" xml:space="preserve">
&lt;xsl:analyze-string select="(Chapter|Appendix) (?=[A-Z0-9]+)"
                    regex="(Chapter|Appendix)\s+(?=[A-Z0-9]+)"&gt;
  &lt;xsl:matching-substring select="regex-groups()?2?value"/&gt;
&lt;/xsl:analyze-string&gt;</eg></example><example><head>Converting camelCase to camel-Case</head><p>Task: insert hyphens at the points in a string marked by
                  transition from lower-case to upper-case.</p><eg role="xslt-instruction" xml:space="preserve">
&lt;xsl:analyze-string select="aLongPieceOfString"
                    regex="(?&lt;=[a-z])(?=([A-Z]))"&gt;
  &lt;xsl:matching-substring&gt;-&lt;/xsl:matching-substring&gt;
  &lt;xsl:non-matching-substring&gt;{.}&lt;/xsl:non-matching-substring&gt;
&lt;/xsl:analyze-string&gt;</eg><p>In this example the matching substrings are zero-length, and these
               zero-length strings are replaced with hyphens. The parts between the
               lower-to-upper case transitions are non-matching substrings, and these
               are output <emph>as is</emph>. It would be easy, of course, to 
               extend the example to change the leading upper-case letters to lower-case.</p></example><example><head>Parsing comma-separated values</head><p>There are many variants of CSV formats. Some, but not all,
                  are handled by new XPath 4.0 functions such as <function>parse-csv</function>.
                  This example is designed to handle input
                  where:</p><ulist><item><p>Each record occupies one line.</p></item><item><p>Fields are separated by commas.</p></item><item><p>Quotation marks around a field are optional, unless the field contains a
                        comma or quotation mark, in which case they are mandatory.</p></item><item><p>A quotation mark within the value of a field is represented by a pair of two
                        adjacent quotation marks.</p></item></ulist><p>For example, the input record:</p><eg role="non-xml" xml:space="preserve">Ten Thousand,10000,,"10,000","It's ""10 Grand"", mister",10K</eg><p>contains six fields, specifically:</p><ulist><item><p>Ten Thousand</p></item><item><p>10000</p></item><item><p>&lt;zero-length-string&gt;</p></item><item><p>10,000</p></item><item><p>It's "10 Grand", mister</p></item><item><p>10K</p></item></ulist><p>The following code parses such CSV input into an XML structure containing
                     <code nobreak="false">row</code> and <code nobreak="false">col</code> elements:</p><eg role="xslt-instruction" xml:space="preserve">
&lt;xsl:for-each select="unparsed-text-lines('in.csv')" expand-text="yes"&gt;
  &lt;row&gt;
    &lt;xsl:analyze-string select="." 
                        regex='(?:^|,)(?:"((?:[^"]|"")*)"|([^",]*))'&gt;
      &lt;xsl:matching-substring&gt;
        &lt;col&gt;{replace(regex-group(1), '""', '"')||regex-group(2)}&lt;/col&gt;
      &lt;/xsl:matching-substring&gt;
    &lt;/xsl:analyze-string&gt;
  &lt;/row&gt;
&lt;/xsl:for-each&gt;</eg><p>Note that because this regular expression matches a zero-length string, it is not
                  permitted in XSLT 2.0.</p></example></div2></div1><div1 id="source-document-instruction"><head>The <code nobreak="false">xsl:source-document</code> instruction</head><p>The <elcode>xsl:source-document</elcode> instruction was specifically designed to handle streaming;
         it is described here because it is useful whether or not the source document
         is processed using streaming.</p><e:element-syntax xmlns:e="http://www.w3.org/1999/XSL/Spec/ElementSyntax" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" name="source-document">
      <e:in-category name="instruction"/>
      <e:attribute name="href" required="yes">
         <e:attribute-value-template>
            <e:data-type name="uri"/>
         </e:attribute-value-template>
      </e:attribute>
      <e:attribute name="streamable" default="'no'">
         <e:data-type name="boolean"/>
      </e:attribute>
      <e:attribute name="use-accumulators" default="''">
         <e:data-type name="tokens"/>
      </e:attribute>
      <e:attribute name="validation">
         <e:constant value="strict"/>
         <e:constant value="lax"/>
         <e:constant value="preserve"/>
         <e:constant value="strip"/>
      </e:attribute>
      <e:attribute name="type">
         <e:data-type name="eqname"/>
      </e:attribute>
      <e:model name="sequence-constructor"/>
      <e:allowed-parents>
         <e:parent-category name="sequence-constructor"/>
      </e:allowed-parents>
   </e:element-syntax><p>The <elcode>xsl:source-document</elcode> instruction reads a source document whose URI is
               supplied, and processes the content of the document  by evaluating the
               contained <termref def="dt-sequence-constructor"/>. 
               The <code nobreak="false">streamable</code> attribute (default <code nobreak="false">"no"</code>)
            allows streamed processing to be requested.</p><p>The document to be read is determined by the <xtermref spec="XT40" ref="dt-effective-value"/> 
               of the <code nobreak="false">href</code> attribute (which is defined as
               an <xtermref spec="XT40" ref="dt-attribute-value-template">attribute value template</xtermref>).
                  This <rfc2119>must</rfc2119> be a valid URI reference.
                  If it is an absolute URI reference, it is used as is; if it is a relative URI
                  reference, it is made absolute by resolving it against the base URI of the
                     <elcode>xsl:source-document</elcode> element. The process of obtaining a
               document node given a URI is the same as for the <xfunction>doc</xfunction> function.
               However, unlike the <xfunction>doc</xfunction> function, the
                  <elcode>xsl:source-document</elcode> instruction offers no guarantee that the resulting
               document will be stable (that is, that multiple calls specifying the same URI will
               return the same document).</p><p>Specifically, if an <elcode>xsl:source-document</elcode> instruction is evaluated several
               times (or if different <elcode>xsl:source-document</elcode> instructions are evaluated) with
               the same URI (after making it absolute) as the
               value of the <code nobreak="false">href</code> attribute, it is <termref def="dt-implementation-dependent">implementation-dependent</termref> whether the
               same nodes or different nodes are returned on each occasion; it is also possible that
               the actual document content will be different. </p><note><p>A different node will necessarily be returned if there
               are differences in attributes such as <code nobreak="false">validation</code>, <code nobreak="false">type</code>,
               <code nobreak="false">streamable</code>, or <code nobreak="false">use-accumulators</code>, or if the calls are in different
               <termref def="dt-package">packages</termref> with variations in the rules for whitespace
               stripping or stripping of type annotations.</p></note><p>The result of the <elcode>xsl:source-document</elcode> instruction is the same as the result
               of the following (non-streaming) process:</p><olist><item><p>The source document is read from the supplied URI and parsed to form a
                     tree of nodes in the XDM data model.</p></item><item><p>The contained sequence constructor is evaluated with the root node of this tree
                     as the context item, and with the context
                     position and context size set to one; and the resulting sequence is returned as
                     the result of the <elcode>xsl:source-document</elcode> instruction.</p></item></olist><p>The <code nobreak="false">use-accumulators</code> attribute defines the
               set of accumulators that are applicable to the document, as explained in
                  <specref ref="applicability-of-accumulators"/>.</p><div2 id="source-document-validation"><head>Validation of Source Documents</head><p>The <code nobreak="false">validation</code> and <code nobreak="false">type</code> attributes of
                     <elcode>xsl:source-document</elcode> may be used to control schema validation of the
                  input document. They have the same effect as the
                  corresponding attributes of the <elcode>xsl:copy-of</elcode> instruction when
                  applied to a document node, except that 
                  when <code nobreak="false">streamable="yes"</code> is specified, 
                  the copy that is produced is itself a
                  streamed document. The process is described in more detail in 
                 <xspecref spec="XT40" ref="validating-document-nodes"/>.</p><p>These two attributes are both optional, and if one is specified then the other
                     <rfc2119>must</rfc2119> be omitted (<errorref spec="XT" class="SE" code="1505"/>).</p><p>The presence of a <code nobreak="false">validation</code> or <code nobreak="false">type</code> attribute on an
                     <elcode>xsl:source-document</elcode> instruction causes any
                     <code nobreak="false">input-type-annotations</code> attribute to have no effect on any document
                  read using that instruction.</p><note><p>In effect, setting <code nobreak="false">validation</code> to <code nobreak="false">strict</code> or
                        <code nobreak="false">lax</code>, or supplying the <code nobreak="false">type</code> attribute, requests
                     document-level validation of the input as it is read. Setting
                        <code nobreak="false">validation="preserve"</code> indicates that if the incoming document
                     contains type annotations (for example, produced by validating the output of a
                     previous step in a streaming pipeline) then they should be retained, while the
                     value <code nobreak="false">strip</code> indicates that any such type annotations should be
                     dropped.</p><p>It is a consequence of the way validation is defined in XSD that the type
                     annotation of an element node can be determined during the processing of its
                     start tag, although the actual validity of the element is not known until the
                     end tag is encountered. When validation is requested, a streamed document
                     should not present data to the stylesheet except to the extent that such data
                     could form the leading part of a valid document. If the document proves to be
                     invalid, the processor should not pass invalid data to the stylesheet to be
                     processed, but should immediately raise the appropriate error. For the
                     purposes of <elcode>xsl:try</elcode> and <elcode>xsl:catch</elcode>, this error
                     can only be caught at the level of the <elcode>xsl:source-document</elcode> instruction
                     that initiated validation, not at a finer level. If validation errors are
                     caught in this way, any output that has been computed up to the point of the
                     error is not added to the final result tree; the mechanisms to achieve this may
                     use memory, which may reduce the efficacy of streaming.</p></note></div2><div2 id="func-stream-available"><head>fn:stream-available</head><glist><gitem><label>Summary</label><def><p>Determines, as far as possible, whether a document is available for streamed processing using <elcode>xsl:source-document</elcode>.</p></def></gitem><gitem><label>Signature</label><def><example role="signature"><proto isOp="no" prefix="fn" name="stream-available" return-type="xs:boolean" 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 <xtermref spec="FO40" ref="dt-nondeterministic">nondeterministic</xtermref>, <xtermref spec="FO40" ref="dt-context-dependent">context-dependent</xtermref>,  and <xtermref spec="FO40" ref="dt-focus-independent">focus-independent</xtermref>.  It depends on 
		available documents.
	</p></def></gitem><gitem><label>Rules</label><def><p>The intent of the <function>stream-available</function> function is to allow a stylesheet author to determine,
            before calling <elcode>xsl:source-document</elcode> with <code nobreak="false">streamable="yes"</code> and 
            with a particular URI as the value of its <code nobreak="false">href</code>
         attribute, whether a document is available at that location for streamed processing.</p><p>If the <code nobreak="false">$uri</code> argument is an empty sequence then the function returns <code nobreak="false">false</code>.</p><p>If the function returns <code nobreak="false">true</code> then the caller can conclude that the following conditions are true:</p><olist><item><p>The supplied URI is valid;</p></item><item><p>A resource can be retrieved at that URI;</p></item><item><p>An XML representation of the resource can be delivered, which is well-formed at least to the extent
            that some initial sequence of octets can be decoded into characters and matched against the production:</p><p>
                  <code nobreak="false">prolog (EmptyElemTag | STag )</code>
               </p><p>as defined in the XML 1.0 or XML 1.1 Recommendation.</p><note>That is, the XML is well-formed at least as far as the end of the first element start tag; to establish this,
               a parser will typically retrieve any external entities referenced in the Doctype declaration or DTD.</note></item></olist><p>If the function returns <code nobreak="false">false</code>, the caller can conclude that either one of the above conditions is not satisfied, or
         the processor detected some other condition that would prevent a call on <elcode>xsl:source-document</elcode> with
            <code nobreak="false">streamable="yes"</code> executing successfully.</p><p>Like <elcode>xsl:source-document</elcode> itself, the function is not deterministic, which means that multiple calls during the execution
         of a stylesheet will not necessarily return the same result. The caller cannot make any inferences about the point in time at which
         the input conditions for <function>stream-available</function> are present, and in particular there is no guarantee that because
         <function>stream-available</function> returns <code nobreak="false">true</code>, <elcode>xsl:source-document</elcode> will necessarily succeed.</p><p>The value of the <code nobreak="false">$uri</code> argument <rfc2119>must</rfc2119> be a URI in the form of a string. If it is a relative URI,
            it is resolved relative to the static base URI of the function call.</p></def></gitem><gitem><label>Error Conditions</label><def><p>If the URI is invalid, such that a call on <xfunction>doc-available</xfunction> would raise an error, then 
            <function>stream-available</function> raises the same error: <xerrorref spec="FO40" class="DC" code="0005"/>.</p></def></gitem></glist></div2></div1><div1 id="accumulators"><head>Accumulators</head><p>Accumulators were introduced in XSLT 3.0 to enable data that is read during streamed
               processing of a document to be accumulated, processed or retained for later use.
               However, they may equally be used with non-streamed processing.</p><p><termdef id="dt-accumulator" term="accumulator">An
                     <term>accumulator</term> defines a series of
                     values associated with the nodes of the tree. If an accumulator is
                  applicable to a particular tree, then for each node in the tree, other than
                  attribute and namespace nodes, there will be two values available, called the
                  pre-descent and post-descent values. These two values are available via a pair of
                  functions, <function>accumulator-before</function> and
                     <function>accumulator-after</function>.</termdef></p><p>There are two ways the values of an accumulator can be
               established for a given tree: they can be computed by evaluating the rules appearing
               in the <elcode>xsl:accumulator</elcode> declaration, or they can be copied from the
               corresponding nodes in a different tree. The second approach (copying the values) is
               available via the <function>snapshot</function> and <function>copy-of</function>
               functions, or by use of the <elcode>xsl:copy-of</elcode> instruction specifying
                  <code nobreak="false">copy-accumulators="yes"</code>. Accumulator values are also copied during
               the implicit invocation of the snapshot function performed by the
                  <elcode>xsl:merge</elcode> instruction.</p><note><p>Accumulators can apply to trees rooted at any kind of node. But
                  because they are most often applied to trees rooted at a document node, this
                  section sometimes refers to the “document” to which an accumulator applies; use of
                  this term should be taken to include all trees whether or not they are rooted at a
                  document node.</p><p>Accumulators can apply to trees rooted at nodes (such
                  as text nodes) that cannot have children, though this serves no useful purpose. In
                  the case of a tree rooted at an attribute or namespace node, there is no way to
                  obtain the value of the accumulator.</p></note><p>The following sections give first, the syntax rules for defining an accumulator; then
               an informal description of the semantics; then a more formal definition; and finally,
               examples. But to illustrate the concept intuitively, the following simple example
               shows how an accumulator can be used for numbering of nodes:</p><example><head>Numbering Figures within a Chapter</head><p>This example assumes document input in which <code nobreak="false">figure</code> elements can
                  appear within <code nobreak="false">chapter</code> elements (which we assume are not nested), and
                  the requirement is to render the figures with a caption that includes the figure
                  number within its containing chapter.</p><p>When the document is processed using streaming, the <elcode>xsl:number</elcode>
                  instruction is not available, so a solution using accumulators is needed.</p><p>The required accumulator can be defined and used like this:</p><eg role="xslt-declaration" xml:space="preserve">&lt;xsl:accumulator name="figNr" as="xs:integer" 
                    initial-value="0" streamable="yes"&gt;
     &lt;xsl:accumulator-rule match="chapter" select="0"/&gt;
     &lt;xsl:accumulator-rule match="figure" select="$value + 1"/&gt;
&lt;/xsl:accumulator&gt;
   
&lt;xsl:mode streamable="yes"/&gt;
&lt;xsl:template match="figure" expand-text="yes"&gt;
     &lt;xsl:apply-templates/&gt;
     &lt;p&gt;Figure {accumulator-before('figNr')}&lt;/p&gt;
&lt;/xsl:template&gt;  
                  </eg></example><div2 id="accumulator-declaration"><head>Declaring an Accumulator</head><e:element-syntax xmlns:e="http://www.w3.org/1999/XSL/Spec/ElementSyntax" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" name="accumulator">
      <e:in-category name="declaration"/>
      <e:attribute name="name" required="yes">
         <e:data-type name="eqname"/>
      </e:attribute>
      <e:attribute name="initial-value" required="yes">
         <e:data-type name="expression"/>
      </e:attribute>
      <e:attribute name="as" default="'item()*'">
         <e:data-type name="sequence-type"/>
      </e:attribute>
      <e:attribute name="streamable" default="'no'">
         <e:data-type name="boolean"/>
      </e:attribute>
      <e:element name="accumulator-rule" repeat="one-or-more"/>
      <e:allowed-parents>
         <e:parent name="package"/>
         <e:parent name="stylesheet"/>
         <e:parent name="transform"/>
      </e:allowed-parents>
   </e:element-syntax><e:element-syntax xmlns:e="http://www.w3.org/1999/XSL/Spec/ElementSyntax" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" name="accumulator-rule">
      <e:attribute name="match" required="yes">
         <e:data-type name="pattern"/>
      </e:attribute>
      <e:attribute name="phase" required="no" default="'start'">
         <e:constant value="start"/>
         <e:constant value="end"/>
      </e:attribute>
      <e:attribute name="select" required="no">
         <e:data-type name="expression"/>
      </e:attribute>
      <e:attribute name="capture" required="no" default="'no'">
         <e:data-type name="boolean" default="'no'"/>
      </e:attribute>
      <e:model name="sequence-constructor"/>
      <e:allowed-parents>
         <e:parent name="accumulator"/>
      </e:allowed-parents>
   </e:element-syntax><p>An <elcode>xsl:accumulator</elcode> element is a <xtermref spec="XT40" ref="dt-declaration">declaration</xtermref> of an accumulator. The
                     <code nobreak="false">name</code> attribute defines the name of the accumulator. The value of
                  the <code nobreak="false">name</code> attribute is an <xtermref spec="XT40" ref="dt-eqname">EQName</xtermref>,
                  which is expanded as described in <xspecref spec="XT40" ref="qname"/>.</p><p>An <elcode>xsl:accumulator</elcode> declaration can only appear as a <xtermref spec="XT40" ref="dt-top-level"/> element in a stylesheet module.</p><p diff="add" at="issue211">The <code nobreak="false">capture</code> attribute is allowed only on an <elcode>xsl:accumulator-rule</elcode> element
               that specifies <code nobreak="false">phase="end"</code>. Its effect is described in <specref ref="capturing-accumulators"/>.</p><p>The functions <function>accumulator-before</function>
                     and <function>accumulator-after</function> return, respectively, the
                  value of the accumulator before visiting the descendants of a given node, and the
                  value after visiting the descendants of a node. Each of these functions takes a single argument, the name of the
                  accumulator, and the function applies implicitly to the context node. The
                  type of the return value (for both functions) is determined by the <code nobreak="false">as</code>
                  attribute of the <elcode>xsl:accumulator</elcode> element.</p><p><termdef id="dt-accumulator-function" term="accumulator function">The functions
                        <function>accumulator-before</function> and
                        <function>accumulator-after</function> are referred to as the
                        <term>accumulator functions</term>.</termdef></p><p>The initial value of the accumulator is obtained by evaluating the expression in
                  the <code nobreak="false">initial-value</code> attribute. This
                     attribute is mandatory. The expression in the
                     <code nobreak="false">initial-value</code> attribute is evaluated with a 
                 <xtermref spec="XT40" ref="dt-singleton-focus"/> based on the root node of
                     the streamed input tree to which the accumulator is being applied.</p><p>The values of the accumulator for individual nodes in a tree are obtained by
                  applying the <elcode>xsl:accumulator-rule</elcode> rules contained within the
                     <elcode>xsl:accumulator</elcode> declaration, as described in subsequent
                  sections. The <code nobreak="false">match</code> attribute of
                        <elcode>xsl:accumulator-rule</elcode> is a <xtermref spec="XT40" ref="dt-pattern"/> which
                     determines which nodes trigger execution of the rule; the <code nobreak="false">phase</code>
                     attribute indicates whether the rule fires before descendants are processed
                        (<code nobreak="false">phase="start"</code>, which is the default), or after descendants are
                     processed (<code nobreak="false">phase="end"</code>).</p><p>The <code nobreak="false">select</code> attribute and the contained sequence constructor of the
                     <elcode>xsl:accumulator-rule</elcode> element are mutually exclusive: if the
                     <code nobreak="false">select</code> attribute is present then the sequence constructor must be
                  empty. The expression in the <code nobreak="false">select</code>
                  attribute of <elcode>xsl:accumulator-rule</elcode>
                  or the contained sequence constructor
                  is evaluated with a static context that follows the normal rules for expressions
                  in stylesheets, except that:</p><ulist><item><p>An additional variable is present in the context. The name of this variable
                        is <code nobreak="false">value</code> (in no namespace), and its type is the type that
                        appears in the <code nobreak="false">as</code> attribute of the
                           <elcode>xsl:accumulator</elcode> declaration.</p></item><item><p>The context item for evaluation of the expression or sequence constructor will always be a node
                        that matches the <xtermref spec="XT40" ref="dt-pattern">pattern</xtermref> in the
                           <code nobreak="false">match</code> attribute.</p></item></ulist><p>The result of both the <code nobreak="false">initial-value</code> and <code nobreak="false">select</code> expressions (or contained sequence
                     constructor) is converted to the type declared in the <code nobreak="false">as</code>
                  attribute by applying the <xtermref spec="XT40" ref="dt-coercion-rules"/>. A
                     <xtermref spec="XT40" ref="dt-type-error">type error</xtermref> occurs if conversion is not
                  possible. The <code nobreak="false">as</code> attribute defaults to <code nobreak="false">item()*</code>.</p><p>The effect of the <code nobreak="false">streamable</code>  attribute 
                  is defined in <xspecref spec="SG40" ref="streamability-of-accumulators"/>.</p><p>The effect of the <code nobreak="false">capture</code> attribute 
                  is defined in <specref ref="capturing-accumulators"/>.</p></div2><div2 id="applicability-of-accumulators"><head>Applicability of Accumulators</head><p>It is not the case that every accumulator is applicable to every tree. The details
                  depend on how the accumulator is declared, and how the tree is created. The rules
                  are as follows:</p><olist><item><p>An accumulator is applicable to a tree unless otherwise specified in these rules.
                  (For example, when a document is read using the <function>document</function>,
                  <xfunction>doc</xfunction>, or <xfunction>collection</xfunction> functions,
                  all accumulators are applicable. Similarly, all accumulators are applicable
                  to a <xtermref spec="XT40" ref="dt-temporary-tree"/> created using <elcode>xsl:variable</elcode>.)</p></item><item><p>Regardless of the rules below, an accumulator is not applicable to a <termref def="dt-streamed-document"/>
                     unless the accumulator is declared with <code nobreak="false">streamable="yes"</code>. (The converse
                  does not apply: for unstreamed documents, accumulators are applicable regardless
                  of the value of the <code nobreak="false">streamable</code> attribute.)</p></item><item><p>For a document read using the
                     <elcode>xsl:source-document</elcode> instruction, the accumulators that are applicable 
                     are those determined by the <code nobreak="false">use-accumulators</code>
                  attribute of that instruction.</p></item><item><p>For a document read using the <code nobreak="false">for-each-source</code> attribute of an
                     <elcode>xsl:merge-source</elcode> child of an <elcode>xsl:merge</elcode> instruction,
                     the accumulators that are applicable are those determined by the <code nobreak="false">use-accumulators</code>
                     attribute of the <elcode>xsl:merge-source</elcode> element.</p></item><item><p>For a document containing nodes supplied in the
                     <xtermref spec="XT40" ref="dt-initial-match-selection"/>, the accumulators that are
                     applicable are those determined by the <elcode>xsl:mode</elcode>
                     declaration of the <xtermref spec="XT40" ref="dt-initial-mode"/>. This means that in the
                     absence of an <elcode>xsl:mode</elcode> declaration, no accumulators are applicable.</p></item><item><p>For a tree <var>T</var> created by copying a node in a tree <var>S</var>
                     using the <function>copy-of</function> or <function>snapshot</function>
                     functions, or the instruction <elcode>xsl:copy-of</elcode> with
                     <code nobreak="false">copy-accumulators="yes"</code>, an accumulator is applicable to
                     <var>T</var> if and only if it is applicable to <var>S</var>.</p></item></olist><p>If an accumulator is not applicable to the tree containing the context item, calls
                  to the functions <function>accumulator-before</function> and
                     <function>accumulator-after</function>, supplying the name of that accumulator,
                  will fail with a dynamic error.</p><note><p>The reason that accumulators are not automatically applicable to every streamed
                     document is to avoid the cost of evaluating them, and to avoid the possibility
                     of dynamic errors occuring if they are not designed to work with a particular
                     document structure.</p><p>In the case of unstreamed documents, there are no compelling reasons to
                     restrict which accumulators are applicable, because an implementation can avoid the cost of
                     evaluating every accumulator against every document by evaluating the
                     accumulator lazily, for example, by only evaluating the accumulator for a
                     particular tree the first time its value is requested for a node in that tree.
                     In the interests of orthogonality, however, restricting the applicable 
                     accumulators works in the same way for streamable and non-streamable documents.
                  </p></note><p>The value of the <code nobreak="false">use-accumulators</code> attribute of
               <elcode>xsl:source-document</elcode>, <elcode>xsl:merge-source</elcode>,
                  or <elcode>xsl:mode</elcode> must either be a
                  whitespace-separated list of <xtermref spec="XT40" ref="dt-eqname">EQNames</xtermref>, or the
                  special token <code nobreak="false">#all</code>. The list may be empty, and the default value is
                  an empty list. Every <code nobreak="false">EQName</code> in the list must be the name of an
                  accumulator, visible in the containing package, and declared with
                     <code nobreak="false">streamable="yes"</code>. The value <code nobreak="false">#all</code> indicates that all
                  accumulators that are visible in the containing package are applicable (except
                  that for a streamable input document, an accumulator is not applicable unless
                  it specifies <code nobreak="false">streamable="yes"</code>).</p><p>
                  <error spec="XT" type="static" class="SE" code="3300"><p>It is a <xtermref spec="XT40" ref="dt-static-error"/> if the list of
                        accumulator names <error.extra>in the <code nobreak="false">use-accumulators</code>
                           attribute</error.extra> contains an invalid token, contains the same
                        token more than once, or contains the token <code nobreak="false">#all</code> along with any
                        other value; or if any token (other than
                              <code nobreak="false">#all</code>) is not the name of a <xtermref spec="SG40" ref="dt-declared-streamable"/> accumulator visible in the containing
                           package.</p></error>

               </p></div2><div2 id="accumulator-informal-rules"><head>Informal Model for Accumulators</head><p><emph>This section describes how accumulator values are
                     established by evaluating the rules in an <elcode>xsl:accumulator</elcode>
                     declaration. This process does not apply to trees created with accumulator
                     values copied from another document, for example by using the
                        <function>copy-of</function> or <function>snapshot</function>
                     functions.</emph></p><p>Informally, an accumulator is evaluated by traversing a tree, as
                     follows.</p><p>Each node is visited twice, once before processing its descendants, and once after
                  processing its descendants. For consistency, this applies even to leaf nodes: each
                  is visited twice. Attribute and namespace nodes, however, are not visited.</p><p>Before the traversal starts, a variable (called the accumulator variable) is
                  initialized to the value of the expression given as the <code nobreak="false">initial-value</code>
                  attribute.</p><p>On each node visit, the <elcode>xsl:accumulator-rule</elcode> elements are
                  examined to see if there is a matching rule. For a match to occur, the pattern in
                  the <code nobreak="false">match</code> attribute must match the node, and the <code nobreak="false">phase</code>
                  attribute must be <code nobreak="false">start</code> if this is the first visit, and
                     <code nobreak="false">end</code> if it is the second visit. If there is a matching rule, then a
                  new value is computed for the accumulator variable using the expression contained
                  in that rule’s <code nobreak="false">select</code>
                     attribute or the contained sequence constructor. If there is more than
                  one matching rule, the last in document order is used. If there is no matching
                  rule, the value of the accumulator variable does not change.</p><p>Each node is labeled with a pre-descent value for the accumulator, which is the
                  value of the accumulator variable immediately <emph>after</emph> processing the
                  first visit to that node, and with a post-descent value for the accumulator, which
                  is the value of the accumulator variable immediately <emph>after</emph> processing the second visit.</p><p>The function <function>accumulator-before</function> delivers
                  the pre-descent value of the accumulator at the context node; the function
                     <function>accumulator-after</function> delivers the post-descent value of the
                  accumulator at the context node.</p><p>Although this description is expressed in procedural terms, it can be seen that
                  the two values of the accumulator for any given node depend only on the node and
                  its preceding and (in the case of the post-descent value) descendant nodes.
                  Calculation of both values is therefore deterministic and free of side-effects;
                  moreover, it is clear that the values can be computed during a streaming pass of a
                  document, provided that the rules themselves use only information that is
                  available without repositioning the input stream.</p><p>It is permitted for the <code nobreak="false">select</code> expression of an accumulator rule, or the contained
                     sequence constructor, to invoke an accumulator function. For a streamable accumulator, the rules ensure that
                     a rule with <code nobreak="false">phase="start"</code> cannot call the
                        <function>accumulator-after</function> function. When such function calls
                     exist in an accumulator rule, they impose a dependency of one accumulator on
                     another, and create the possibility of cyclic dependencies. Processors are
                     allowed to raise the error statically if they can detect it statically.
                     Failing this, processors are allowed to fail catastrophically in the event of a
                     cycle, in the same way as they might fail in the event of infinite function or
                     template recursion. Catastrophic failure might manifest itself, for example, as
                     a stack overflow, or as non-termination of the transformation.</p></div2><div2 id="accumulator-formal-rules"><head>Formal Model for Accumulators</head><p><emph>This section describes how accumulator values are
                     established by evaluating the rules in an <elcode>xsl:accumulator</elcode>
                     declaration. This process does not apply to trees created with accumulator
                     values copied from another document, for example by using the
                        <function>copy-of</function> or <function>snapshot</function>
                     functions.</emph></p><p><termdef id="dt-traversal" term="traversal">A <term>traversal</term> of a tree is
                     a sequence of <termref def="dt-traversal-event">traversal
                     events</termref>.</termdef></p><p><termdef id="dt-traversal-event" term="traversal-event">a <term>traversal
                        event</term> (shortened to <term>event</term> in this section) is a pair
                     comprising a phase (start or end) and a node.</termdef> It is modelled as a map
                  with two entries: <code nobreak="false">{ "phase": p, "node": n }</code> where p is the string
                     <code nobreak="false">"start"</code> or <code nobreak="false">"end"</code> and <code nobreak="false">n</code> is a node.</p><p>The traversal of a tree contains two
                  traversal events for each node in the tree, other than attribute and namespace
                  nodes. One of these events (the “start event”) has phase <code nobreak="false">"start"</code>, the other (the
                  “end event”) has phase <code nobreak="false">"end"</code>.</p><p>The order of traversal events within a traversal is such that, given any two nodes
                     <var>M</var> and <var>N</var> with start/end events denoted by <var>M0</var>,
                     <var>M1</var>, <var>N0</var>, and <var>N1</var>, :</p><ulist><item><p>For any node <var>N</var>, <var>N0</var> precedes <var>N1</var>;</p></item><item><p>If <var>M</var> is an ancestor of <var>N</var> then <var>M0</var> precedes
                           <var>N0</var> and <var>N1</var> precedes <var>M1</var>;</p></item><item><p>If <var>M</var> is on the preceding axis of <var>N</var> then <var>M1</var>
                        precedes <var>N0</var>.</p></item></ulist><p>The accumulator defines a (private) delta function <var>Δ</var>. The delta
                  function computes the value of the accumulator for one traversal event in terms of
                  its value for the previous traversal event. The function is defined as
                  follows:</p><olist><item><p>The signature of <var>Δ</var> is <code nobreak="false">function ($old-value as T,
                           $event as map(*)) as T</code>, where <var>T</var> is the sequence type
                        declared in the <code nobreak="false">as</code> attribute of the accumulator
                        declaration;</p></item><item><p>The implementation of the function is equivalent to the following
                        algorithm:</p><olist><item><p>Let <var>R</var> be the set of <elcode>xsl:accumulator-rule</elcode>
                              elements among the children of the accumulator declaration whose
                                 <code nobreak="false">phase</code> attribute equals <code nobreak="false">$event("phase")</code>
                              and whose <code nobreak="false">match</code> attribute is a 
                             <xtermref spec="XT40" ref="dt-pattern">pattern</xtermref> that matches <code nobreak="false">$event("node")</code></p></item><item><p>If <var>R</var> is empty, return <code nobreak="false">$old-value</code></p></item><item><p>Let <var>Q</var> be the <elcode>xsl:accumulator-rule</elcode> in
                                 <var>R</var> that is last in document order</p></item><item><p>Return the value of the expression in the <code nobreak="false">select</code>
                              attribute of <var>Q</var>, or the
                                 contained sequence constructor, evaluating this with a
                                 <xtermref spec="XT40" ref="dt-singleton-focus">singleton focus</xtermref> set to
                                 <code nobreak="false">$event("node")</code> and with a dynamic context that binds
                              the variable whose name is <code nobreak="false">$value</code> (in no namespace) to the value
                                 <code nobreak="false">$old-value</code>.</p><note><p>The argument names <code nobreak="false">old-value</code> and <code nobreak="false">event</code>
                                 are used here purely for definitional purposes; these names are not
                                 available for use within the <code nobreak="false">select</code> expression or contained sequence
                                    constructor.</p></note><note diff="add" at="issue211"><p>There is a slight variation here for an accumulator rule specifying
                              <code nobreak="false">phase="end"</code> and <code nobreak="false">capture="yes"</code>. For details,
                              see <xspecref spec="SG40" ref="streamability-of-accumulators"/>.</p></note></item></olist></item></olist><p>For every node <var>N</var>, other than attribute and namespace nodes, the
                  accumulator defines a pre-descent value <var>B/N</var> and a post-descent value
                     <var>A/N</var> whose values are as follows:</p><olist><item><p>Let <var>T</var> be the <termref def="dt-traversal">traversal</termref> of
                        the tree rooted at <code nobreak="false">fn:root(N)</code>.</p></item><item><p>Let <var>SB</var> be the subsequence of <var>T</var> starting at the first
                        event in <var>T</var> and ending with the start event for node <var>N</var>
                        (that is, the event <code nobreak="false">{ "phase": "start", "node": N }</code>).</p></item><item><p>Let <var>SA</var> be the subsequence of <var>T</var> starting at the first
                        event in <var>T</var>, and ending with the  end event
                        for node <var>N</var> (that is, the event <code nobreak="false">{ "phase": "end", "node": N
                           }</code>).</p></item><item><p>Let <var>Z</var> be the result of evaluating the expression contained in the
                           <code nobreak="false">initial-value</code> attribute of the
                           <elcode>xsl:accumulator</elcode> declaration, evaluated with a <xtermref spec="XT40" ref="dt-singleton-focus"/>
                           based on <code nobreak="false">root(N)</code>.</p></item><item><p>Then the pre-descent value <var>B/N</var> is the value of
                           <code nobreak="false">fn:fold-left(SB, Z, Δ)</code>, and the post-descent value
                           <var>A/N</var> is the value of <code nobreak="false">fn:fold-left(SA, Z,
                        Δ)</code>.</p></item></olist></div2><div2 id="errors-in-accumulators"><head>Dynamic Errors in Accumulators</head><p>If a dynamic error occurs when evaluating the <code nobreak="false">initial-value</code> expression
               of <elcode>xsl:accumulator</elcode>, or the <code nobreak="false">select</code> expression of <elcode>xsl:accumulator-rule</elcode>,
                  <phrase diff="add" at="2022-01-01">or the sequence constructor contained in <elcode>xsl:accumulator-rule</elcode>, </phrase>
               then the error is raised as an error from any subsequent call on <function>accumulator-before</function>
                  or <function>accumulator-after</function> that references the accumulator. If no such call on <function>accumulator-before</function>
                  or <function>accumulator-after</function> happens, then the error goes unreported.
               </p><note><p>In the above rule, the phrase <term>subsequent call</term> is to be understood in terms of functional dependency; that is, a call to
                  <function>accumulator-before</function> or <function>accumulator-after</function> raises an error if the accumulator value at the node in question is
               functionally dependent on a computation that fails with a dynamic error.</p></note><note><p>Particularly in the case of streamed accumulators, this may mean that the implementation has to “hold back” the error
               until the next time the accumulator is referenced, to give applications the opportunity to catch the error using <elcode>xsl:try</elcode>
               and <elcode>xsl:catch</elcode> in a predictable way.</p></note><note><p>Errors that occur during the evaluation of the pattern in the <code nobreak="false">match</code> attribute of
               <elcode>xsl:accumulator-rule</elcode> are handled as described in <xspecref spec="XT40" ref="pattern-errors"/>:
               specifically, the pattern does not match the relevant node, and no error is raised.</p></note></div2><div2 id="func-accumulator-before"><head>fn:accumulator-before</head><glist><gitem><label>Summary</label><def><p>Returns the pre-descent value of the selected accumulator at the context node.</p></def></gitem><gitem><label>Signature</label><def><example role="signature"><proto isOp="no" prefix="fn" name="accumulator-before" return-type="item()*" returnEmptyOk="no" returnSeq="no" returnVaries="no" isSchema="no" isDatatype="no" isSpecial="no"><arg name="name" type="(xs:string | xs:QName)"/></proto></example></def></gitem><gitem><label>Properties</label><def><p>This function is <xtermref spec="FO40" ref="dt-deterministic">deterministic</xtermref>, <xtermref spec="FO40" ref="dt-context-dependent">context-dependent</xtermref>,  and <xtermref spec="FO40" ref="dt-focus-dependent">focus-dependent</xtermref>. </p></def></gitem><gitem><label>Rules</label><def><p>The <code nobreak="false">$name</code> argument specifies the name of the <termref def="dt-accumulator"/>. 
            The value of the argument <rfc2119>must</rfc2119> be 
            <phrase diff="add" at="2022-01-01">either an <code nobreak="false">xs:QName</code>, or</phrase>
            a string containing an <termref def="dt-eqname"/>. If it is a 
            <termref def="dt-lexical-qname">lexical QName</termref>, then it is expanded as described in
               <specref ref="qname"/> (no prefix means no namespace).</p><p>The function returns the pre-descent value <var>B(N)</var>of the selected accumulator
            where <var>N</var> is the context node, as defined in <specref ref="accumulator-formal-rules"/>.</p><p>If the context item is a node in a streamed document, then the accumulator 
            must be declared with <code nobreak="false">streamable="yes"</code>.</p><note><p>The converse is not true: an accumulator declared to be streamable is available on both
         streamed and unstreamed nodes.</p></note></def></gitem><gitem><label>Error Conditions</label><def><p>
            <error spec="XT" type="dynamic" class="DE" code="3340"><p>It is a <termref def="dt-dynamic-error"/> if the value of the first
                     argument to the <function>accumulator-before</function> or
                        <function>accumulator-after</function> function is 
                  <phrase diff="add" at="2022-01-01">a string that is</phrase> not a valid
                     <termref def="dt-eqname"/>, or if there is no namespace declaration in scope
                  for the prefix of the QName, or if the name obtained by expanding the QName is not
                  the same as the expanded name of any <elcode>xsl:accumulator</elcode> declaration
                  appearing in the <termref def="dt-package">package</termref> in which the function
                  call appears. 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 raise this as a <termref def="dt-static-error">static error</termref>.</p></error>
         </p><p>
            <error spec="XT" type="dynamic" class="DE" code="3350"><p>It is a <termref def="dt-dynamic-error">dynamic error</termref> to call the
                     <function>accumulator-before</function> or
                     <function>accumulator-after</function> function when there is no <termref def="dt-context-item"/>.</p></error>
         </p><p>
            <error spec="XT" type="dynamic" class="TE" code="3360"><p>It is a <termref def="dt-type-error">type error</termref> to call the
                     <function>accumulator-before</function> or
                     <function>accumulator-after</function> function when the <termref def="dt-context-item"/> is 
                  not a node, or when it is an attribute or namespace node.</p></error>
         </p><p>
            <error spec="XT" type="dynamic" class="DE" code="3362"><p>It is a <termref def="dt-dynamic-error">dynamic error</termref> to call the
                     <function>accumulator-before</function> or
                     <function>accumulator-after</function> function when the context
                  item is a node in a tree to which the selected accumulator is not
                  applicable (including the case where it is not applicable
                     because the document is streamed and the accumulator is not 
                  declared with <code nobreak="false">streamable="yes"</code>). Implementations
                  <rfc2119>may</rfc2119> raise this error but are <rfc2119>not required</rfc2119> to do so,
                  if they are capable of streaming documents without imposing this restriction.</p></error>
         </p><p>
            <error spec="XT" type="dynamic" class="DE" code="3400"><p>It is an error if there is a cyclic set of dependencies among accumulators such
                  that the (pre- or post-descent) value of an accumulator depends directly or indirectly on itself.
                  A processor <rfc2119>may</rfc2119> report this as a <termref def="dt-static-error"/> if it
                  can be detected statically. Alternatively a processor <rfc2119>may</rfc2119> report this as a 
                  <termref def="dt-dynamic-error"/>. As a further option, a processor may fail catastrophically when
                  this error occurs.</p></error>
         </p><note><p>The term <term>catastrophic failure</term> here means a failure similar to infinite function or template
         recursion, which might result in stack overflow or even in non-termination of the transformation, rather than in 
         a dynamic error of the kind that can be processed using <elcode>xsl:try</elcode> and <elcode>xsl:catch</elcode>.</p></note></def></gitem><gitem><label>Notes</label><def><note><p>The <function>accumulator-before</function> function can be applied to a node whether or not the accumulator
            has a <code nobreak="false">phase="start"</code> rule for that node. In effect, there is a <code nobreak="false">phase="start"</code> rule
            for every node, where the default rule is to leave the accumulator value unchanged; the 
            <function>accumulator-before</function> function delivers the value of the accumulator after processing
            the explicit or implicit <code nobreak="false">phase="start"</code> rule.</p><p>In XSLT 4.0, the argument can be supplied as a QName literal, for example
         <code nobreak="false">accumulator-before( #accum )</code>.</p></note></def></gitem><gitem><label>Examples</label><def role="example"><table role="medium" border="1" cellpadding="5" width="100%"><tbody><tr><td colspan="2" rowspan="1" align="left" valign="top"><p>Given the accumulator:</p></td></tr><tr><td colspan="2" rowspan="1" align="left" valign="top"><eg xml:space="preserve">
&lt;xsl:accumulator name="a" initial-value="0"&gt;
   &lt;xsl:accumulator-rule match="section" select="$value + 1"/&gt;
&lt;/xsl:accumulator&gt;</eg></td></tr><tr><td colspan="2" rowspan="1" align="left" valign="top"><p>and the template rule:</p></td></tr><tr><td colspan="2" rowspan="1" align="left" valign="top"><eg xml:space="preserve">
&lt;xsl:template match="section"&gt;
   &lt;xsl:value-of select="accumulator-before('a')"/&gt;
   &lt;xsl:apply-templates/&gt;
&lt;/xsl:template&gt;</eg></td></tr><tr><td colspan="2" rowspan="1" align="left" valign="top"><p>The stylesheet will precede the output from processing each section with a section
               number that runs sequentially 1, 2, 3... irrespective of the nesting of sections.</p></td></tr></tbody></table></def></gitem></glist></div2><div2 id="func-accumulator-after"><head>fn:accumulator-after</head><glist><gitem><label>Summary</label><def><p>Returns the post-descent value of the selected accumulator at the context node.</p></def></gitem><gitem><label>Signature</label><def><example role="signature"><proto isOp="no" prefix="fn" name="accumulator-after" return-type="item()*" returnEmptyOk="no" returnSeq="no" returnVaries="no" isSchema="no" isDatatype="no" isSpecial="no"><arg name="name" type="(xs:string | xs:QName)"/></proto></example></def></gitem><gitem><label>Properties</label><def><p>This function is <xtermref spec="FO40" ref="dt-deterministic">deterministic</xtermref>, <xtermref spec="FO40" ref="dt-context-dependent">context-dependent</xtermref>,  and <xtermref spec="FO40" ref="dt-focus-dependent">focus-dependent</xtermref>. </p></def></gitem><gitem><label>Rules</label><def><p>The <code nobreak="false">$name</code> argument specifies the name of the <termref def="dt-accumulator"/>. 
            The value of the argument <rfc2119>must</rfc2119> be 
            <phrase diff="add" at="2022-01-01">either an <code nobreak="false">xs:QName</code>, or</phrase>
            a string containing an <termref def="dt-eqname">EQName</termref>. If it is a
               <termref def="dt-lexical-qname">lexical QName</termref>, then it is expanded as
            described in <specref ref="qname"/> (no prefix means no namespace).</p><p>The function returns the post-descent value <var>A(N)</var> of the selected accumulator
            where <var>N</var> is the context node, as defined in <specref ref="accumulator-formal-rules"/>.</p><p>If the context item is a node in a streamed document, then the accumulator 
            must be declared with <code nobreak="false">streamable="yes"</code>.</p><note><p>The converse is not true: an accumulator declared to be streamable is available on both
            streamed and unstreamed nodes.</p></note></def></gitem><gitem><label>Error Conditions</label><def><p>The following errors apply: <errorref spec="XT" type="dynamic" class="DE" code="3340"/>,
               <errorref spec="XT" type="dynamic" class="DE" code="3350"/>, <errorref spec="XT" type="type" class="TE" code="3360"/>, <errorref spec="XT" type="dynamic" class="DE" code="3362"/>, <errorref spec="XT" type="dynamic" class="DE" code="3400"/>. </p><p>For constraints on the use of <function>accumulator-after</function> when streaming, see
         <xspecref spec="SG40" ref="streamability-fn-accumulator-after"/>.</p></def></gitem><gitem><label>Notes</label><def><note><p>The <function>accumulator-after</function> function can be applied to a node whether or not the accumulator
            has a <code nobreak="false">phase="end"</code> rule for that node. In effect, there is a <code nobreak="false">phase="end"</code> rule
            for every node, where the default rule is to leave the accumulator value unchanged; the 
            <function>accumulator-after</function> function delivers the value of the accumulator after processing
            the explicit or implicit <code nobreak="false">phase="end"</code> rule.</p><p>In XSLT 4.0, the argument can be supplied as a QName literal, for example
         <code nobreak="false">accumulator-before( #accum )</code>.</p></note></def></gitem><gitem><label>Examples</label><def role="example"><table role="medium" border="1" cellpadding="5" width="100%"><tbody><tr><td colspan="2" rowspan="1" align="left" valign="top"><p>Given the accumulator:</p></td></tr><tr><td colspan="2" rowspan="1" align="left" valign="top"><eg xml:space="preserve">
&lt;xsl:accumulator name="w" initial-value="0" streamable="true" as="xs:integer"&gt;
   &lt;xsl:accumulator-rule match="text()" 
                         select="$value + count(tokenize(.))"/&gt;
&lt;/xsl:accumulator&gt;</eg></td></tr><tr><td colspan="2" rowspan="1" align="left" valign="top"><p>and the template rule:</p></td></tr><tr><td colspan="2" rowspan="1" align="left" valign="top"><eg xml:space="preserve">
&lt;xsl:template match="section"&gt;
   &lt;xsl:apply-templates/&gt;
   (words: &lt;xsl:value-of select="accumulator-after('w') - accumulator-before('w')"/&gt;)
&lt;/xsl:template&gt;</eg></td></tr><tr><td colspan="2" rowspan="1" align="left" valign="top"><p>The stylesheet will output at the end of each section a (crude) count of the number of words
               in that section.</p></td></tr></tbody></table></def></gitem></glist></div2><div2 id="accumulators-visibility-and-overriding"><head>Importing of Accumulators</head><p>If a <termref def="dt-package">package</termref> contains more than one
                     <elcode>xsl:accumulator</elcode> declaration with a particular name, then the
                  one with the highest <termref def="dt-import-precedence"/> is used.</p><p>
                  <error spec="XT" type="static" class="SE" code="3350"><p>It is a <xtermref spec="XT40" ref="dt-static-error">static error</xtermref> for a 
                        <termref def="dt-package">package</termref> to contain two or more 
                        <phrase diff="del" at="2022-01-01">non-hidden</phrase>
                        accumulators with the same <termref def="dt-expanded-qname">expanded
                           QName</termref> and the same <termref def="dt-import-precedence">import
                           precedence</termref>, unless there is another accumulator with the same
                           <termref def="dt-expanded-qname">expanded QName</termref>, and a higher
                        import precedence.</p></error>
               </p><p>Accumulators cannot be referenced from, or overridden
                  in, a different package from the one in which they are declared.</p></div2><div2 id="capturing-accumulators"><head>Capturing Accumulators</head><changes><change issue="211" PR="717" date="2023-09-29">
                     Capturing accumulators have been added; when streaming with a capturing accumulator,
                     the <function>accumulator-after</function> has full access to a snapshot of the matched
                     element node.
                  </change></changes><p>The <code nobreak="false">capture</code> attribute is intended primarily for use with streamable accumulators, but
                  in the interests of consistency, it has the same effect both for streamable and non-streamable
                  accumulators. If an accumulator rule with <code nobreak="false">phase="end"</code> and <code nobreak="false">capture="yes"</code>
                  matches an element node,
                  then the rule is evaluated not with the matched element node as the context item, but rather with a snapshot
                  copy of the matched node. The snapshot copy is made following the rules of the <function>snapshot</function>
                  function, with one exception: no accumulator values are copied into the snapshot tree (which would otherwise
                  happen: see <specref ref="copying-accumulators"/>).</p><p diff="add" at="issue1013">If a rule with <code nobreak="false">capture="yes"</code> matches a node other than an element, the attribute
               has no effect.</p><note><p>The principal effect of specifying <code nobreak="false">capture="yes"</code> is to relax
                  the rules for streamability. With this option, the <code nobreak="false">phase="end"</code> accumulator rule
                  has access to the full subtree rooted at the node being visited. In a typical implementation,
                  a streaming processor encountering an element that matches a capturing accumulator rule
                  will make an on-the-fly in-memory copy of that element, allowing the <code nobreak="false">phase="end"</code>
                  accumulator rule full access to the subtree, and also to attributes of ancestors.</p><p>This means that an accumulator that needs access to the typed value or string value of an element 
                     can get this directly with a rule that matches the element, avoiding the need 
                     to write rules that match the element’s text node children.
                  </p><p>For example, to capture a copy of the most recent <code nobreak="false">h2</code> element in a document,
                  the following accumulator might be declared:</p><eg xml:space="preserve">&lt;xsl:accumulator name="most-recent-h2" streamable="yes"&gt;
  &lt;xsl:accumulator-rule match="h2" phase="end" capture="yes" select="."/&gt;
&lt;/xsl:accumulator&gt;</eg><p>and subsequent processing wishing to copy the most recent <code nobreak="false">h2</code> element into the result
                  tree can simply use <code nobreak="false">&lt;xsl:copy-of select="accumulator-before('most-recent-h2')"/&gt;</code>.</p><p>Without the <code nobreak="false">capture="yes"</code> attribute, this accumulator would be rejected
                  as non-streamable, because the <code nobreak="false">select</code> expression on the accumulator rule
                  is consuming.</p></note><example id="use-accumulator-to-create-glossary"><head>Using a capturing accumulator to construct a glossary</head><p>Suppose a document contains definitions of technical terms with markup such as:</p><eg xml:space="preserve">&lt;define term="oxidation"&gt;In &lt;topic&gt;chemistry&lt;/topic&gt;, 
   &lt;term&gt;oxidation&lt;/term&gt; is a chemical process in which atoms lose electrons.&lt;/define&gt;</eg><p>and the requirement is to generate a glossary that lists all the defined terms in the document, as an appendix.</p><p>This can be achieved by capturing all the defined terms in a map:</p><eg xml:space="preserve">&lt;xsl:accumulator name="glossary-terms" 
         as="{ xs:string, element(define) }" 
         initial-value="{}"
         streamable="yes"&gt;
   &lt;xsl:accumulator-rule match="define[@term]" 
           phase="end" 
           capture="yes"
           select="map:put($value, @term, .)"/&gt;
&lt;/xsl:accumulator&gt;</eg><p>Suppose that the input XML document contains an element <code nobreak="false">&lt;glossary/&gt;</code> marking
                     the point where the glossary is to be inserted. The glossary can then be generated
                     using a template rule such as:</p><eg xml:space="preserve">&lt;xsl:template match="glossary"&gt;
  &lt;h2&gt;Glossary&lt;/h2&gt;
  &lt;dl&gt;
    &lt;xsl:for-each select="map:pairs(accumulator-before('glossary-terms'))"&gt;
      &lt;xsl:sort select="?key"/&gt;
      &lt;dt&gt;{?key}&lt;/dt&gt;
      &lt;dd&gt;&lt;xsl:apply-templates select="?value"/&gt;&lt;/dd&gt;
    &lt;/xsl:for-each&gt;
  &lt;/dl&gt;  
&lt;/xsl:template&gt;</eg></example><p diff="add" at="issue731">
                  <error spec="XT" type="static" class="SE" code="3355"><p>It is a <xtermref spec="XT40" ref="dt-static-error">static error</xtermref> for a 
                        an <elcode>xsl:accumulator-rule</elcode> element to specify
                     <code nobreak="false">capture="yes"</code> unless it also specifies <code nobreak="false">phase="end"</code>.</p></error>
               </p><note diff="add" at="issue731"><p>Since <code nobreak="false">capture="yes"</code> causes the subtree of the relevant element node
                  to be built in memory, using this option on an element that has a large subtree is best
                  avoided, because it can defeat the purpose of streaming.</p></note></div2><div2 id="copying-accumulators"><head>Copying Accumulator Values</head><p>When nodes (including streamed nodes) are copied using the
                     <function>snapshot</function> or <function>copy-of</function> functions, or
                  using the <elcode>xsl:copy-of</elcode> instruction with the attribute
                     <code nobreak="false">copy-accumulators="yes"</code>, then the pre-descent and post-descent
                  values of accumulators for that tree are not determined by traversing the tree as
                  described in <specref ref="accumulator-informal-rules"/> and <specref ref="accumulator-formal-rules"/>. Instead the values are the same as the values
                  on the corresponding nodes of the source tree. </p><p>This applies also to the implicit invocation of the <function>snapshot</function>
                  function that happens during the evaluation of <elcode>xsl:merge</elcode>.</p><p>If an accumulator is not applicable to a tree <var>S</var>, then it is also not
                  applicable to any tree formed by copying nodes from <var>S</var> using the above
                  methods.</p><note><p>During streamed processing, accumulator values will typically be computed “on
                     the fly”; when the <function>copy-of</function> or
                        <function>snapshot</function> functions are applied to a streamed node, the
                     computed accumulator values for the streamed document will typically be
                     materialized and saved as part of the copy.</p><p>Accumulator values for a non-streamed document will often be computed lazily,
                     that is, they will not be computed unless and until they are needed. A call on
                        <function>copy-of</function> or <function>snapshot</function> on a
                     non-streamed document whose accumulator values have not yet been computed can
                     then be handled in a variety of ways. The implementation might interpret the
                     call on <function>copy-of</function> or <function>snapshot</function> as a
                     trigger causing the accumulator values to be computed; or it might retain a
                     link between the nodes of the copied tree and the nodes of the original tree,
                     so that a request for accumulator values on the copied tree can trigger
                     computation of accumulator values for the original tree. </p></note></div2><div2 id="accumulator-examples"><head>Examples of Accumulators</head><example><head>Remember the Title of a Document</head><p>Consider an XHTML document in which the title of the document is represented by
                     the content of a <code nobreak="false">title</code> element appearing as a child of the
                        <code nobreak="false">head</code> element, which in turn appears as a child of the
                        <code nobreak="false">html</code> element. Suppose that we want to process the document in
                     streaming mode, and that we want to avoid outputting the content of the
                        <code nobreak="false">h1</code> element if it is the same as the document title.</p><p>This can be achieved by remembering the value of the title in an accumulator
                     variable.</p><eg role="xslt-declaration" xml:space="preserve">
  &lt;xsl:accumulator name="firstTitle" as="xs:string?" initial-value="()" 
                                                     streamable="yes"&gt;
    &lt;xsl:accumulator-rule match="/html/head/title/text()" select="string(.)"/&gt;
  &lt;/xsl:accumulator&gt;
  </eg><p>Subsequently, while processing an <code nobreak="false">h1</code> element appearing later in
                     the document, the value can be referenced:</p><eg role="xslt-declaration" xml:space="preserve">
  &lt;xsl:template match="h1"&gt;
    &lt;xsl:variable name="firstTitle" select="accumulator-before('firstTitle')"/&gt;
    &lt;xsl:variable name="thisTitle" select="string(.)"/&gt;
    &lt;xsl:if test="$thisTitle ne $firstTitle"&gt;
      &lt;div class="heading-1"&gt;&lt;xsl:value-of select="$thisTitle"/&gt;&lt;/div&gt;
    &lt;/xsl:if&gt;
    &lt;/xsl:template&gt;</eg></example><example><head>Keep a Word Count</head><p>Suppose that there is a requirement to output, at the end of the HTML rendition
                     of a document, a paragraph giving the total number of words in the
                     document.</p><p>An accumulator can be used to maintain a (crude) word count as follows:</p><eg role="xslt-declaration" xml:space="preserve">
  &lt;xsl:accumulator name="word-count" 
                   as="xs:integer" 
                   initial-value="0"&gt;
    &lt;xsl:accumulator-rule match="text()" 
         select="$value + count(tokenize(.))"/&gt;
  &lt;/xsl:accumulator&gt;
  </eg><p diff="del" at="2022-01-01"><emph>Note: the call on <code nobreak="false">tokenize#1</code> relies on XPath 3.1</emph></p><p>The final value can be output at the end of the document:</p><eg role="xslt-declaration" xml:space="preserve">
   &lt;xsl:template match="/"&gt;
     &lt;xsl:apply-templates/&gt;
     &lt;p&gt;Word count: &lt;xsl:value-of select="accumulator-after('word-count')"/&gt;&lt;/p&gt;
   &lt;/xsl:template&gt;</eg></example><example><head>Output Hierarchic Section Numbers</head><p>Consider a document in which <code nobreak="false">section</code> elements are nested within
                        <code nobreak="false">section</code> elements to arbitrary depth, and there is a requirement
                     to render the document with hierarchic section numbers of the form
                        <code nobreak="false">3.5.1.4</code>.</p><p>The current section number can be maintained in an accumulator in the form of a
                     sequence of integers, managed as a stack. The number of integers represents the
                     current level of nesting, and the value of each integer represents the number
                     of preceding sibling sections encountered at that level. For convenience the
                     first item in the sequence represents the top of the stack.</p><eg role="xslt-declaration" xml:space="preserve">
&lt;xsl:accumulator name="section-nr" as="xs:integer*" 
                 initial-value="0"&gt;
  &lt;xsl:accumulator-rule match="section" phase="start" 
                 select="0, head($value)+1, tail($value)"/&gt;
  &lt;xsl:accumulator-rule match="section" phase="end" 
                 select="tail($value) (:pop:)"/&gt;
&lt;/xsl:accumulator&gt;  
</eg><p>To illustrate this, consider the values after processing a series of start and
                     end tags:</p><table class="data" border="1" cellpadding="5" width="100%"><caption>Example data illustrating the effect of parsing events on an accumulator</caption><thead><tr><th rowspan="1" colspan="1" align="left" valign="top">events</th><th rowspan="1" colspan="1" align="left" valign="top">accumulator value</th><th rowspan="1" colspan="1" align="left" valign="top">required section number</th></tr></thead><tbody><tr><td rowspan="1" colspan="1" align="left" valign="top"><code nobreak="false">&lt;section&gt;</code></td><td rowspan="1" colspan="1" align="left" valign="top"><code nobreak="false">0, 1</code></td><td rowspan="1" colspan="1" align="left" valign="top">1</td></tr><tr><td rowspan="1" colspan="1" align="left" valign="top"><code nobreak="false">&lt;section&gt;</code></td><td rowspan="1" colspan="1" align="left" valign="top"><code nobreak="false">0, 1, 1</code></td><td rowspan="1" colspan="1" align="left" valign="top">1.1</td></tr><tr><td rowspan="1" colspan="1" align="left" valign="top"><code nobreak="false">&lt;/section&gt;</code></td><td rowspan="1" colspan="1" align="left" valign="top"><code nobreak="false">1, 1</code></td><td rowspan="1" colspan="1" align="left" valign="top"> </td></tr><tr><td rowspan="1" colspan="1" align="left" valign="top"><code nobreak="false">&lt;section&gt;</code></td><td rowspan="1" colspan="1" align="left" valign="top"><code nobreak="false">0, 2, 1</code></td><td rowspan="1" colspan="1" align="left" valign="top">1.2</td></tr><tr><td rowspan="1" colspan="1" align="left" valign="top"><code nobreak="false">&lt;/section&gt;</code></td><td rowspan="1" colspan="1" align="left" valign="top"><code nobreak="false">2, 1</code></td><td rowspan="1" colspan="1" align="left" valign="top"> </td></tr><tr><td rowspan="1" colspan="1" align="left" valign="top"><code nobreak="false">&lt;section&gt;</code></td><td rowspan="1" colspan="1" align="left" valign="top"><code nobreak="false">0, 3, 1</code></td><td rowspan="1" colspan="1" align="left" valign="top">1.3</td></tr><tr><td rowspan="1" colspan="1" align="left" valign="top"><code nobreak="false">&lt;section&gt;</code></td><td rowspan="1" colspan="1" align="left" valign="top"><code nobreak="false">0, 1, 3, 1</code></td><td rowspan="1" colspan="1" align="left" valign="top">1.3.1</td></tr><tr><td rowspan="1" colspan="1" align="left" valign="top"><code nobreak="false">&lt;/section&gt;</code></td><td rowspan="1" colspan="1" align="left" valign="top"><code nobreak="false">1, 3, 1</code></td><td rowspan="1" colspan="1" align="left" valign="top"> </td></tr><tr><td rowspan="1" colspan="1" align="left" valign="top"><code nobreak="false">&lt;section&gt;</code></td><td rowspan="1" colspan="1" align="left" valign="top"><code nobreak="false">0, 2, 3, 1</code></td><td rowspan="1" colspan="1" align="left" valign="top">1.3.2</td></tr><tr><td rowspan="1" colspan="1" align="left" valign="top"><code nobreak="false">&lt;/section&gt;</code></td><td rowspan="1" colspan="1" align="left" valign="top"><code nobreak="false">2, 3, 1</code></td><td rowspan="1" colspan="1" align="left" valign="top"> </td></tr><tr><td rowspan="1" colspan="1" align="left" valign="top"><code nobreak="false">&lt;/section&gt;</code></td><td rowspan="1" colspan="1" align="left" valign="top"><code nobreak="false">3, 1</code></td><td rowspan="1" colspan="1" align="left" valign="top"> </td></tr><tr><td rowspan="1" colspan="1" align="left" valign="top"><code nobreak="false">&lt;/section&gt;</code></td><td rowspan="1" colspan="1" align="left" valign="top"><code nobreak="false">1</code></td><td rowspan="1" colspan="1" align="left" valign="top"> </td></tr></tbody></table><p>The section number for a section can thus be generated as:</p><eg role="xslt-declaration" xml:space="preserve">
&lt;xsl:template match="section"&gt;
  &lt;p&gt;
    &lt;xsl:value-of select="reverse(tail(accumulator-before('section-nr')))" 
                  separator="."/&gt;
  &lt;/p&gt;
  &lt;xsl:apply-templates/&gt;
&lt;/xsl:template&gt;
                  </eg></example><example><head>Compute a Histogram showing the Number of Books, by Publisher</head><eg role="xslt-declaration" xml:space="preserve">
 &lt;xsl:accumulator name="histogram" as="map(xs:string, xs:integer)"
    initial-value="{}"&gt;
    &lt;xsl:accumulator-rule match="book"&gt;
      &lt;xsl:choose&gt;
        &lt;xsl:when test="map:contains($value, @publisher)"&gt;
          &lt;xsl:sequence select="map:put($value, string(@publisher), 
                                        $value(@publisher)+1)"/&gt;
        &lt;/xsl:when&gt;
        &lt;xsl:otherwise&gt;
          &lt;xsl:sequence select="map:put($value, string(@publisher), 1)"/&gt;
        &lt;/xsl:otherwise&gt;
      &lt;/xsl:choose&gt;
    &lt;/xsl:accumulator-rule&gt;  
 &lt;/xsl:accumulator&gt;</eg><p>The <code nobreak="false">contained sequence constructor</code> is
                     evaluated with the variable <code nobreak="false">$value</code> set to the current value, and
                     with the context node as the node being visited.</p><note><p>In the two calls on <code nobreak="false">map:put()</code>, it is necessary to explicitly
                        convert <code nobreak="false">@publisher</code> to an <code nobreak="false">xs:string</code> value, because
                        this is the declared type of the keys in the result map. Relying on
                        atomization would produce keys of type <code nobreak="false">xs:untypedAtomic</code>, which
                        would not satisfy the declared type of the map.</p></note><p>The accumulated histogram might be displayed as
                     follows:</p><eg role="xslt-instruction" xml:space="preserve">
 &lt;xsl:source-document streamable="yes" href="booklist.xml" expand-text="yes"&gt;
   .....
   &lt;h1&gt;Number of books, by publisher&lt;/h1&gt;
   &lt;table&gt;
     &lt;thead&gt;
       &lt;th&gt;Publisher&lt;/th&gt;
       &lt;th&gt;Number of books&lt;/th&gt;
     &lt;/thead&gt;
     &lt;tbody&gt;
       &lt;xsl:variable name="histogram" select="accumulator-after('histogram')"/&gt;
       &lt;xsl:for-each select="map:keys($histogram)"&gt;
         &lt;tr&gt;
           &lt;td&gt;{.}&lt;/td&gt;
           &lt;td&gt;{$histogram(.)}&lt;/td&gt;
         &lt;/tr&gt;
       &lt;/xsl:for-each&gt;
     &lt;/tbody&gt;
   &lt;/table&gt;
 &lt;/xsl:source-document&gt;</eg></example></div2></div1><div1 id="add-func"><head>Additional Functions</head><changes><change date="2022-01-01">
               Functions that accept a lexical QName as an argument, such as <function>key</function>,
               <function>function-available</function>, <function>element-available</function>,
               <function>type-available</function>, <function>system-property</function>,
               <function>accumulator-before</function>, and <function>accumulator-after</function>,
               now have the option of supplying an <code nobreak="false">xs:QName</code> value instead.
               [This change was in the editor's draft accepted by the WG as its baseline when
               it started work.]
            </change></changes><p>This section describes XSLT-specific additions to the XPath function library. Some of these 
            additional functions also make use of
            information specified by <termref def="dt-declaration">declarations</termref> in the
            stylesheet; this section also describes these declarations.</p><div2 id="func-document"><head>fn:document</head><changes><change issue="2292">An options parameter has been added.</change></changes><glist><gitem><label>Summary</label><def><p>Provides access to XML documents identified by a URI.</p></def></gitem><gitem><label>Signature</label><def><example role="signature"><proto isOp="no" prefix="fn" name="document" return-type="node()*" returnEmptyOk="no" returnSeq="no" returnVaries="no" isSchema="no" isDatatype="no" isSpecial="no"><arg name="uri-sequence" type="item()*"/><arg name="options" type="(map(*)|node())?" default="map{}"/></proto></example></def></gitem><gitem><label>Properties</label><def><p>The one-argument form of this function is <xtermref spec="FO40" ref="dt-deterministic">deterministic</xtermref>, <xtermref spec="FO40" ref="dt-focus-independent">focus-independent</xtermref>,  and <xtermref spec="FO40" ref="dt-context-dependent">context-dependent</xtermref>.  It depends on 
		static base URI.
	</p><p>The two-argument form of this function is <xtermref spec="FO40" ref="dt-deterministic">deterministic</xtermref>, <xtermref spec="FO40" ref="dt-focus-independent">focus-independent</xtermref>,  and <xtermref spec="FO40" ref="dt-context-independent">context-independent</xtermref>. </p></def></gitem><gitem><label>Rules</label><def><p>The <function>document</function> function allows access to XML documents identified by
            a URI.</p><p>The first argument contains a sequence of URI references. These are resolved
            as described below.</p><p>The second argument, if present, may be either a node, or an options map. 
            Supplying a node is allowed for backwards compatibility: the effect of supplying a node <code nobreak="false">$N</code>
            is the same as supplying the map <code nobreak="false">{"base-uri": fn:base-uri($N)}</code>.
            The effect is that the base URI of the node is used to resolve any relative URI references
            contained in the first argument.</p><p>If the second argument is supplied as a map, then the 
            <xtermref spec="FO40" ref="option-parameter-conventions"/> apply. The options available are as follows, and
         apply to each of the documents constructed by the function:</p><example role="record"><record returnEmptyOk="no" returnSeq="no" prefix="fn" returnVaries="no" isSchema="no" isDatatype="no" isSpecial="no" isOp="no"><arg name="base-uri" type="xs:anyURI" occur="opt"/><arg name="trusted" type="xs:boolean" occur="opt"/><arg name="dtd-validation" type="xs:boolean" occur="opt"/><arg name="stable" type="xs:boolean" occur="opt"/><arg name="strip-space" type="xs:boolean?" occur="opt"/><arg name="xinclude" type="xs:boolean" occur="opt"/><arg name="xsd-validation" type="xs:string" occur="opt"/><arg name="use-xsi-schema-location" type="xs:boolean" occur="opt"/><arg name="schema" type="xs:NCName" occur="opt"/></record></example><table class="fos-options" border="1" cellpadding="5" width="100%"><thead><tr><th rowspan="1" colspan="1" align="left" valign="top">Key</th><th rowspan="1" colspan="1" align="left" valign="top">Value</th><th rowspan="1" colspan="1" align="left" valign="top">Meaning</th></tr></thead><tbody><tr><td rowspan="1" colspan="1" align="left" valign="top"><p><code nobreak="false">base-uri?</code></p></td><td class="fos-thin" colspan="2" rowspan="1" align="left" valign="top">Determines the base URI used to resolve any relative URI supplied
                     in the first argument. This in turn affects the base URI of the constructed
                     document.
                  <ulist><item><p><term>Type: </term><code nobreak="false">xs:anyURI</code></p></item><item><p><term>Default: </term>Where the first argument supplies a node, the base URI property of that node is used
                     to resolve the URI. Where the first argument supplies an atomic value,
                     the static base URI of the function call is used.</p></item></ulist></td></tr><tr><td rowspan="3" colspan="1" align="left" valign="top"><p><code nobreak="false">trusted?</code></p></td><td class="fos-thick" colspan="2" rowspan="1" align="left" valign="top">Indicates whether processing the document may cause other
                  external resources to be fetched (including, for example, external entities, an external DTD,
                  or documents referenced using <code nobreak="false">xsi:schemaLocation</code> or
                  XInclude elements).<ulist><item><p><term>Type: </term><code nobreak="false">xs:boolean</code></p></item><item><p><term>Default: </term><code nobreak="false">false</code></p></item></ulist></td></tr><tr><td class="fos-thin" rowspan="1" colspan="1" align="left" valign="top"><code nobreak="false">true</code></td><td rowspan="1" colspan="1" align="left" valign="top">The document may include references to other external
                     resources.
                  </td></tr><tr><td class="fos-thick" rowspan="1" colspan="1" align="left" valign="top"><code nobreak="false">false</code></td><td rowspan="1" colspan="1" align="left" valign="top">The document must not include references to other
                     external resources unless access to these resources has been explicitly
                     enabled.
                  </td></tr><tr><td rowspan="3" colspan="1" align="left" valign="top"><p><code nobreak="false">dtd-validation?</code></p></td><td class="fos-thick" colspan="2" rowspan="1" align="left" valign="top">Determines whether DTD validation takes place.<ulist><item><p><term>Type: </term><code nobreak="false">xs:boolean</code></p></item><item><p><term>Default: </term><code nobreak="false">false</code></p></item></ulist></td></tr><tr><td class="fos-thin" rowspan="1" colspan="1" align="left" valign="top"><code nobreak="false">true</code></td><td rowspan="1" colspan="1" align="left" valign="top">The input is parsed using a validating XML parser.
                  The input must contain a <code nobreak="false">DOCTYPE</code> declaration to identify
                  the DTD to be used for validation. The DTD may be internal or external.
                  </td></tr><tr><td class="fos-thick" rowspan="1" colspan="1" align="left" valign="top"><code nobreak="false">false</code></td><td rowspan="1" colspan="1" align="left" valign="top">DTD validation does not take place. However, if a
                     <code nobreak="false">DOCTYPE</code> declaration is present, then it is read, for example
                     to perform entity expansion.
                  </td></tr><tr><td rowspan="3" colspan="1" align="left" valign="top"><p><code nobreak="false">stable?</code></p></td><td class="fos-thick" colspan="2" rowspan="1" align="left" valign="top">Determines whether two calls on the <function>document</function> function,
               with the same URI, the same options, and the same context, are guaranteed to return
               the same document node. The default value is <code nobreak="false">true</code>, but this may be overridden
               by implementation-defined configuration options.<ulist><item><p><term>Type: </term><code nobreak="false">xs:boolean</code></p></item><item><p><term>Default: </term><code nobreak="false">true</code></p></item></ulist></td></tr><tr><td class="fos-thin" rowspan="1" colspan="1" align="left" valign="top"><code nobreak="false">true</code></td><td rowspan="1" colspan="1" align="left" valign="top">Given the same explicit and implicit arguments, multiple
                     calls return the same document node: that is, the function is <xtermref spec="FO40" ref="dt-deterministic"/>.
                  </td></tr><tr><td class="fos-thick" rowspan="1" colspan="1" align="left" valign="top"><code nobreak="false">false</code></td><td rowspan="1" colspan="1" align="left" valign="top">Multiple calls with the same explicit and implicit arguments
                     may return the same document node or different document nodes at the discretion of
                     the implementation.
                  </td></tr><tr><td rowspan="3" colspan="1" align="left" valign="top"><p><code nobreak="false">strip-space?</code></p></td><td class="fos-thick" colspan="2" rowspan="1" align="left" valign="top">Determines whether whitespace-only text nodes are removed
                  from the resulting document.
               <ulist><item><p><term>Type: </term><code nobreak="false">xs:boolean?</code></p></item><item><p><term>Default: </term><code nobreak="false">true</code></p></item></ulist></td></tr><tr><td class="fos-thin" rowspan="1" colspan="1" align="left" valign="top"><code nobreak="false">true</code></td><td rowspan="1" colspan="1" align="left" valign="top">Whitespace stripping is to take place according 
                     to the <elcode>xsl:strip-space</elcode>
                  and <elcode>xsl:preserve-space</elcode> declarations of the containing <termref def="dt-package"/>:
                     see <specref ref="strip"/>.
                  </td></tr><tr><td class="fos-thick" rowspan="1" colspan="1" align="left" valign="top"><code nobreak="false">false</code></td><td rowspan="1" colspan="1" align="left" valign="top">All whitespace-only text nodes are preserved,
                  unless either (a) DTD validation marks them as ignorable, or (b) XSD validation recognizes
                  the containing element as having element-only or empty content.
                  </td></tr><tr><td rowspan="3" colspan="1" align="left" valign="top"><p><code nobreak="false">xinclude?</code></p></td><td class="fos-thick" colspan="2" rowspan="1" align="left" valign="top">Determines whether any <code nobreak="false">xi:include</code> elements in the input
                  are to be processed using an XInclude processor.<ulist><item><p><term>Type: </term><code nobreak="false">xs:boolean</code></p></item><item><p><term>Default: </term><code nobreak="false">false</code></p></item></ulist></td></tr><tr><td class="fos-thin" rowspan="1" colspan="1" align="left" valign="top"><code nobreak="false">true</code></td><td rowspan="1" colspan="1" align="left" valign="top">Any <code nobreak="false">xi:include</code> elements are expanded. If there are
                     <code nobreak="false">xi:include</code> elements and no XInclude processor is available then 
                     a dynamic error is raised.
                  </td></tr><tr><td class="fos-thick" rowspan="1" colspan="1" align="left" valign="top"><code nobreak="false">false</code></td><td rowspan="1" colspan="1" align="left" valign="top">Any <code nobreak="false">xi:include</code> elements are handled as
                     ordinary elements without expansion.
                  </td></tr><tr><td rowspan="5" colspan="1" align="left" valign="top"><p><code nobreak="false">xsd-validation?</code></p></td><td class="fos-thick" colspan="2" rowspan="1" align="left" valign="top">Determines whether XSD validation takes place, using the
                  schema definitions present in the static context. The effect of requesting
               validation is the same as invoking the <function>document</function> function without
               validation, and then applying the instruction <elcode>xsl:copy-of</elcode> to the result,
               with corresponding <code nobreak="false">validation</code> and <code nobreak="false">type</code> options,
               using the schema identified in the <code nobreak="false">schema</code> option if specified.<ulist><item><p><term>Type: </term><code nobreak="false">xs:string</code></p></item><item><p><term>Default: </term><code nobreak="false">skip</code></p></item></ulist></td></tr><tr><td class="fos-thin" rowspan="1" colspan="1" align="left" valign="top"><code nobreak="false">strict</code></td><td rowspan="1" colspan="1" align="left" valign="top">Strict XSD validation takes place</td></tr><tr><td class="fos-thin" rowspan="1" colspan="1" align="left" valign="top"><code nobreak="false">lax</code></td><td rowspan="1" colspan="1" align="left" valign="top">Lax XSD validation takes place</td></tr><tr><td class="fos-thin" rowspan="1" colspan="1" align="left" valign="top"><code nobreak="false">skip</code></td><td rowspan="1" colspan="1" align="left" valign="top">No XSD validation takes place</td></tr><tr><td class="fos-thick" rowspan="1" colspan="1" align="left" valign="top"><code nobreak="false">type Q{uri}local</code></td><td rowspan="1" colspan="1" align="left" valign="top">XSD validation takes place against the
                  schema-defined type, present in the selected schema, that has the given URI
                  and local name.</td></tr><tr><td rowspan="3" colspan="1" align="left" valign="top"><p><code nobreak="false">use-xsi-schema-location?</code></p></td><td class="fos-thick" colspan="2" rowspan="1" align="left" valign="top">When XSD validation takes place, determines whether
                  schema components referenced using <code nobreak="false">xsi:schemaLocation</code> or <code nobreak="false">xsi:noNamespaceSchemaLocation</code>
                  attributes within the source document are to be used. The option is ignored
                  if XSD validation does not take place.<ulist><item><p><term>Type: </term><code nobreak="false">xs:boolean</code></p></item><item><p><term>Default: </term><code nobreak="false">false</code></p></item></ulist></td></tr><tr><td class="fos-thin" rowspan="1" colspan="1" align="left" valign="top"><code nobreak="false">true</code></td><td rowspan="1" colspan="1" align="left" valign="top">XSD validation uses the schema components referenced 
                  using <code nobreak="false">xsi:schemaLocation</code> or <code nobreak="false">xsi:noNamespaceSchemaLocation</code>
                  attributes in addition to the schema components present in the static context;
                  these components must be compatible as described in <xspecref spec="DM40" ref="schema-consistency"/>.</td></tr><tr><td class="fos-thick" rowspan="1" colspan="1" align="left" valign="top"><code nobreak="false">false</code></td><td rowspan="1" colspan="1" align="left" valign="top">Any <code nobreak="false">xsi:schemaLocation</code> and <code nobreak="false">xsi:noNamespaceSchemaLocation</code>
                  attributes in the document are ignored.</td></tr><tr><td rowspan="1" colspan="1" align="left" valign="top"><p><code nobreak="false">schema?</code></p></td><td class="fos-thin" colspan="2" rowspan="1" align="left" valign="top">When XSD validation takes place, identifies the schema to be used for validation.
               If supplied, the value must match the <code nobreak="false">role</code> attribute of an <elcode>xsl:import-schema</elcode>
                  declaration in the containing <termref def="dt-package"/>. A zero-length string refers to the
                  schema imported using an <elcode>xsl:import-schema</elcode> declaration with no <code nobreak="false">role</code>
                  attribute.
               <ulist><item><p><term>Type: </term><code nobreak="false">xs:NCName</code></p></item><item><p><term>Default: </term>The schema in the static context of the <function>fn:document</function>
               function call (determined by the innermost element with an <code nobreak="false">[xsl:]schema-role</code>
                  attribute if present).</p></item></ulist></td></tr></tbody></table><p>A sequence of absolute URI references is obtained as follows.</p><ulist><item><p>For an item in <code nobreak="false">$uri-sequence</code> that is an instance of
                     <code nobreak="false">xs:string</code>, <code nobreak="false">xs:anyURI</code>, or
                     <code nobreak="false">xs:untypedAtomic</code>, the value is cast to <code nobreak="false">xs:anyURI</code>. If
                  the resulting URI reference is an absolute URI reference then it is used <emph>as
                     is</emph>. If it is a relative URI reference <var>R</var>, then it is resolved as follows:</p><olist><item><p>If the second argument <code nobreak="false">$options</code> is an XNode, 
                        then <var>R</var> is resolved against the base URI of that node.</p></item><item><p>If <code nobreak="false">$options</code> is supplied as a map and includes a value for the
                     <code nobreak="false">base-uri</code> option, then <var>R</var> is resolved against that URI.</p></item><item><p>Otherwise <var>R</var> is resolved against the static base URI from the static context of the
                  expression containing the call to the <function>document</function> function. In cases where the source
                  code of the stylesheet is available at execution time, this will typically be the location of the
                  relevant stylesheet module.</p></item></olist></item><item><p>For an item in <code nobreak="false">$uri-sequence</code> that is a node <var>N</var>, 
                  the node is <termref def="dt-atomization">atomized</termref>. The result <rfc2119>must</rfc2119> be
                  a sequence whose items are all instances of <code nobreak="false">xs:string</code>,
                     <code nobreak="false">xs:anyURI</code>, or <code nobreak="false">xs:untypedAtomic</code>. Each of these values
                  is cast to <code nobreak="false">xs:anyURI</code>, and if the resulting URI reference is an
                  absolute URI reference then it is used <emph>as is</emph>. If it is a relative URI
                  reference <var>R</var>, then it is resolved as follows:</p><olist><item><p>If the second argument <code nobreak="false">$options</code> is an XNode, 
                        then <var>R</var> is resolved against the base URI of that node.</p></item><item><p>If <code nobreak="false">$options</code> is supplied as a map and includes a value for the
                     <code nobreak="false">base-uri</code> option, then <var>R</var> is resolved against that URI.</p></item><item><p>Otherwise <var>R</var> is resolved against the base URI of <var>N</var>.</p></item></olist></item><item><p>A relative URI is resolved against a base URI using the rules of the <xfunction>resolve-uri</xfunction>
                  function. A dynamic error occurs (see below) if no base URI is available.</p></item><item><p> If <code nobreak="false">$uri-sequence</code> (after atomizing any nodes) contains an 
                  item other than an atomic item of type <code nobreak="false">xs:string</code>, <code nobreak="false">xs:anyURI</code>, or
                     <code nobreak="false">xs:untypedAtomic</code> then a type error is raised <xerrorref spec="XP40" class="TY" code="0004"/>. </p></item></ulist><p>Each of these absolute URI references is then processed as follows. Any fragment
            identifier that is present in the URI reference is removed, and the resulting absolute
            URI is cast to a string and then passed to the <xfunction>doc</xfunction> function
            defined in <bibref ref="xpath-functions-40"/>. This returns a document node. If an error
            occurs during evaluation of the <xfunction>doc</xfunction> function, the processor
               <rfc2119>may</rfc2119> either raise this error in the normal way, or
               <rfc2119>may</rfc2119> recover by ignoring the failure, in which case the failing URI
            will not contribute any nodes to the result of the <function>document</function>
            function.</p><p>If the URI reference contained no fragment identifier, then this document node is
            included in the sequence of nodes returned by the <function>document</function>
            function.</p><p>If the URI reference contained a fragment identifier, then the fragment identifier is
            interpreted according to the rules for the media type of the resource representation
            identified by the URI, and is used to select zero or more nodes that are
            descendant-or-self nodes of the returned document node. As described in <specref ref="initiating"/>, the media type is available as part of the evaluation context for
            a transformation.</p><p>The sequence of nodes returned by the function is in document order, with no duplicates.
            This order has no necessary relationship to the order in which URIs were supplied in the
               <code nobreak="false">$uri-sequence</code> argument.</p></def></gitem><gitem><label>Error Conditions</label><def><p>
            <error spec="XT" type="dynamic" class="DE" code="1160"><p>When a URI reference <error.extra>supplied to the <function>document</function>
                     function</error.extra> contains a fragment identifier, it is a <termref def="dt-dynamic-error"/> if the media type is not one that is recognized by the
                  processor, or if the fragment identifier does not conform to the rules for
                  fragment identifiers for that media type, or if the fragment identifier selects
                  something other than a sequence of nodes (for example, if it selects a range of
                  characters within a text node). </p></error>
         </p><p>A processor <rfc2119>may</rfc2119> provide an option which, if
            selected, causes the processor instead of raising this error, to ignore the fragment
            identifier and return the document node.</p><p>The set of media types recognized by a processor is <termref def="dt-implementation-defined">implementation-defined</termref>.</p><imp-def-feature>The set of media types recognized by the processor, for the purpose of
            interpreting fragment identifiers in URI references passed to the
               <function>document</function> function, is implementation-defined.</imp-def-feature><p>
            
            <error spec="XT" type="dynamic" class="DE" code="1162"><p>When a URI reference <error.extra>supplied to the <function>document</function>
                     function</error.extra> is a relative reference, it is a <termref def="dt-dynamic-error">dynamic error</termref> if no base URI is available to
                  resolve the relative reference. This can arise for example when the URI is
                  contained in a node that has no base URI (for example a parentless text node), or
                  when the second argument to the function is a node that has no base URI, or when
                  the base URI from the static context is undefined. </p></error>
         </p></def></gitem><gitem><label>Notes</label><def><note><p>One effect of these rules is that in an interpreted environment 
            where the source code of the stylesheet is available and its base URI is known, then unless
            XML entities or <code nobreak="false">xml:base</code> are used, the expression <code nobreak="false">document("")</code> refers 
            to the document node of the containing stylesheet module (the definitive rules are in <bibref ref="RFC3986"/>). 
            The XML resource containing the stylesheet module is then processed exactly as if it were any 
            other XML document, for example there is no special recognition of <elcode>xsl:text</elcode> elements, 
            and no special treatment of comments and processing instructions.</p><p>The XPath rules for function calling ensure that it is a type error if the supplied
            value of the second argument is anything other than a single node. If <termref def="dt-xpath-compat-mode">XPath 1.0 compatibility mode</termref> is enabled, then a
            sequence of nodes may be supplied, and the first node in the sequence will be used.</p></note></def></gitem></glist></div2><div2 id="key"><head>Keys</head><p>Keys provide a way to work with documents that contain an implicit cross-reference
               structure. They make it easier to locate the nodes within a document that have a
               given value for a given attribute or child element, and they provide a hint to the
               implementation that certain access paths in the document need to be efficient.</p><div3 id="xsl-key"><head>The <elcode>xsl:key</elcode> Declaration</head><e:element-syntax xmlns:e="http://www.w3.org/1999/XSL/Spec/ElementSyntax" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" name="key">
      <e:in-category name="declaration"/>
      <e:attribute name="name" required="yes">
         <e:data-type name="eqname"/>
      </e:attribute>
      <e:attribute name="match" required="yes">
         <e:data-type name="pattern"/>
      </e:attribute>
      <e:attribute name="use">
         <e:data-type name="expression"/>
      </e:attribute>
      <e:attribute name="composite" default="'no'">
         <e:data-type name="boolean"/>
      </e:attribute>
      <e:attribute name="collation" required="no">
         <e:data-type name="uri"/>
      </e:attribute>
      <e:model name="sequence-constructor"/>
      <e:allowed-parents>
         <e:parent name="package"/>
         <e:parent name="stylesheet"/>
         <e:parent name="transform"/>
      </e:allowed-parents>
   </e:element-syntax><p>The <elcode>xsl:key</elcode>
                  <termref def="dt-declaration">declaration</termref> is used to declare <termref def="dt-key">keys</termref>. 
                  The <code nobreak="false">name</code> attribute specifies the name
                  of the key. The value of the <code nobreak="false">name</code> attribute is 
                  an <termref def="dt-eqname">EQName</termref>, which is expanded as
                  described in <specref ref="qname"/>. The <code nobreak="false">match</code> attribute 
                  is a <nt xmlns:xlink="http://www.w3.org/1999/xlink" def="doc-xslt40-Pattern" xlink:type="simple">Pattern</nt>; an <elcode>xsl:key</elcode> element applies to
                  all nodes that match the pattern specified in the <code nobreak="false">match</code>
                  attribute.</p><p>
                  <termdef id="dt-key" term="key">A <term>key</term> is defined as a set of
                        <elcode>xsl:key</elcode> declarations in the same
                           <termref def="dt-package">package</termref> that share the same
                     name.</termdef>
               </p><p>The key name is scoped to the containing <termref def="dt-package">package</termref>, 
                  and is available for use in calls to the
                     <function>key</function> function within that package.</p><p>The value of the key may be specified either using the <code nobreak="false">use</code> attribute
                  or by means of the contained <termref def="dt-sequence-constructor">sequence
                     constructor</termref>.</p><p>
                  <error spec="XT" type="static" class="SE" code="1205"><p>It is a <termref def="dt-static-error">static error</termref> if an
                           <elcode>xsl:key</elcode> declaration has a <code nobreak="false">use</code> attribute and
                        has non-empty content, or if it has empty content and no <code nobreak="false">use</code>
                        attribute.</p></error>
               </p><p>If the <code nobreak="false">use</code> attribute is present, its value is an 
                  <termref def="dt-expression">expression</termref> specifying the values of the key. The
                  expression will be evaluated with a <termref def="dt-singleton-focus">singleton focus</termref> 
                  based on the node that matches the pattern. The result of evaluating the expression is
                     <termref def="dt-atomization">atomized</termref>. </p><p>Similarly, if a <termref def="dt-sequence-constructor">sequence
                     constructor</termref> is present, it is used to determine the values of the
                  key. The sequence constructor will be evaluated with the node that matches the
                  pattern as the context node. The result of evaluating the sequence constructor is
                     <termref def="dt-atomization">atomized</termref>.</p><p>
                  <termdef id="dt-key-specifier" term="key specifier">The expression in the
                        <code nobreak="false">use</code> attribute and the <termref def="dt-sequence-constructor">sequence constructor</termref> 
                     within an <elcode>xsl:key</elcode>
                     declaration are referred to collectively as the <term>key specifier</term>. The
                     key specifier determines the values that may be used to find a node using this
                        <termref def="dt-key">key</termref>.</termdef>
               </p><p>When evaluation of the <termref def="dt-key-specifier">key
                     specifier</termref> results in a sequence (after atomization) containing more
                  than one atomic item, the effect depends on the value of the
                     <code nobreak="false">composite</code> attribute:</p><ulist><item><p>When the attribute is absent or has the value <code nobreak="false">no</code>, each atomic
                        item in the sequence acts as an individual key. For example, if
                           <code nobreak="false">match="book" use="author" composite="no"</code> is specified, then
                        a <code nobreak="false">book</code> element may be located using the value of any
                           <code nobreak="false">author</code> element.</p></item><item><p>When the attribute is present and has the value <code nobreak="false">yes</code>, the
                        sequence of atomic items is treated as a composite key that must be matched
                        in its entirety. For example, if <code nobreak="false">match="book" use="author"
                           composite="yes"</code> is specified, then a <code nobreak="false">book</code> element may
                        be located using the value of all its <code nobreak="false">author</code> elements, supplied
                        in the correct order.</p></item></ulist><p>If there are several <elcode>xsl:key</elcode> declarations in
                  the same package with the same key name, then
                  they must all have the same <termref def="dt-effective-value"/> for their <code nobreak="false">composite</code>
                  attribute. The <termref def="dt-effective-value"/> is the actual value of the attribute if present, or
                  <code nobreak="false">"no"</code> if the attribute is absent.</p><note><p>There is no requirement that all the values of a key should have the same
                     type.</p></note><p>The presence of an <elcode>xsl:key</elcode> declaration makes it easy to find a
                  node that matches the <code nobreak="false">match</code> pattern if  the values of the <termref def="dt-key-specifier">key
                     specifier</termref> (when applied to that node) are known. It also provides a
                  hint to the implementation that access to the nodes by means of these values needs
                  to be efficient (many implementations are likely to construct an index or hash
                  table to achieve this). </p><note><p>An <elcode>xsl:key</elcode> declaration is not bound to a specific source
                     document. The source document to which it applies is determined only when the
                        <function>key</function> function is used to locate nodes using the key.
                     Keys can be used to locate nodes within any source document (including
                     temporary trees), but each use of the <function>key</function> function
                     searches one document only.</p><p>Keys can only be used to search within a tree 
                     that is rooted at a document node.</p></note><p>The optional <code nobreak="false">collation</code> attribute is used only when deciding whether
                  two strings are equal for the purposes of key matching. Specifically, two key
                  values <code nobreak="false">$a</code> and <code nobreak="false">$b</code> are considered equal if the result of
                  the function call <code nobreak="false">deep-equal($a, $b,
                        $collation)</code> returns <code nobreak="false">true</code>. The effective collation for an
                     <elcode>xsl:key</elcode> declaration is the collation specified in its
                     <code nobreak="false">collation</code> attribute if present, resolved against the base URI of
                  the <elcode>xsl:key</elcode> element, or the 
                  <termref def="dt-default-collation">default collation</termref> that is in scope for the <elcode>xsl:key</elcode>
                  declaration otherwise; the effective collation must be the same for all the
                     <elcode>xsl:key</elcode> declarations making up a <termref def="dt-key">key</termref>.</p><p>
                  <error spec="XT" type="static" class="SE" code="1210"><p>It is a <termref def="dt-static-error">static error</termref> if the
                           <elcode>xsl:key</elcode> declaration has a <code nobreak="false">collation</code>
                        attribute whose value (after resolving against the base URI) is not a URI
                        recognized by the implementation as referring to a collation.</p></error>
               </p><p>
                  <error spec="XT" type="static" class="SE" code="1220"><p>It is a <termref def="dt-static-error">static error</termref> if there are
                        several <elcode>xsl:key</elcode> declarations in the same <termref def="dt-package">package</termref> with the
                        same key name and different effective collations. Two collations are the
                        same if their URIs are equal under the rules for comparing
                           <code nobreak="false">xs:anyURI</code> values, or if the implementation can determine
                        that they are different URIs referring to the same collation.</p></error>
               </p><p>
                  <error spec="XT" type="static" class="SE" code="1222"><p>It is a <termref def="dt-static-error">static error</termref> if there are
                        several <elcode>xsl:key</elcode> declarations in a <termref def="dt-package">package</termref> 
                        with the same key name and
                        different <termref def="dt-effective-value">effective values</termref> 
                        for the <code nobreak="false">composite</code> attribute.</p></error>
               </p><p>It is possible to have:</p><ulist><item><p>multiple <elcode>xsl:key</elcode> declarations with the same name;</p></item><item><p>a node that matches the <code nobreak="false">match</code> patterns of several different
                           <elcode>xsl:key</elcode> declarations, whether these have the same key
                        name or different key names;</p></item><item><p>a node that returns more than one value from its <termref def="dt-key-specifier">key specifier</termref>
                        (which can be treated either as separate
                           individual key values, or as a single composite key value);</p></item><item><p>a key value that identifies more than one node (the key values for different
                        nodes do not need to be unique).</p></item></ulist><p>An <elcode>xsl:key</elcode> declaration with higher 
                  <termref def="dt-import-precedence">import precedence</termref> does not override
                  another of lower import precedence; all the <elcode>xsl:key</elcode> declarations
                  in the stylesheet are effective regardless of their import precedence.</p></div3><div3 id="func-key"><head>fn:key</head><changes><change issue="1619" PR="1622" date="2024-11-29">The rules for equality comparison have changed to bring keys into line with maps.</change></changes><glist><gitem><label>Summary</label><def><p>Returns the nodes within a document or subtree that match a supplied key value.</p></def></gitem><gitem><label>Signature</label><def><example role="signature"><proto isOp="no" prefix="fn" name="key" return-type="node()*" returnEmptyOk="no" returnSeq="no" returnVaries="no" isSchema="no" isDatatype="no" isSpecial="no"><arg name="key-name" type="(xs:string | xs:QName)"/><arg name="key-value" type="xs:anyAtomicType*"/><arg name="top" type="node()" default="/"/></proto></example></def></gitem><gitem><label>Properties</label><def><p>The two-argument form of this function is <xtermref spec="FO40" ref="dt-deterministic">deterministic</xtermref>, <xtermref spec="FO40" ref="dt-focus-dependent">focus-dependent</xtermref>,  and <xtermref spec="FO40" ref="dt-context-dependent">context-dependent</xtermref>. </p><p>The three-argument form of this function is <xtermref spec="FO40" ref="dt-deterministic">deterministic</xtermref>, <xtermref spec="FO40" ref="dt-focus-independent">focus-independent</xtermref>,  and <xtermref spec="FO40" ref="dt-context-dependent">context-dependent</xtermref>. </p></def></gitem><gitem><label>Rules</label><def><p>The <function>key</function> function returns the nodes within a document or subtree that
            have a specified key value.</p><p>The <code nobreak="false">$key-name</code> argument specifies the name of the <termref def="dt-key">key</termref>. 
            The value of the argument <rfc2119>must</rfc2119> be <phrase diff="add" at="2022-01-01">either an <code nobreak="false">xs:QName</code>, or </phrase>
            a string containing an <termref def="dt-eqname"/>. If it is
            a <termref def="dt-lexical-qname">lexical QName</termref>, then it is expanded as
            described in <specref ref="qname"/> (no prefix means no namespace).</p><p>The <code nobreak="false">$key-value</code> argument to the <function>key</function> function is
            considered as a sequence. The effect depends on the value of
               the <code nobreak="false">composite</code> attribute of the corresponding <code nobreak="false">xsl:key</code>
               declaration.</p><ulist><item><p>If <code nobreak="false">composite</code> is <code nobreak="false">no</code> or
                     absent, the set of requested key values is formed by atomizing the
                  supplied value of the argument, using the standard <termref def="dt-coercion-rules">coercion rules</termref>. Each of
                  the resulting atomic items is considered as a requested key value. The result of
                  the function is a sequence of nodes, in document order and with duplicates
                  removed, comprising those nodes in the selected subtree (see below) that are
                  matched by an <elcode>xsl:key</elcode> declaration whose name is the same as the
                  supplied key name, where the result of evaluating the 
                  <termref def="dt-key-specifier">key specifier</termref> contains a value that is equal
                  to one of these requested key values: the rules for comparing two items
                  are given below. No error is reported if two values are encountered that
                  are not comparable; they are regarded for the purposes of this function as being
                  not equal. </p><p>If the second argument is an empty sequence, the result of the function will be an
                  empty sequence.</p></item><item><p>If <code nobreak="false">composite</code> is <code nobreak="false">yes</code>, the requested key
                  value is the sequence formed by atomizing the supplied value of the argument,
                  using the standard <termref def="dt-coercion-rules">coercion rules</termref>. 
                  The result of the function is a sequence of nodes, in document
                  order and with duplicates removed, comprising those nodes in the selected subtree
                  (see below) that are matched by an <elcode>xsl:key</elcode> declaration whose name
                  is the same as the supplied key name, where the result of evaluating the <termref def="dt-key-specifier">key specifier</termref> is deep-equal to the requested
                  key value, under the rules appropriate to the <xfunction>deep-equal</xfunction>
                  function applied to the two values in question: the detailed comparison rules are 
                  defined below.</p><p>If the second argument is an empty sequence, the result of the
                  function will be the set of nodes having an empty sequence as the value of the key
                  specifier.</p></item></ulist><p>Two atomic items <var>K1</var> and <var>K2</var> are deemed equal if they satisfy 
            one of the following rules:</p><olist><item><p>If both <var>K1</var> and <var>K2</var> are of type 
               <code nobreak="false">xs:string</code>, <code nobreak="false">xs:untypedAtomic</code>,
            or <code nobreak="false">xs:anyURI</code>, then they are deemed equal if 
               <code nobreak="false">compare(<var>K1</var>, <var>K2</var>, $collation)</code>
            returns zero, where <code nobreak="false">$collation</code> is the collation of the key definition.</p></item><item><p>Otherwise, they are deemed equal if <code nobreak="false">atomic-equal(<var>K1</var>, <var>K2</var>)</code>
            returns true.</p></item></olist><p>When <code nobreak="false">composite="yes"</code>, then two sequences of atomic
            items <var>S1</var> and <var>S2</var> are deemed equal if <code nobreak="false">deep-equal(<var>S1</var>,
            <var>S2</var>, { 'items-equal': $F }))</code> returns true, where <code nobreak="false">$F</code> is the function
            just described for comparing atomic items.</p><note><p>The rules for comparing items have changed in this version of the specification,
            in the interests of bringing keys into line with maps. The main differences are:</p><ulist><item><p>Numeric equality is transitive. In particular, when comparing an <code nobreak="false">xs:double</code>
               value to an <code nobreak="false">xs:decimal</code>, they must now be exactly numerically equal; the <code nobreak="false">xs:decimal</code>
               was previously converted to the nearest <code nobreak="false">xs:double</code>.</p></item><item><p>The implicit timezone is no longer used when comparing date/time values with a timezone
               to values without one. To be equal, the values must either both have a timezone, or both be without one.</p></item></ulist></note><p>The third argument is used to identify the selected subtree. If the argument is present,
            the selected subtree is the set of nodes that have <var>$top</var> as an
            ancestor-or-self node. If the argument is omitted, the selected subtree is the document
            containing the context node. This means that the third argument effectively defaults to
               <code nobreak="false">/</code>.</p><p>The result of the <function>key</function> function can be described more specifically
            as follows. The result is a sequence containing every node <var>$N</var> that satisfies
            the following conditions:</p><ulist><item><p>
                  <code nobreak="false">$N/ancestor-or-self::node() intersect $top</code> is non-empty. (If the
                  third argument is omitted, <code nobreak="false">$top</code> defaults to <code nobreak="false">/</code>)</p></item><item><p>
                  <var>$N</var> matches the pattern specified in the <code nobreak="false">match</code> attribute of
                  an <elcode>xsl:key</elcode> declaration whose <code nobreak="false">name</code> attribute matches
                  the name specified in the <code nobreak="false">$key-name</code> argument.</p></item><item><p>When <code nobreak="false">composite="no"</code>,  and the
                     <termref def="dt-key-specifier">key specifier</termref> of that
                     <elcode>xsl:key</elcode> declaration is evaluated with a <termref def="dt-singleton-focus">singleton focus</termref> based on <var>$N</var>, the
                     <termref def="dt-atomization">atomized</termref> value of the resulting
                  sequence includes a value that compares equal to at least one item in the atomized
                  value of the sequence supplied as <code nobreak="false">$key-value</code>, using the equality
                  comparison defined above.</p><p>When <code nobreak="false">composite="yes"</code>,  and the
                     <termref def="dt-key-specifier">key specifier</termref> of that
                     <elcode>xsl:key</elcode> declaration is evaluated with a <termref def="dt-singleton-focus">singleton focus</termref> based on <var>$N</var>, the
                     <termref def="dt-atomization">atomized</termref> value of the resulting
                  sequence compares equal to the atomized value of the sequence supplied as
                     <code nobreak="false">$key-value</code>, under the rules of the
                     <xfunction>deep-equal</xfunction> function as described above.</p></item></ulist><p>The sequence returned by the <function>key</function> function will be in document
            order, with duplicates (that is, nodes having the same identity) removed. </p><p>Different rules apply when <termref def="dt-xslt-10-behavior">XSLT 1.0 compatible behavior</termref> is enabled.</p><p>A key (that is, a set of <elcode>xsl:key</elcode>
            declarations sharing the same key name) is processed in backwards compatible mode if (a)
            at least one of the <elcode>xsl:key</elcode> elements in the definition of the key enables backwards
            compatible behavior, and (b) the effective value of the <code nobreak="false">composite</code> attribute
            is <code nobreak="false">no</code>.</p><p>When a key is processed in backwards compatible mode,
            then:</p><ulist><item><p>The result of evaluating the key specifier in any <elcode>xsl:key</elcode>
               declaration having this key name is converted after atomization to a sequence of
               strings, by applying a cast to each item in the sequence.</p></item><item><p>When the first argument to the <function>key</function> function specifies this key
               name, then the value of the second argument is converted after atomization to a
               sequence of strings, by applying a cast to each item in the sequence. The values are
               then compared as strings.</p></item></ulist></def></gitem><gitem><label>Error Conditions</label><def><p>
            <error spec="XT" type="dynamic" class="DE" code="1260"><p>It is a <termref def="dt-dynamic-error"> dynamic error</termref> if the value
                     of <code nobreak="false">$key-name</code> is not a valid QName, or if there is no namespace
                  declaration in scope for the prefix of the QName, or if the name obtained by
                  expanding the QName is not the same as the expanded name of any
                     <elcode>xsl:key</elcode> declaration in the containing <termref def="dt-package">package</termref>. 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 raise this as a <termref def="dt-static-error">static
                  error</termref>.</p></error>
         </p><p>
            <error spec="XT" type="dynamic" class="DE" code="1270"><p>It is a <termref def="dt-dynamic-error">dynamic
                        error</termref> to call the <function>key</function> function with
                  two arguments if there is no <termref def="dt-context-node">context
                  node</termref>, or if the root of the tree containing the context node is not a
                  document node; or to call the function with three arguments if the root of the
                  tree containing the node supplied in the third argument is not a document
                  node.</p></error>
         </p></def></gitem><gitem><label>Notes</label><def><note><p>Untyped atomic items are converted to strings, not to the type of the other operand.
            This means, for example, that if the expression in the <code nobreak="false">use</code> attribute
            returns a date, supplying an untyped atomic item in the call to the
               <function>key</function> function will return an empty sequence.</p></note></def></gitem><gitem><label>Examples</label><def role="example"><table role="medium" border="1" cellpadding="5" width="100%"><tbody><tr><td colspan="2" rowspan="1" align="left" valign="top"><example><head>Using a Key to Follow Cross-References</head><p>Given a declaration</p><eg xml:space="preserve">&lt;xsl:key name="idkey" match="div" use="@id"/&gt;</eg><p>an expression <code nobreak="false">key("idkey",@ref)</code> will return the same nodes as
                     <code nobreak="false">id(@ref)</code>, assuming that the only ID attribute declared in the XML
                  source document is:</p><eg xml:space="preserve">&lt;!ATTLIST div id ID #IMPLIED&gt;</eg><p>and that the <code nobreak="false">ref</code> attribute of the context node contains no
                  whitespace.</p></example></td></tr><tr><td colspan="2" rowspan="1" align="left" valign="top"><example><head>Using a Key to Generate Hyperlinks</head><p>Suppose a document describing a function library uses a <code nobreak="false">prototype</code>
                  element to define functions</p><eg xml:space="preserve">&lt;prototype name="sqrt" return-type="xs:double"&gt;
  &lt;arg type="xs:double"/&gt;
&lt;/prototype&gt;</eg><p>and a <code nobreak="false">function</code> element to refer to function names</p><eg xml:space="preserve">&lt;function&gt;sqrt&lt;/function&gt;</eg><p>Then the stylesheet could generate hyperlinks between the references and
                  definitions as follows:</p><eg xml:space="preserve">&lt;xsl:key name="func" match="prototype" use="@name"/&gt;

&lt;xsl:template match="function"&gt;
&lt;b&gt;
  &lt;a href="#{generate-id(key('func',.))}"&gt;
    &lt;xsl:apply-templates/&gt;
  &lt;/a&gt;
&lt;/b&gt;
&lt;/xsl:template&gt;

&lt;xsl:template match="prototype"&gt;
  &lt;p&gt;
    &lt;a name="{generate-id()}"&gt;
      &lt;b&gt;Function: &lt;/b&gt;
      ...
    &lt;/a&gt;
  &lt;/p&gt;
  &lt;/xsl:template&gt;</eg></example></td></tr><tr><td colspan="2" rowspan="1" align="left" valign="top"><p>When called with two arguments, the <function>key</function> function always returns
               nodes that are in the same document as the context node. To retrieve a node from any
               other document, it is necessary either to change the context node, or to supply a
               third argument.</p></td></tr><tr><td colspan="2" rowspan="1" align="left" valign="top"><example><head>Using Keys to Reference other Documents</head><p>For example, suppose a document contains bibliographic references in the form
                     <code nobreak="false">&lt;bibref&gt;XSLT&lt;/bibref&gt;</code>, and there is a separate XML
                  document <code nobreak="false">bib.xml</code> containing a bibliographic database with entries in
                  the form:</p><eg xml:space="preserve">&lt;entry name="XSLT"&gt;...&lt;/entry&gt;</eg><p>Then the stylesheet could use the following to transform the <code nobreak="false">bibref</code>
                  elements:</p><eg xml:space="preserve">&lt;xsl:key name="bib" match="entry" use="@name"/&gt;

&lt;xsl:template match="bibref"&gt;
  &lt;xsl:variable name="name" select="."/&gt;
  &lt;xsl:apply-templates select="document('bib.xml')/key('bib', $name)"/&gt;
&lt;/xsl:template&gt;</eg><note><p>This relies on the ability in XPath 2.0 to have a function call on the
                     right-hand side of the <code nobreak="false">/</code> operator in a path expression.</p></note><p>The following code would also work:</p><eg xml:space="preserve">&lt;xsl:key name="bib" match="entry" use="@name"/&gt;

&lt;xsl:template match="bibref"&gt;
  &lt;xsl:apply-templates select="key('bib', ., document('bib.xml'))"/&gt;
&lt;/xsl:template&gt;</eg></example></td></tr><tr><td colspan="2" rowspan="1" align="left" valign="top"><example><head>Using a Composite Key</head><p>This example uses a composite key consisting of first name and last name to locate
                  employees in an employee file.</p><p>The key can be defined like this:</p><eg xml:space="preserve">
&lt;xsl:key name="emp-name-key" 
         match="employee" 
         use="name/first, name/last" 
         composite="yes"/&gt;                     
         </eg><p>A particular employee can then be located using the function call:</p><eg xml:space="preserve">key('emp-name-key', ('Tim', 'Berners-Lee'), doc('employees.xml'))</eg></example></td></tr></tbody></table></def></gitem></glist></div3><div3 id="func-map-for-key"><head>fn:map-for-key</head><changes><change issue="1619" PR="1622" date="2024-11-29">New in 4.0.</change></changes><glist><gitem><label>Summary</label><def><p>Delivers the content of a key, for a specific document or subtree, as a map.</p></def></gitem><gitem><label>Signature</label><def><example role="signature"><proto isOp="no" prefix="fn" name="map-for-key" return-type="map(xs:anyAtomicType, node()*)" returnEmptyOk="no" returnSeq="no" returnVaries="no" isSchema="no" isDatatype="no" isSpecial="no"><arg name="key-name" type="(xs:string | xs:QName)"/><arg name="top" type="(document-node() | element())" default="/"/></proto></example></def></gitem><gitem><label>Properties</label><def><p>This function is <xtermref spec="FO40" ref="dt-deterministic">deterministic</xtermref>,  and <xtermref spec="FO40" ref="dt-focus-independent">focus-independent</xtermref>. </p></def></gitem><gitem><label>Rules</label><def><p>The effect of the function is to return a map <code nobreak="false">$M</code> such that
         <code nobreak="false">map:get($M, $key)</code> returns the same result as <code nobreak="false">key($key-name, $key, $top)</code>.</p><p>The function is defined only for maps that satisfy the following constraints:</p><olist><item><p>The key's collation must be the Unicode Codepoint Collation.</p></item><item><p>The key must not specify <code nobreak="false">composite=yes</code>.</p></item></olist><p>The <code nobreak="false">$key-name</code> argument specifies the name of the <termref def="dt-key">key</termref>. 
            The value of the argument <rfc2119>must</rfc2119> be either an <code nobreak="false">xs:QName</code>, or 
            a string containing an <termref def="dt-eqname"/>. If it is
            a <termref def="dt-lexical-qname">lexical QName</termref>, then it is expanded as
            described in <specref ref="qname"/> (no prefix means no namespace).</p><p>The <code nobreak="false">$top</code> argument is used to identify the selected subtree. If the argument is present,
            the selected subtree is the set of nodes that have <code nobreak="false">$top</code> as an
            ancestor-or-self node. If the argument is omitted, the selected subtree is the document
            containing the context node. This means that the third argument effectively defaults to
               <code nobreak="false">/</code>.</p><p>The returned map contains one entry (<var>K</var>, <var>V</var>) for every atomic item <var>K</var>
         where the result of <code nobreak="false">key($key-name, <var>K</var>, $top)</code> is not empty, with <var>V</var>
         set to the result of <code nobreak="false">key($key-name, <var>K</var>, $top)</code>.</p></def></gitem><gitem><label>Error Conditions</label><def><p>It is a <termref def="dt-dynamic-error"> dynamic error</termref> if the value
                     <error.extra>of the first argument to the <function>map-for-key</function>
                     function</error.extra> is not a valid QName, or if there is no namespace
                  declaration in scope for the prefix of the QName, or if the name obtained by
                  expanding the QName is not the same as the expanded name of any
                     <elcode>xsl:key</elcode> declaration in the containing <termref def="dt-package">package</termref>. 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 raise this as a <termref def="dt-static-error">static
                  error</termref> <errorref class="DE" code="1260"/>.          
         </p><p>
            <error spec="XT" type="dynamic" class="DE" code="1262"><p>It is a <termref def="dt-dynamic-error">dynamic
                        error</termref> if the key identified in a call to the function <function>map-for-key</function>
               is unsuitable because it uses a collation other than the Unicode Codepoint Collation, or because
               it is defined with <code nobreak="false">composite=yes</code>.</p></error>
         </p><p>
            It is a <termref def="dt-dynamic-error">dynamic
                        error</termref> to call the <function>key</function> function with
                  two arguments if there is no <termref def="dt-context-node">context
                  node</termref>, or if the root of the tree containing the context node is not a
                  document node; or to call the function with three arguments if the root of the
                  tree containing the node supplied in the third argument is not a document
                  node <errorref class="DE" code="1270"/>. 
         </p></def></gitem><gitem><label>Notes</label><def><note><p>The function has two main uses:</p><ulist><item><p>It enables the key values present in a key to be enumerated.</p></item><item><p>It enables the keys for multiple documents to be combined into a single map, for example
            by using <xfunction>map:merge</xfunction>.</p></item></ulist></note></def></gitem><gitem><label>Examples</label><def role="example"><table role="medium" border="1" cellpadding="5" width="100%"><tbody><tr><td colspan="2" rowspan="1" align="left" valign="top"><example><head>Finding keys that are present in one document but absent in another</head><p>This example uses a key identifying employees in an employee file by their social security
                     number.</p><p>The key might be defined like this:</p><eg xml:space="preserve">
   &lt;xsl:key name="emp-name-key" 
         match="employee" 
         use="SSN"/&gt;                     
            </eg><p>Given two documents <code nobreak="false">$doc1</code> and <code nobreak="false">$doc2</code>, the following expression
                     returns a map representing the employees who are present in the first document
                     but not the second:</p><eg xml:space="preserve">map-for-key('emp-name-key', $doc1)
   =&gt; map:remove(map-for-key('emp-name-key', $doc2) =&gt; map:keys())</eg></example></td></tr></tbody></table></def></gitem></glist></div3></div2><div2 id="func-copy-of"><head>fn:copy-of</head><glist><gitem><label>Summary</label><def><p>Returns a deep copy of the sequence supplied as the <code nobreak="false">$input</code> argument, or of the
            context item if the argument is absent.</p></def></gitem><gitem><label>Signature</label><def><example role="signature"><proto isOp="no" prefix="fn" name="copy-of" return-type="item()*" returnEmptyOk="no" returnSeq="no" returnVaries="no" isSchema="no" isDatatype="no" isSpecial="no"><arg name="input" type="item()*" default="."/></proto></example></def></gitem><gitem><label>Properties</label><def><p>The zero-argument form of this function is <xtermref spec="FO40" ref="dt-nondeterministic">nondeterministic</xtermref>, <xtermref spec="FO40" ref="dt-focus-dependent">focus-dependent</xtermref>,  and <xtermref spec="FO40" ref="dt-context-independent">context-independent</xtermref>. </p><p>The one-argument form of this function is <xtermref spec="FO40" ref="dt-nondeterministic">nondeterministic</xtermref>, <xtermref spec="FO40" ref="dt-focus-independent">focus-independent</xtermref>,  and <xtermref spec="FO40" ref="dt-context-independent">context-independent</xtermref>. </p></def></gitem><gitem><label>Rules</label><def><p>The zero-argument form of this function is defined so that <code nobreak="false">copy-of()</code>
         returns the value of <code nobreak="false">internal:copy-item(.)</code>, where <code nobreak="false">internal:copy-item</code> (which
            exists only for the purpose of this exposition) is defined below. Informally, <code nobreak="false">copy-of()</code>
         copies the context item.</p><p>The single argument form of this function is defined in terms of the
         <code nobreak="false">internal:copy-item</code> as follows: <code nobreak="false">copy-of($input)</code> is equivalent
            to <code nobreak="false">$input ! internal:copy-item(.)</code>. Informally, <code nobreak="false">copy-of($input)</code> copies each item in the
         input sequence in turn.</p><p>The <code nobreak="false">internal:copy-item</code> function is defined as follows:</p><eg xml:space="preserve">
&lt;xsl:function name="internal:copy-item" as="item()" 
              new-each-time="maybe"&gt;
  &lt;xsl:param name="input" as="item()"/&gt;
  &lt;xsl:copy-of select="$input" 
               copy-namespaces="yes"
               copy-accumulators="yes"
               validation="preserve"/&gt;
&lt;/xsl:function&gt;</eg><p>The streamability analysis, however, is different: see <xspecref spec="SG40" ref="classifying-built-in-functions"/>.</p><p>The use of <code nobreak="false">new-each-time="maybe"</code> in the above definition means that 
            if the <code nobreak="false">internal:copy-item</code> function is called more than once with the same node as argument 
            (whether or not these calls are part of the same call on <code nobreak="false">copy-of</code>), then it is <termref def="dt-implementation-dependent">implementation-dependent</termref> whether each
            call returns the same node, or whether multiple calls return different nodes.
           Returning the original node, however, is not allowed, except as an optimization when the processor
         can determine that this is equivalent.</p><note><p>One case where such optimization might be possible is when the copy is immediately atomized.</p></note></def></gitem><gitem><label>Notes</label><def><note><p>The <function>copy-of</function> function is available for use (and is primarily
            intended for use) when a source document is processed using streaming. It can also be
            used when not streaming. The effect, 
            when applied to element and document nodes,
            is to take a copy of the subtree rooted at the
            current node, and to make this available as a normal tree: one that can be processed without
            any of the restrictions that apply while streaming, for example only being able to
            process children once. The copy, of course, does not include siblings or ancestors of
            the context node, so any attempt to navigate to siblings or ancestors will result in an
            empty sequence being returned.</p><p>All nodes in the result sequence will be parentless.</p><p>If atomic items or functions (including maps and arrays) are present in the input sequence,
         they will be included unchanged at the corresponding position of the result sequence.</p><p>Accumulator values are taken from the copied
            document as described in <specref ref="copying-accumulators"/>.</p></note></def></gitem><gitem><label>Examples</label><def role="example"><table role="medium" border="1" cellpadding="5" width="100%"><tbody><tr><td colspan="2" rowspan="1" align="left" valign="top"><p>Using <code nobreak="false">copy-of()</code> while streaming:</p></td></tr><tr><td colspan="2" rowspan="1" align="left" valign="top"><p>This example copies from the source document all employees who work in marketing and
               are based in Dubai. Because there are two accesses using the child axis, it is not
               possible to do this without buffering each employee in memory, which can be achieved
               using the <function>copy-of</function> function.</p></td></tr><tr><td colspan="2" rowspan="1" align="left" valign="top"><eg xml:space="preserve">&lt;xsl:source-document streamable="yes" href="employees.xml"&gt;
  &lt;xsl:sequence select="copy-of(employees/employee)
                          [department='Marketing' and location='Dubai']"/&gt;
&lt;/xsl:source-document&gt;</eg></td></tr></tbody></table></def></gitem></glist></div2><div2 id="func-snapshot"><head>fn:snapshot</head><glist><gitem><label>Summary</label><def><p>Returns a copy of a sequence, retaining copies of the ancestors and descendants of any node in the input sequence, together with their
            attributes and namespaces.</p></def></gitem><gitem><label>Signature</label><def><example role="signature"><proto isOp="no" prefix="fn" name="snapshot" return-type="item()*" returnEmptyOk="no" returnSeq="no" returnVaries="no" isSchema="no" isDatatype="no" isSpecial="no"><arg name="input" type="item()*" default="."/></proto></example></def></gitem><gitem><label>Properties</label><def><p>The zero-argument form of this function is <xtermref spec="FO40" ref="dt-nondeterministic">nondeterministic</xtermref>, <xtermref spec="FO40" ref="dt-focus-dependent">focus-dependent</xtermref>,  and <xtermref spec="FO40" ref="dt-context-independent">context-independent</xtermref>. </p><p>The one-argument form of this function is <xtermref spec="FO40" ref="dt-nondeterministic">nondeterministic</xtermref>, <xtermref spec="FO40" ref="dt-focus-independent">focus-independent</xtermref>,  and <xtermref spec="FO40" ref="dt-context-independent">context-independent</xtermref>. </p></def></gitem><gitem><label>Rules</label><def><p>The zero-argument form of this function is defined so that <code nobreak="false">snapshot()</code>
            returns the value of <code nobreak="false">internal:snaphot-item(.)</code>, where <code nobreak="false">internal:snapshot-item</code> (which
            exists only for the purpose of this exposition) is defined below. Informally, <code nobreak="false">snapshot()</code>
            takes a snapshot of the context item.</p><p>The single argument form of this function is defined in terms of the
            <code nobreak="false">internal:snapshot-item</code> as follows: <code nobreak="false">snapshot($input)</code> is equivalent
            to <code nobreak="false">$input ! internal:snapshot-item(.)</code>. Informally, <code nobreak="false">snapshot($input)</code> takes a snapshot of each item in the
            input sequence in turn.</p><p>The <code nobreak="false">internal:snapshot-item</code> function behaves as follows:</p><ulist><item><p>If the supplied item is an atomic item or a function item (including maps
            and arrays), then it returns that item unchanged.</p></item><item><p>If the supplied item is a node, then it returns a <termref def="dt-snapshot"/>
            of that node, as defined below.</p></item></ulist><p>
            <termdef id="dt-snapshot" term="snapshot">A <term>snapshot</term> of a node <var>N</var>
               is a deep copy of <var>N</var>, as produced by the <elcode>xsl:copy-of</elcode>
               instruction with <code nobreak="false">copy-namespaces</code> set to <code nobreak="false">yes</code>,
               <code nobreak="false">copy-accumulators</code> set to <code nobreak="false">yes</code>, and
                  <code nobreak="false">validation</code> set to <code nobreak="false">preserve</code>, with the additional property
               that for every ancestor of <var>N</var>, the copy also has a corresponding ancestor
               whose name, node-kind, and base URI are the same as the corresponding ancestor of
               <var>N</var>, and that has copies of the attributes, namespaces and accumulator values of the
               corresponding ancestor of <var>N</var>. But the ancestor has a type annotation of
                  <code nobreak="false">xs:anyType</code>, has the properties <code nobreak="false">nilled</code>,
                  <code nobreak="false">is-id</code>, and <code nobreak="false">is-idref</code> set to <code nobreak="false">false</code>, and has no children
               other than the child that is a copy of <var>N</var> or one of its
               ancestors.</termdef>
         </p><p>If the function is called more than once with the same argument, it is <termref def="dt-implementation-dependent">implementation-dependent</termref> whether each
            call returns the same node, or whether multiple calls return different nodes. That is,
            the result of the expression <code nobreak="false">snapshot($X) is snapshot($X)</code> is <termref def="dt-implementation-dependent">implementation-dependent</termref>.</p><p>Except for the effect on accumulators, the <code nobreak="false">internal:snapshot-item</code> function can be expressed
            as follows:</p><eg xml:space="preserve">
    &lt;xsl:function name="internal:snapshot-item" as="item()"&gt;
        &lt;xsl:param name="input" as="item()"/&gt;
        &lt;xsl:apply-templates select="$input" mode="internal:snapshot"/&gt;
    &lt;/xsl:function&gt;
    
    &lt;!-- for atomic items and function items, return the item unchanged --&gt;
    
    &lt;xsl:template match="." mode="internal:snapshot" priority="1"&gt;
        &lt;xsl:sequence select="."/&gt;
    &lt;/xsl:template&gt;
    
    &lt;!-- for a document node, or any other root node, return a deep copy --&gt;
    
    &lt;xsl:template match="root()" mode="internal:snapshot" priority="5"&gt;
        &lt;xsl:copy-of select="."/&gt;
    &lt;/xsl:template&gt;
    
    &lt;!-- for an element, comment, text node, or processing instruction: --&gt;
    
    &lt;xsl:template match="node()" mode="internal:snapshot" 
                                 as="node()" priority="3"&gt;
        &lt;xsl:sequence select="internal:graft-to-parent(
                                ., .., function($n){$n/node()})"/&gt;
    &lt;/xsl:template&gt;
    
    &lt;!-- for an attribute: --&gt;
    
    &lt;xsl:template match="@*" mode="internal:snapshot" 
                             as="attribute()" priority="3"&gt;
        &lt;xsl:variable name="name" select="node-name(.)"/&gt;
        &lt;xsl:sequence select="internal:graft-to-parent(., .., 
                                function($n){$n/@*[node-name(.) = $name]})"/&gt;
    &lt;/xsl:template&gt;
    
    &lt;!-- for a namespace node: --&gt;
    
    &lt;xsl:template match="namespace-node()" mode="internal:snapshot" 
                  as="namespace-node()" priority="3"&gt;
        &lt;xsl:variable name="name" select="local-name(.)"/&gt;
        &lt;xsl:sequence select="internal:graft-to-parent(., .., 
                  function($n){$n/namespace-node()[local-name(.) = $name]})"/&gt;
    &lt;/xsl:template&gt;
    
    &lt;!-- make a copy C of a supplied node N, grafting it to a shallow copy of 
         C's original parent, and returning the copy C --&gt;
    
    &lt;xsl:function name="internal:graft-to-parent" as="node()"&gt;
        &lt;xsl:param name="n" as="node()"/&gt;
        &lt;xsl:param name="original-parent" as="node()?"/&gt;
        &lt;xsl:param name="down-function" as="function(node()) as node()"/&gt;
        &lt;xsl:choose&gt;
            &lt;xsl:when test="exists($original-parent)"&gt;
                &lt;xsl:variable name="p" as="node()"&gt;
                    &lt;xsl:copy select="$original-parent"&gt;
                        &lt;xsl:copy-of select="@*"/&gt;
                        &lt;xsl:copy-of select="$n"/&gt;
                    &lt;/xsl:copy&gt;
                &lt;/xsl:variable&gt;
                &lt;xsl:variable name="copied-parent" 
                     select="internal:graft-to-parent(
                        $p, $original-parent/.., function($n){$n/node()}))"/&gt;
                &lt;xsl:sequence select="$down-function($copied-parent)"/&gt;              
            &lt;/xsl:when&gt;
            &lt;xsl:otherwise&gt;
                &lt;xsl:sequence select="$n"/&gt;
            &lt;/xsl:otherwise&gt;
        &lt;/xsl:choose&gt;
    &lt;/xsl:function&gt;
    
</eg></def></gitem><gitem><label>Notes</label><def><note><p>The <function>snapshot</function> function is available for use (and is primarily
            intended for use) when a source document is processed using streaming. It can also be
            used when not streaming. The effect is to take a copy of the subtree rooted at the
            current node, along with copies of the ancestors and their attributes, and to make this
            available as a normal tree, that can be processed without any of the restrictions that
            apply while streaming, for example only being able to process children once. The copy,
            of course, does not include siblings of the context node or of its ancestors, so any
            attempt to navigate to these siblings will result in an empty sequence being
            returned.</p><p>For parentless nodes, the effect of <code nobreak="false">snapshot($x)</code> is identical to the effect
         of <code nobreak="false">copy-of($x)</code>.</p></note></def></gitem><gitem><label>Examples</label><def role="example"><table role="medium" border="1" cellpadding="5" width="100%"><tbody><tr><td colspan="2" rowspan="1" align="left" valign="top"><p>Using <code nobreak="false">snapshot()</code> while streaming:</p></td></tr><tr><td colspan="2" rowspan="1" align="left" valign="top"><p>This example copies from the source document all employees who work in marketing and
               are based in Dubai. It assumes that employees are grouped by location. Because there
               are two accesses using the child axis (referencing <code nobreak="false">department</code> and
                  <code nobreak="false">salary</code>), it is not possible to do this without buffering each
               employee in memory. The <function>snapshot</function> function is used in preference
               to the simpler <function>copy-of</function> so that access to attributes of the
               parent <code nobreak="false">location</code> element remains possible.</p></td></tr><tr><td colspan="2" rowspan="1" align="left" valign="top"><eg xml:space="preserve">&lt;xsl:source-document streamable="yes" href="employees.xml"&gt;
  &lt;xsl:for-each select="snapshot(locations/location[@name='Dubai']
                          /employee)[department='Marketing']"&gt;
    &lt;employee&gt;
      &lt;location code="{../@code}"/&gt;
      &lt;salary value="{salary}"/&gt;
    &lt;/employee&gt;
  &lt;/xsl:for-each&gt;
&lt;/xsl:source-document&gt;</eg></td></tr></tbody></table></def></gitem></glist></div2><div2 id="misc-func"><head>Miscellaneous Additional Functions</head><div3 id="func-current"><head>fn:current</head><changes><change issue="407" PR="2274" date="2026-01-06">In XSLT 4.0, the function item <code nobreak="false">current#0</code> retains the value of the current
         item within its captured context.</change></changes><glist><gitem><label>Summary</label><def><p>Returns the item that is the context item for the evaluation of the containing XPath
            expression</p></def></gitem><gitem><label>Signature</label><def><example role="signature"><proto isOp="no" prefix="fn" name="current" return-type="item()" returnEmptyOk="no" returnSeq="no" returnVaries="no" isSchema="no" isDatatype="no" isSpecial="no"/></example></def></gitem><gitem><label>Properties</label><def><p>This function is <xtermref spec="FO40" ref="dt-deterministic">deterministic</xtermref>, <xtermref spec="FO40" ref="dt-context-dependent">context-dependent</xtermref>,  and <xtermref spec="FO40" ref="dt-focus-dependent">focus-dependent</xtermref>. </p></def></gitem><gitem><label>Rules</label><def><p>The <function>current</function> function, used within an XPath <termref def="dt-expression">expression</termref>, returns the item that was the <termref def="dt-context-item">context item</termref> at the point where the expression was
            invoked from the XSLT <termref def="dt-stylesheet">stylesheet</termref>. This is
            referred to as the current item. For an outermost expression (an expression not
            occurring within another expression), the current item is always the same as the context
            item. Thus,</p><eg xml:space="preserve">&lt;xsl:value-of select="current()"/&gt;</eg><p>means the same as</p><eg xml:space="preserve">&lt;xsl:value-of select="."/&gt;</eg><p>However, within square brackets, or on the right-hand side of the <code nobreak="false">/</code>
            operator, the current item is generally different from the context item.</p><p>If the <function>current</function> function is used within a <termref def="dt-pattern">pattern</termref>, its value is the item that is
            being matched against the pattern.</p></def></gitem><gitem><label>Error Conditions</label><def><p>
            <error spec="XT" type="dynamic" class="DE" code="1360"><p>If the <function>current</function> function is evaluated within an expression
                  that is evaluated when the context item is absent, a <termref def="dt-dynamic-error">
                     dynamic error</termref> occurs.</p></error>
         </p></def></gitem><gitem><label>Examples</label><def role="example"><table role="medium" border="1" cellpadding="5" width="100%"><tbody><tr><td colspan="2" rowspan="1" align="left" valign="top"><p>The instruction:</p></td></tr><tr><td colspan="2" rowspan="1" align="left" valign="top"><eg xml:space="preserve">&lt;xsl:apply-templates select="//glossary/entry[@name=current()/@ref]"/&gt;</eg></td></tr><tr><td colspan="2" rowspan="1" align="left" valign="top"><p>will process all <code nobreak="false">entry</code> elements that have a <code nobreak="false">glossary</code> parent
               element and that have a <code nobreak="false">name</code> attribute with value equal to the value of
               the current item’s <code nobreak="false">ref</code> attribute. This is different from</p></td></tr><tr><td colspan="2" rowspan="1" align="left" valign="top"><eg xml:space="preserve">&lt;xsl:apply-templates select="//glossary/entry[@name=./@ref]"/&gt;</eg></td></tr><tr><td colspan="2" rowspan="1" align="left" valign="top"><p>which means the same as</p></td></tr><tr><td colspan="2" rowspan="1" align="left" valign="top"><eg xml:space="preserve">&lt;xsl:apply-templates select="//glossary/entry[@name=@ref]"/&gt;</eg></td></tr><tr><td colspan="2" rowspan="1" align="left" valign="top"><p>and so would process all <code nobreak="false">entry</code> elements that have a
                  <code nobreak="false">glossary</code> parent element and that have a <code nobreak="false">name</code> attribute
               and a <code nobreak="false">ref</code> attribute with the same value.</p></td></tr></tbody></table></def></gitem></glist></div3><div3 id="func-unparsed-entity-uri"><head>fn:unparsed-entity-uri</head><glist><gitem><label>Summary</label><def><p>Returns the URI (system identifier) of an unparsed entity</p></def></gitem><gitem><label>Signature</label><def><example role="signature"><proto isOp="no" prefix="fn" name="unparsed-entity-uri" return-type="xs:anyURI" returnEmptyOk="no" returnSeq="no" returnVaries="no" isSchema="no" isDatatype="no" isSpecial="no"><arg name="entity-name" type="xs:string"/><arg name="doc" type="node()" default="."/></proto></example></def></gitem><gitem><label>Properties</label><def><p>This function is <xtermref spec="FO40" ref="dt-deterministic">deterministic</xtermref>, <xtermref spec="FO40" ref="dt-focus-dependent">focus-dependent</xtermref>,  and <xtermref spec="FO40" ref="dt-context-dependent">context-dependent</xtermref>. </p></def></gitem><gitem><label>Rules</label><def><p>Calling the single-argument form of this function has the same effect as calling the
         two-argument form with the context item as the second argument.</p><p>The two-argument <function>unparsed-entity-uri</function> 
            function returns the URI of the unparsed
            entity whose name is given by the value of the <code nobreak="false">$entity-name</code> argument, in
            the document containing the node supplied as the 
               value of the <code nobreak="false">$doc</code> argument. It
            returns the zero-length <code nobreak="false">xs:anyURI</code> if there is no such entity. This function
            maps to the <code nobreak="false">dm:unparsed-entity-system-id</code> accessor defined in <bibref ref="xpath-datamodel-40"/>.</p></def></gitem><gitem><label>Error Conditions</label><def><p>
            <error spec="XT" type="dynamic" class="DE" code="1370"><p>It is a <termref def="dt-dynamic-error"/> if <code nobreak="false">$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></error>
         </p><p>The following errors may be raised when <code nobreak="false">$node</code> is omitted:</p><ulist><item><p>If the context item is absent, <termref def="dt-dynamic-error"/> 
                  <xerrorref spec="XP40" class="DY" code="0002"/>.</p></item><item><p>If the context item is not a node, <termref def="dt-type-error"/> 
                  <xerrorref spec="XP40" class="TY" code="0004"/>.</p></item></ulist></def></gitem><gitem><label>Notes</label><def><note><p>The XDM accessor <code nobreak="false">dm:unparsed-entity-system-id</code> is defined to return an absolute URI,
            obtained by resolving the system identifier as written against the base URI of the document. If no
            base URI is available for the document, the <function>unparsed-entity-uri</function> function
            <rfc2119>should</rfc2119> return the system identifier as written, without any attempt to make
            it absolute.</p><p>XML permits more than one unparsed entity declaration with the same name to appear,
         and says that the first declaration is the one that should be used. This rule <rfc2119>should</rfc2119> be 
         respected during construction of the data model; the data model instance should not contain more than one
         unparsed entity with the same name.</p></note></def></gitem></glist></div3><div3 id="func-unparsed-entity-public-id"><head>fn:unparsed-entity-public-id</head><glist><gitem><label>Summary</label><def><p>Returns the public identifier of an unparsed entity</p></def></gitem><gitem><label>Signature</label><def><example role="signature"><proto isOp="no" prefix="fn" name="unparsed-entity-public-id" return-type="xs:string" returnEmptyOk="no" returnSeq="no" returnVaries="no" isSchema="no" isDatatype="no" isSpecial="no"><arg name="entity-name" type="xs:string"/><arg name="doc" type="node()" default="."/></proto></example></def></gitem><gitem><label>Properties</label><def><p>This function is <xtermref spec="FO40" ref="dt-deterministic">deterministic</xtermref>, <xtermref spec="FO40" ref="dt-focus-dependent">focus-dependent</xtermref>,  and <xtermref spec="FO40" ref="dt-context-dependent">context-dependent</xtermref>. </p></def></gitem><gitem><label>Rules</label><def><p>Calling the single-argument form of this function has the same effect as calling the
            two-argument form with the context item as the second argument.</p><p>The two-argument <function>unparsed-entity-public-id</function> 
            function returns the public
            identifier of the unparsed entity whose name is given by the value of the
            <code nobreak="false">$entity-name</code> argument, in the document containing the node supplied as the 
               value of the <code nobreak="false">$doc</code> argument. It returns the zero-length string if
            there is no such entity, or if the entity has no public identifier. This function maps
            to the <code nobreak="false">dm:unparsed-entity-public-id</code> accessor defined in <bibref ref="xpath-datamodel-40"/>.</p></def></gitem><gitem><label>Error Conditions</label><def><p>
            <error spec="XT" type="dynamic" class="DE" code="1380"><p>It is a <termref def="dt-dynamic-error"/> if <code nobreak="false">$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></error>
         </p><p>The following errors may be raised when <code nobreak="false">$node</code> is omitted:</p><ulist><item><p>If the context item is absent, <termref def="dt-dynamic-error"/> 
                  <xerrorref spec="XP40" class="DY" code="0002"/>.</p></item><item><p>If the context item is not a node, <termref def="dt-type-error"/> 
                  <xerrorref spec="XP40" class="TY" code="0004"/>.</p></item></ulist></def></gitem><gitem><label>Notes</label><def><note><p>XML permits more than one unparsed entity declaration with the same name to appear,
            and says that the first declaration is the one that should be used. This rule <rfc2119>should</rfc2119> be 
            respected during construction of the data model; the data model instance should not contain more than one
            unparsed entity with the same name.</p></note></def></gitem></glist></div3><div3 id="func-system-property"><head>fn:system-property</head><glist><gitem><label>Summary</label><def><p>Returns the value of a system property</p></def></gitem><gitem><label>Signature</label><def><example role="signature"><proto isOp="no" prefix="fn" name="system-property" return-type="xs:string" returnEmptyOk="no" returnSeq="no" returnVaries="no" isSchema="no" isDatatype="no" isSpecial="no"><arg name="name" type="(xs:string | xs:QName)"/></proto></example></def></gitem><gitem><label>Properties</label><def><p>This function is <xtermref spec="FO40" ref="dt-deterministic">deterministic</xtermref>, <xtermref spec="FO40" ref="dt-focus-independent">focus-independent</xtermref>,  and <xtermref spec="FO40" ref="dt-context-dependent">context-dependent</xtermref>.  It depends on 
		namespaces.
	</p></def></gitem><gitem><label>Rules</label><def><p>The value of the <code nobreak="false">$name</code> argument 
            <rfc2119>must</rfc2119> be <phrase diff="add" at="2022-01-01">either an <code nobreak="false">xs:QName</code>, or </phrase>
            a string containing an <termref def="dt-eqname">EQName</termref>. If it is a 
            <termref def="dt-lexical-qname">lexical QName</termref>
            with a prefix, then it is expanded into an <termref def="dt-expanded-qname">expanded
               QName</termref> using the namespace declarations in the static context of the
            <termref def="dt-expression">expression</termref>. If there is no prefix, the name is
            taken as being in no namespace.</p><p>The <function>system-property</function> function returns a string representing the
            value of the system property identified by the name. If there is no such system
            property, the zero-length string is returned.</p><p>Implementations <rfc2119>must</rfc2119> provide the following system properties, which
            are all in the <termref def="dt-xslt-namespace">XSLT namespace</termref>:</p><ulist><item><p>
                  <code nobreak="false">xsl:version</code>, a number giving the version of XSLT implemented by the
                     <termref def="dt-processor">processor</termref>; for implementations conforming
                  to the version of XSLT specified by this document, this is the string <code nobreak="false">"4.0"</code>. 
                  The value will always be a
                  string in the lexical space of the decimal datatype defined in XML Schema (see
                     <bibref ref="xmlschema-2"/>). This allows the value to be converted to a number
                  for the purpose of magnitude comparisons.</p></item><item><p>
                  <code nobreak="false">xsl:vendor</code>, a string identifying the implementer of the <termref def="dt-processor">processor</termref>
               </p></item><item><p>
                  <code nobreak="false">xsl:vendor-url</code>, a string containing a URL identifying the implementer
                  of the <termref def="dt-processor">processor</termref>; typically this is the host
                  page (home page) of the implementer’s Web site.</p></item><item><p>
                  <code nobreak="false">xsl:product-name</code>, a string containing the name of the implementation,
                  as defined by the implementer. This <rfc2119>should</rfc2119> normally remain
                  constant from one release of the product to the next. It <rfc2119>should</rfc2119>
                  also be constant across platforms in cases where the same source code is used to
                  produce compatible products for multiple execution platforms.</p></item><item><p>
                  <code nobreak="false">xsl:product-version</code>, a string identifying the version of the
                  implementation, as defined by the implementer. This <rfc2119>should</rfc2119>
                  normally vary from one release of the product to the next, and at the discretion
                  of the implementer it <rfc2119>may</rfc2119> also vary across different execution
                  platforms.</p></item><item><p>
                  <code nobreak="false">xsl:is-schema-aware</code>, returns the string <code nobreak="false">"yes"</code> in the
                  case of a processor that claims conformance as a <termref def="dt-schema-aware-xslt-processor">schema-aware XSLT processor</termref>, or
                     <code nobreak="false">"no"</code> in the case of a <termref def="dt-basic-xslt-processor">basic
                     XSLT processor</termref>.</p></item><item><p>
                  <code nobreak="false">xsl:supports-serialization</code>, returns the string <code nobreak="false">"yes"</code> in
                  the case of a processor that offers the <termref def="dt-serialization-feature">serialization feature</termref>, or <code nobreak="false">"no"</code> otherwise.</p></item><item><p>
                  <code nobreak="false">xsl:supports-backwards-compatibility</code>, returns the string
                     <code nobreak="false">"yes"</code> in the case of a processor that offers the <termref def="dt-1.0-compatibility-feature"/>, or
                     <code nobreak="false">"no"</code> otherwise.</p></item><item><p>
                  <code nobreak="false">xsl:supports-namespace-axis</code>, returns the string <code nobreak="false">"yes"</code> in
                  the case of a processor that offers the XPath namespace axis even when not in
                  backwards compatible mode, or <code nobreak="false">"no"</code> otherwise. Note that a processor
                  that supports backwards compatible mode must support the namespace axis when in
                  that mode, so this property is not relevant to that case.</p></item><item><p>
                  <code nobreak="false">xsl:supports-streaming</code>, returns the string <code nobreak="false">"yes"</code> in the
                  case of a processor that offers the streaming feature (see <specref ref="streaming-feature"/>), or <code nobreak="false">"no"</code> otherwise.</p></item><item><p>
                  <code nobreak="false">xsl:supports-dynamic-evaluation</code>, returns the string
                     <code nobreak="false">"yes"</code> unless dynamic evaluation (that is,
                  use of <elcode>xsl:evaluate</elcode>) has been disabled, in which
                  case it returns <code nobreak="false">"no"</code>.</p></item><item><p diff="chg" at="2023-01-29">
                  <code nobreak="false">xsl:supports-higher-order-functions</code>, always returns the string
                  <code nobreak="false">"yes"</code>.</p><note diff="chg" at="2023-01-29">In XSLT 4.0, support for higher-order functions is no
               longer an optional feature.</note></item><item><p>
                  <code nobreak="false">xsl:xpath-version</code>, a number giving the version of XPath implemented by the
                  <termref def="dt-processor">processor</termref>; for implementations conforming
                  to the version of XSLT specified by this document, this is the string <code nobreak="false">"4.0"</code>. 
                  The value will always be a
                  string in the lexical space of the <code nobreak="false">xs:decimal</code> data type. 
                  This allows the value to be converted to a number
                  for the purpose of magnitude comparisons.
               </p></item><item><p>
                  <code nobreak="false">xsl:xsd-version</code>, a number giving the version of XSD (XML Schema) implemented by the
                  <termref def="dt-processor">processor</termref>. The value will always be a
                  string in the lexical space of the decimal datatype defined in XML Schema (see
                  <bibref ref="xmlschema-2"/>). This allows the value to be converted to a number
                  for the purpose of magnitude comparisons. Typical values are <code nobreak="false">"1.0"</code> or <code nobreak="false">"1.1"</code>.
                  This property is relevant even when the processor is not schema-aware, since the built-in datatypes
                  for XSD 1.1 differ from those in XSD 1.0.
               </p></item></ulist><p>Some of these properties relate to the conformance levels and features offered by the
               <termref def="dt-processor">processor</termref>: these options are described in
               <specref ref="conformance"/>.</p><p>Except where otherwise specified, the actual values returned for the above properties 
            are <termref def="dt-implementation-defined">implementation-defined</termref>.</p><p>The set of system properties that are supported, in addition to those listed above, is
            also <termref def="dt-implementation-defined">implementation-defined</termref>.
            Implementations <rfc2119>must not</rfc2119> define additional system properties in the
            XSLT namespace.</p><imp-def-feature>The values returned by the <function>system-property</function> function,
            and the names of the additional properties that are recognized, are
            implementation-defined.</imp-def-feature></def></gitem><gitem><label>Error Conditions</label><def><p>
            <error spec="XT" type="dynamic" class="DE" code="1390"><p>It is a <termref def="dt-dynamic-error"> dynamic error</termref> if the value supplied as
                  the <code nobreak="false">$property-name</code> argument <error.extra>to the
                        <function>system-property</function> function</error.extra> is not a valid
                  QName, or if there is no namespace declaration in scope for the prefix of the
                  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 raise this as a <termref def="dt-static-error">static error</termref>. </p></error>
         </p></def></gitem><gitem><label>Notes</label><def><note><p>An implementation must not return the value <code nobreak="false">
               3.0
            </code> as the value of the <code nobreak="false">xsl:version</code> system property unless it is
            conformant to XSLT 3.0.</p><p>It is recognized that vendors who are enhancing XSLT 1.0 or
               2.0 processors may wish to release interim implementations before all the
            mandatory features of this specification are implemented. Since such products are not
            conformant to XSLT 3.0, this specification cannot define their behavior. However,
            implementers of such products are encouraged to return a value for the
               <code nobreak="false">xsl:version</code> system property that is intermediate between 1.0 and 3.0,
            and to provide the <function>element-available</function> and
               <function>function-available</function> functions to allow users to test which
            features have been fully implemented.</p><p>In XSLT 4.0, the argument can be supplied as a QName literal, for example
         <code nobreak="false">system-property( #xsl:version )</code>.</p><p>TODO: add change metadata (PR 1243)</p></note></def></gitem></glist></div3><div3 id="func-available-system-properties"><head>fn:available-system-properties</head><glist><gitem><label>Summary</label><def><p>Returns a list of system property names that are suitable for passing to
            the <function>system-property</function> function, as a sequence of QNames.</p></def></gitem><gitem><label>Signature</label><def><example role="signature"><proto isOp="no" prefix="fn" name="available-system-properties" return-type="xs:QName*" returnEmptyOk="no" returnSeq="no" returnVaries="no" isSchema="no" isDatatype="no" isSpecial="no"/></example></def></gitem><gitem><label>Properties</label><def><p>This function is <xtermref spec="FO40" ref="dt-deterministic">deterministic</xtermref>, <xtermref spec="FO40" ref="dt-context-independent">context-independent</xtermref>,  and <xtermref spec="FO40" ref="dt-focus-independent">focus-independent</xtermref>. </p></def></gitem><gitem><label>Rules</label><def><p>The function returns a sequence of QNames, being the names of the system properties
            recognized by the processor, in some <termref def="dt-implementation-dependent">implementation-dependent</termref> order.</p><p>The prefix part of a returned QName is <termref def="dt-implementation-dependent"/>.</p><p>The function is <xtermref spec="FO40" ref="dt-deterministic">deterministic</xtermref>: that is, the
            set of available system properties does not vary during the course of a transformation.</p></def></gitem><gitem><label>Notes</label><def><note><p>The function returns a list of QNames, containing no duplicates.</p><p>The QNames in this list are suitable for passing to the
            <function>system-property</function> function.<phrase diff="del" at="2022-01-01"> However, they must first be converted to
            the form expected by the <function>system-property</function> function, which is either
            a lexical QName or to an EQName in the form <code nobreak="false">Q{uri}local</code>. Because the prefix 
            of the returned QName is unpredictable, the <code nobreak="false">Q{uri}local</code> is likely
            to be more convenient. Conversion of an <code nobreak="false">xs:QName</code> value to an EQName in 
            <code nobreak="false">Q{uri}local</code> format can be achieved using the function:</phrase></p></note></def></gitem></glist></div3></div2></div1><div1 id="map"><head>Maps</head><p diff="chg" at="2022-01-01">Maps are defined in the XDM Data Model: see <xspecref spec="DM40" ref="map-items"/>.</p><div2 id="map-instructions"><head>Map Instructions</head><changes><change issue="1632" PR="1694" date="2025-01-14">
                  The <elcode>xsl:map</elcode> instruction allows a <code nobreak="false">select</code> attribute
                  as an alternative to the contained sequence constructor.
               </change><change issue="1632" PR="1694" date="2025-01-14">
                  The <elcode>xsl:map-entry</elcode> instruction, in common with other instructions,
                  now raises error XTSE3185 (rather than XTSE3280) if both a <code nobreak="false">select</code>
                  attribute and a sequence constructor are present.
               </change><change issue="1651" PR="1703" date="2025-01-14">
                  Ordered maps are introduced.
               </change></changes><p>Three instructions are added to XSLT to facilitate the construction of maps.</p><e:element-syntax xmlns:e="http://www.w3.org/1999/XSL/Spec/ElementSyntax" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" name="map">
      <e:in-category name="instruction"/>
      <e:attribute name="select">
         <e:data-type name="expression"/>
      </e:attribute>
      <e:attribute name="duplicates" required="no" default="fn($a, $b) { error(xs:QName(err:XTDE3365)) }">
         <e:data-type name="expression"/>
      </e:attribute>
      <!--<e:attribute name="ordered" default="no">
         <e:attribute-value-template>
            <e:data-type name="boolean"/>
         </e:attribute-value-template>
      </e:attribute>-->
      <e:model name="sequence-constructor"/>
      <e:allowed-parents>
         <e:parent-category name="sequence-constructor"/>
      </e:allowed-parents>
   </e:element-syntax><p>The instruction <elcode>xsl:map</elcode> constructs and returns a new map.</p><p>The <code nobreak="false">select</code> attribute and the contained sequence constructor are mutually
               exclusive: if a <code nobreak="false">select</code> attribute is present, then the content
                  <rfc2119>must</rfc2119> be empty except optionally for
                  <elcode>xsl:fallback</elcode> instructions. <errorref spec="XT" class="SE" code="3185"/></p><p>The result of evaluating the <code nobreak="false">select</code> expression or the contained
            sequence constructor is referred to as the <term>input sequence</term>.</p><p>The input sequence <rfc2119>must</rfc2119> be a sequence of
               maps: call this <code nobreak="false">$maps</code>.</p><p><phrase diff="chg" at="2022-01-01">In the absence of duplicate keys,</phrase> the result of the instruction  
               is then given by the XPath 3.1 expression:</p><eg role="non-xml" xml:space="preserve">map:merge($maps)</eg><note><p>Informally: <phrase diff="chg" at="2022-01-01">in the absence of duplicate keys</phrase> the resulting map contains
                  the union of the map entries from the supplied sequence of maps.</p></note><note><p>The order of entries in the returned map will reflect
                  the order of items in the sequence that results from evaluation of the
                  input sequence.</p></note><p>The handling of duplicate keys is described in <specref ref="duplicate-keys"/> below.</p><p>There is no requirement that the supplied input maps should have the same or
               compatible types.
               The type of a map (for example <code nobreak="false">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><note diff="add" at="2023-04-04"><p>A common coding pattern is to supply the input as a set of single-entry maps, that is,
               maps containing a single key-value pair. Moreover, it is often convenient to construct these
               using the <elcode>xsl:map-entry</elcode> instruction. However, it is not required that
               the input maps should be single-entry maps, nor is it required that they should be constructed
               using this instruction.</p></note><p><error spec="XT" class="TE" code="3375" type="type"><p>A type error occurs if the result of the input sequence
                        <error.extra>of an <elcode>xsl:map</elcode> instruction</error.extra> is
                     not an instance of the required type <code nobreak="false">map(*)*</code>.</p></error></p><note><p>In practice, the effect of this rule is that the result of the 
                  <code nobreak="false">select</code> expression or sequence
                  constructor contained in the <elcode>xsl:map</elcode> instruction is severely
                  constrained: it doesn’t make sense, for example, for it to contain
                  instructions such as <elcode>xsl:element</elcode> that create new nodes. As with
                  other type errors, processors are free to raise the error statically if they are
                  able to determine that the sequence constructor would always fail when
                  evaluated.</p></note><note><p>It is legitimate to construct a map using an instruction such as
               <code nobreak="false">&lt;xsl:map select="{'a':1, 'b':2}"/&gt;</code>. In this situation
               <elcode>xsl:map</elcode> has exactly the same effect as <elcode>xsl:sequence</elcode>,
               but users may feel that it improves readability.</p></note><e:element-syntax xmlns:e="http://www.w3.org/1999/XSL/Spec/ElementSyntax" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" name="map-entry">
      <e:in-category name="instruction"/>
      <e:attribute name="key" required="yes">
         <e:data-type name="expression"/>
      </e:attribute>
      <e:attribute name="select">
         <e:data-type name="expression"/>
      </e:attribute>
      <e:model name="sequence-constructor"/>
      <e:allowed-parents>
         <e:parent-category name="sequence-constructor"/>
      </e:allowed-parents>
   </e:element-syntax><p>The instruction <elcode>xsl:map-entry</elcode> constructs and returns a singleton
               map: that is, a map which  contains one
               key and one value. Such a map is primarily used as a building block when constructing
               maps using the <elcode>xsl:map</elcode> instruction.</p><p>The <code nobreak="false">select</code> attribute and the contained sequence constructor are mutually
               exclusive: if a <code nobreak="false">select</code> attribute is present, then the content
                  <rfc2119>must</rfc2119> be empty except optionally for
                  <elcode>xsl:fallback</elcode> instructions. <errorref spec="XT" class="SE" code="3185"/></p><p>The key of the entry in the new map is the value obtained by evaluating the
               expression in the <code nobreak="false">key</code> attribute, converted to the required type
                  <code nobreak="false">xs:anyAtomicType</code> by applying the <termref def="dt-coercion-rules"/>. If the supplied key (after conversion) is of
               type <code nobreak="false">xs:untypedAtomic</code>, it is cast to <code nobreak="false">xs:string</code>.</p><p>The associated value is the value obtained by evaluating the expression in the
                  <code nobreak="false">select</code> attribute, or the contained sequence constructor, with no
               conversion. If there is no <code nobreak="false">select</code> attribute and the sequence constructor
               is empty, the associated value is the empty sequence.</p><example><head>Using XSLT instructions to create a fixed map</head><p>The following example binds a variable to a map whose content is statically
                     known:</p><eg role="xslt-declaration" xml:space="preserve">
&lt;xsl:variable name="week" as="map(xs:string, xs:string)"&gt;
  &lt;xsl:map&gt;
    &lt;xsl:map-entry key="'Mo'" select="'Monday'"/&gt;
    &lt;xsl:map-entry key="'Tu'" select="'Tuesday'"/&gt;
    &lt;xsl:map-entry key="'We'" select="'Wednesday'"/&gt;
    &lt;xsl:map-entry key="'Th'" select="'Thursday'"/&gt;
    &lt;xsl:map-entry key="'Fr'" select="'Friday'"/&gt;
    &lt;xsl:map-entry key="'Sa'" select="'Saturday'"/&gt;
    &lt;xsl:map-entry key="'Su'" select="'Sunday'"/&gt;
  &lt;/xsl:map&gt;
&lt;/xsl:variable&gt;  
</eg><p>In simple cases like this the same effect can be achieved using the
                <elcode>xsl:record</elcode> instruction:</p><eg role="xslt-declaration" xml:space="preserve">
&lt;xsl:variable name="week" as="map(xs:string, xs:string)"&gt;
  &lt;xsl:record
    Mo="'Monday'"
    Tu="'Tuesday'"
    We="'Wednesday'"
    Th="'Thursday'"
    Fr="'Friday'"
    Sa="'Saturday'"
    Su="'Sunday'"/&gt;
&lt;/xsl:variable&gt;  
</eg><p>A third option is to construct the map in XPath:</p><eg role="xslt-declaration" xml:space="preserve">
&lt;xsl:variable name="week" as="map(xs:string, xs:string)"&gt;
  &lt;xsl:select&gt;
    {'Mo':'Monday', 'Tu':'Tuesday', 'We':'Wednesday',
     'Th':'Thursday', 'Fr': 'Friday', 'Sa':'Saturday',
     'Su':'Sunday'}
  &lt;/xsl:select&gt;   
&lt;/xsl:variable&gt;  
</eg></example><example><head>Using XSLT instructions to create a computed map</head><p>The following example binds a variable to a map acting as an index into a source
                     document:</p><eg role="xslt-declaration" xml:space="preserve">
&lt;xsl:variable name="index" as="map(xs:string, element(employee))"&gt;
  &lt;xsl:map&gt;
    &lt;xsl:for-each select="//employee"&gt;
      &lt;xsl:map-entry key="@empNr" select="."/&gt;
    &lt;/xsl:for-each&gt;
  &lt;/xsl:map&gt;
&lt;/xsl:variable&gt;  
</eg><p>Again, an alternative is to use an XPath expression:</p><eg role="xslt-declaration" xml:space="preserve">
&lt;xsl:variable name="index" as="map(xs:string, element(employee))"&gt;
  &lt;xsl:select&gt;
    map:build(//employee, fn{@empNr})
  &lt;/xsl:select&gt;
&lt;/xsl:variable&gt;  
</eg></example><example diff="add" at="2023-04-04"><head>Modifying the keys in a map</head><p>The following example modifies a supplied map <code nobreak="false">$input</code> by changing
                     all the keys to upper case. A dynamic error occurs if this results in duplicate
                     keys:</p><eg role="xslt-declaration" xml:space="preserve">&lt;xsl:map&gt;
  &lt;xsl:for-each select="map:pairs($map)"&gt;
    &lt;xsl:map-entry key="upper-case(?key)" select="?value"/&gt;
  &lt;/xsl:for-each&gt;
&lt;/xsl:map&gt; 
</eg></example><example diff="add" at="2023-04-04"><head>Modifying the values in a map</head><p>The following example modifies a supplied map <code nobreak="false">$input</code> by wrapping
                     each of the values in an array:</p><eg role="xslt-declaration" xml:space="preserve">&lt;xsl:map&gt;
  &lt;xsl:for-each select="map:pairs($map)"&gt;
    &lt;xsl:map-entry key="?key"&gt;
       &lt;xsl:array select="?value"/&gt;
    &lt;/xsl:map-entry&gt;
  &lt;/xsl:for-each&gt;
&lt;/xsl:map&gt; 
</eg><p>This could also be written:</p><eg role="xslt-declaration" xml:space="preserve">&lt;xsl:map select="
  map:pairs($map) ! { ?key : array{ ?value } }"/&gt;
</eg></example><div3 id="record-instructions" diff="add" at="2025-03-14"><head>Record Instruction</head><changes><change issue="322" PR="1858" date="2025-03-25"> The <elcode>xsl:record</elcode> instruction is introduced
                     to make construction of record maps simpler. </change></changes><e:element-syntax xmlns:e="http://www.w3.org/1999/XSL/Spec/ElementSyntax" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" name="record">
        <e:in-category name="instruction"/>
        <e:attribute name="xsl:as" default="'map(*)'">
            <e:data-type name="item-type"/>
        </e:attribute>
        <e:attribute name="xsl:duplicates" required="no" default="fn($a, $b) { error(xs:QName(err:XTDE3365)) }">
            <e:data-type name="expression"/>
        </e:attribute>
        <e:attribute name="*" required="yes">
           <e:data-type name="expression"/>
        </e:attribute>
        <e:model name="sequence-constructor"/>
        <e:allowed-parents>
            <e:parent-category name="sequence-constructor"/>
        </e:allowed-parents>
    </e:element-syntax><p>(The notation <code nobreak="false">* = expression</code> indicates that this instruction accepts
             any number of additional attributes in no namespace.)</p><p><ednote><edtext>There needs to be a construct available within <code nobreak="false">element-catalog.xml</code>
                             to declare 'any permitted attribute of a given name type/pattern', in this case <code nobreak="false">xs:NCName</code>
             
                             </edtext></ednote></p><p>The instruction <elcode>xsl:record</elcode> constructs and returns a new
                 populated map, permitting entries to be declared as attributes on the
                 instruction. It is intended to make writing maps where the entry keys are
                 NCNames simpler and more concise, avoiding larger XSLT constructs using
                 <elcode>xsl:map</elcode> and <elcode>xsl:map-entry</elcode> or
                 <elcode>xsl:sequence</elcode> containing map-constructing XPath
                 expressions.</p><note><p>Unlike all other <termref def="dt-xslt-element">XSLT elements</termref>, the names of the attributes <code nobreak="false">xsl:as</code> and
                         <code nobreak="false">xsl:duplicates</code> as well as the <termref def="dt-standard-attributes">standard
                             attributes</termref> (such as <code nobreak="false">use-when</code> or <code nobreak="false">xpath-default-namespace</code>) attached to the <elcode>xsl:record</elcode> instruction <rfc2119>must</rfc2119> be in the <termref def="dt-xslt-namespace">XSLT namespace</termref>, 
                         as opposed to being in no namespace. This has been chosen to
                         avoid reserving the names of such attributes (e.g. <code nobreak="false">as</code>, <code nobreak="false">duplicates</code>, <code nobreak="false">use-when</code> etc.) as potential
                         entry keys, leaving any valid NCName as a candidate.</p></note><p>The <elcode>xsl:record</elcode> generates a new map: call this
                 <code nobreak="false">$record</code>. For each of the attributes of the instruction whose name
                 is an <code nobreak="false">xs:NCName</code> an entry is added to <code nobreak="false">$record</code> whose
                 key is the name of the attribute (as <code nobreak="false">xs:string</code>) and whose value is
                 the result of evaluating the value of that attribute as an expression in the
                 current context.</p><note><p>As the values of the attributes whose names are <code nobreak="false">xs:NCName</code> are considered to be XPath expressions,
                     two consequences follow for such attributes:
                     <olist><item>They <rfc2119>must not</rfc2119> be considered as shadow attributes (see <specref ref="shadow-attributes"/>) 
                             as a leading underscore is a valid character within an <code nobreak="false">xs:NCName</code>.</item><item>They are not designated as <termref def="dt-attribute-value-template">attribute
                                 value templates</termref>.</item></olist> These restrictions do not apply to attributes of <elcode>xsl:record</elcode> whose names are in namespaces.</p></note><note><p>The order of attribute-generated entries in <code nobreak="false">$record</code> will reflect
                         the order of attributes returned along the <code nobreak="false">attribute::</code> axis, which is <termref def="dt-implementation-dependent"/> but stable.</p></note><p>After processing the applicable attributes of the instruction, any contained
                 sequence constructor is evaluated and the result <rfc2119>must</rfc2119> be a
                 (possibly empty) sequence of maps. The entries in these maps are merged into
                 <code nobreak="false">$record</code>. By this means entries can be added whose keys are not
                 NCNames, or conditionally generated entries can be included.</p><p> Each of the map entries in
                 <code nobreak="false">$record</code> is modified by applying the <termref def="dt-coercion-rules"/>
                 to convert the singleton map to the type declared in the <code nobreak="false">xsl:as</code>
                 attribute of the <elcode>xsl:record</elcode> instruction, if present. 
                 This may contain a map type declaration or 
                 a reference to one of the <xtermref spec="XP40" ref="dt-in-scope-named-item-types"/>, which may include record types. 
                 Unless any type restriction is violated <code nobreak="false">$record</code> is returned as the instruction result.</p><p><ednote><edtext>This implies that <elcode>xsl:map</elcode> and possibly <elcode>xsl:map-entry</elcode>
                             should support an <code nobreak="false">as</code> attribute, restricting type.</edtext></ednote></p><p>The treatment of duplicate keys between entries defined in the attributes of
                 <elcode>xsl:record</elcode> and any generated by a contained sequence
                 constructor is described in <specref ref="duplicate-keys"/> below. Note that in
                 the absence of a sequence constructor, no duplicate keys can appear, as all
                 attributes of <elcode>xsl:record</elcode> must have a unique name within the
                 element tag.</p><p>The effect of this instruction, in the absence of errors, is equivalent to execution of the XSLT <elcode>xsl:map</elcode> instruction generated by the 
                     the following source transformation of the <elcode>xsl:record</elcode> subtree</p><eg role="xslt-declaration" xml:space="preserve">
                   &lt;xsl:namespace-alias stylesheet-prefix="t" result-prefix="xsl"/&gt;
...

&lt;xsl:mode name="record" on-no-match="shallow-copy"&gt;
   &lt;xsl:template match="xsl:record"&gt;
      &lt;xsl:variable name="xsl-attributes" select="@xsl:*"/&gt;
      &lt;xsl:variable name="ncname-attributes" select="@*[empty(prefix-from-QName(node-name()))]"/&gt;
      &lt;xsl:variable name="other-attributes"
          select="@* except ($xsl-attributes, $ncname-attributes)"/&gt;
      &lt;t:map&gt;
         &lt;xsl:sequence select="$other-attributes"/&gt;
         &lt;xsl:apply-templates select="$xsl-attributes, $ncname-attributes, node()"/&gt;
      &lt;/t:map&gt;
   &lt;/xsl:template&gt;
   &lt;xsl:template match="xsl:record/@*"&gt;
      &lt;t:map-entry key="'{name()}'" select="{.}"/&gt;
   &lt;/xsl:template&gt;
   &lt;xsl:template match="xsl:record/@xsl:*" priority="1"&gt;
      &lt;xsl:attribute name="{local-name()}" select="."/&gt;
   &lt;/xsl:template&gt;
&lt;/xsl:mode&gt;
                 </eg><p>which for the instruction:</p><eg xml:space="preserve"> &lt;xsl:record xsl:as="eg:book" author="string(AUTHOR)"
               title="string(TITLE)" 
               price="xs:decimal(PRICE)" 
               publisher="string(../@name)"&gt;
      &lt;xsl:if test="@private"&gt;
         &lt;xsl:map-entry name="'private entry'" select="true()"/&gt;
      &lt;/xsl:if&gt;
   &lt;/xsl:record&gt;</eg><p>would produce</p><eg xml:space="preserve"> &lt;xsl:map as="eg:book"&gt;
      &lt;xsl:map-entry key="'author'" select="string(AUTHOR)"/&gt;
      &lt;xsl:map-entry key="'title'" select="string(TITLE)"/&gt;
      &lt;xsl:map-entry key="'price'" select="xs:decimal(PRICE)"/&gt;
      &lt;xsl:map-entry key="'publisher'" select="string(../@name)"/&gt;
      &lt;xsl:if test="@private"&gt;
         &lt;xsl:map-entry name="'private entry'" select="true()"/&gt;
      &lt;/xsl:if&gt;
   &lt;/xsl:map&gt;</eg><example diff="add" at="2025-02-25"><head>Generating a map with <elcode>xsl:record</elcode></head><p>The following example constructs a map using <elcode>xsl:record</elcode></p><eg role="xslt-declaration" xml:space="preserve">&lt;xsl:template match="book" as="map(*)"&gt;
   &lt;xsl:record author="string(AUTHOR)"
               title="string(TITLE)" 
               price="xs:decimal(PRICE)" 
               publisher="string(../@name)"&gt;
      &lt;xsl:if test="@private"&gt;
         &lt;xsl:map-entry name="'private entry'" select="true()"/&gt;
      &lt;/xsl:if&gt;
   &lt;/xsl:record&gt;
&lt;/xsl:template&gt;</eg><p>with the following input</p><eg xml:space="preserve">&lt;catalog name="QT4 Community"&gt;
  &lt;book private="true"&gt;
    &lt;AUTHOR&gt;MHK&lt;/AUTHOR&gt;
    &lt;TITLE&gt;XSLT 4.0&lt;/TITLE&gt;
    &lt;PRICE&gt;123.45&lt;/PRICE&gt;
  &lt;/book&gt;
&lt;/catalog&gt;</eg><p>will produce a resulting map:</p><eg xml:space="preserve">map{'author':'MHK', 'title': 'XSLT 4.0', 'price':123.45, 
                     'publisher':'QT4 Community', 'private entry': true()} </eg></example></div3><div3 id="duplicate-keys" diff="add" at="2022-01-01"><head>Handling of duplicate keys</head><changes><change issue="169" date="2023-11-28">
                     A new attribute <code nobreak="false">xsl:map/@duplicates</code> is available,
                  allowing control over how duplicate keys are handled by the <elcode>xsl:map</elcode>
                  instruction.
                  </change><change issue="322" PR="1858" date="2025-03-14">
                       Attribute <code nobreak="false">xsl:record/@xsl:duplicates</code> is added to control duplicate keys handling in the <elcode>xsl:record</elcode>
                       instruction.
                   </change></changes><p>This section describes what happens when two or more maps in the input sequence of
               an <elcode>xsl:map</elcode> or <elcode>xsl:record</elcode> instruction contain duplicate keys: that is, when one of these
               maps contains an entry with key <var>K</var>, and another contains an entry with key <var>L</var>,
                  and <code nobreak="false">fn:atomic-equal(<var>K</var>, <var>L</var>)</code> returns <code nobreak="false">true</code>.</p><p><error spec="XT" class="DE" code="3365" type="dynamic"><p>In the absence of the <code nobreak="false">[xsl:]duplicates</code> attribute, 
                     a <termref def="dt-dynamic-error">dynamic error</termref> occurs if the set of
                     keys in the maps making up the input sequence
                      <error.extra>of an <elcode>xsl:map</elcode> or <elcode>xsl:record</elcode> instruction</error.extra>
                     contains duplicates.</p></error></p><p>The result of evaluating the <code nobreak="false">[xsl:]duplicates</code> attribute, if present, <rfc2119>must</rfc2119>
               be either one of the strings <code nobreak="false">"use-first"</code>, <code nobreak="false">"use-last"</code>,
                  <code nobreak="false">"use-any"</code>, <code nobreak="false">"combine"</code>, or <code nobreak="false">"reject"</code>,
                  or a function with arity 2. These values correspond to the permitted
                  values of the <code nobreak="false">duplicates</code> option of the 
                  <xfunction>map:merge</xfunction> function.</p><p>The result of the <elcode>xsl:map</elcode> or <elcode>xsl:record</elcode> instruction is defined by reference to 
               the function <xfunction>map:merge</xfunction>. Specifically, if <code nobreak="false">$maps</code>
               is the input sequence to <elcode>xsl:map</elcode> or <elcode>xsl:record</elcode>, and <code nobreak="false">$duplicates</code>
               is the <termref def="dt-effective-value"/> of the <code nobreak="false">[xsl:]duplicates</code>
               attribute, then the result of the instruction is the result of the function
               call <code nobreak="false">map:merge($maps, { "duplicates": $duplicates })</code>.</p><p>The following table shows some possible values 
                  of the <code nobreak="false">duplicates</code> attribute, and explains their effect:</p><table border="1" cellpadding="5" width="100%"><thead><tr><th rowspan="1" colspan="1" align="left" valign="top">Attribute</th><th rowspan="1" colspan="1" align="left" valign="top">Effect</th></tr></thead><tbody><tr><td rowspan="1" colspan="1" align="left" valign="top"><code nobreak="false">duplicates="'use-first'"</code></td><td rowspan="1" colspan="1" align="left" valign="top">The first of the duplicate values is used.</td></tr><tr><td rowspan="1" colspan="1" align="left" valign="top"><code nobreak="false">duplicates="'use-last'"</code></td><td rowspan="1" colspan="1" align="left" valign="top">The last of the duplicate values is used.</td></tr><tr><td rowspan="1" colspan="1" align="left" valign="top"><code nobreak="false">duplicates="'combine'"</code></td><td rowspan="1" colspan="1" align="left" valign="top">The <xtermref spec="XP40" ref="dt-sequence-concatenation"/> 
                           of the duplicate values is used. This could
                        also be expressed as <code nobreak="false">duplicates="op(',')"</code>.</td></tr><tr><td rowspan="1" colspan="1" align="left" valign="top"><code nobreak="false">duplicates="fn($a, $b) { max(($a, $b)) }"</code></td><td rowspan="1" colspan="1" align="left" valign="top">The highest of the duplicate values is used.</td></tr><tr><td rowspan="1" colspan="1" align="left" valign="top"><code nobreak="false">duplicates="fn($a, $b) { min(($a, $b)) }"</code></td><td rowspan="1" colspan="1" align="left" valign="top">The lowest of the duplicate values is used.</td></tr><tr><td rowspan="1" colspan="1" align="left" valign="top"><code nobreak="false">duplicates="concat(?, ', ', ?) }"</code></td><td rowspan="1" colspan="1" align="left" valign="top">The comma-separated string concatenation of the duplicate values is used.</td></tr><tr><td rowspan="1" colspan="1" align="left" valign="top"><code nobreak="false">duplicates="op('+')"</code></td><td rowspan="1" colspan="1" align="left" valign="top">The sum of the duplicate values is used.</td></tr><tr><td rowspan="1" colspan="1" align="left" valign="top"><code nobreak="false">duplicates="fn($a, $b) { subsequence(($a, $b), 1, 4) }"</code></td><td rowspan="1" colspan="1" align="left" valign="top">The first four of the duplicates are retained; any further duplicates
                           are discarded.
                        </td></tr><tr><td rowspan="1" colspan="1" align="left" valign="top"><code nobreak="false">duplicates="fn($a, $b) { distinct-values(($a, $b)) }"</code></td><td rowspan="1" colspan="1" align="left" valign="top">When multiple entries have the same key, the corresponding values
                           are retained only if they are distinct from other values having the
                           same key.
                        </td></tr></tbody></table><example id="map-with-duplicates-into-array"><head>Combining Duplicates into an Array</head><p>This example takes as input an XML document such as:</p><eg xml:space="preserve">&lt;data&gt;
   &lt;event id="A23" value="12"/&gt;
   &lt;event id="A24" value="5"/&gt;
   &lt;event id="A25" value="9"/&gt;
   &lt;event id="A23" value="2"/&gt;
 &lt;/data&gt;</eg><p>and constructs a map whose JSON representation is:</p><eg xml:space="preserve">{ "A23": [ 12, 2 ], "A24": [ 5 ], "A23": [ 9 ] }</eg><p>The logic is:</p><eg xml:space="preserve">&lt;xsl:template match="data"&gt;
   &lt;xsl:map duplicates="fn($a, $b) { array:join(($a, $b)) }"&gt;
     &lt;xsl:for-each select="event"&gt;
        &lt;xsl:map-entry key="@id" select="[xs:integer(@value)]"/&gt;
     &lt;/xsl:for-each&gt;
   &lt;/xsl:map&gt;
   &lt;/xsl:template&gt;</eg></example><note><p>Specifying the effect by reference to <xfunction>map:merge</xfunction> has
                  the following consequences when duplicates are combined
                  into a merged entry:</p><ulist><item><p>The position of the merged entry in the result corresponds
                     to the position of the first of the duplicate keys in the input.</p></item><item><p>The key used for the merged entry in the result corresponds
                     to one of the duplicate keys in the input: it is 
                        <termref def="dt-implementation-dependent"/> which one is chosen.
                        This is relevant when
                     the duplicate keys differ in some way, for example when they have
                     different type annotations, or when they are <code nobreak="false">xs:dateTime</code>
                     values in different timezones.</p></item></ulist></note></div3></div2><div2 id="map-examples"><head>Examples using Maps</head><p>This section gives some examples of where maps can be useful.</p><example id="maps-with-iterate"><head>Using Maps with xsl:iterate</head><p>This example uses maps in conjunction with the <elcode>xsl:iterate</elcode>
                  instruction to find the highest-earning employee in each department, in a single
                  streaming pass of an input document containing employee records.</p><eg role="xslt-instruction" xml:space="preserve">
&lt;xsl:source-document streamable="yes" href="employees.xml"&gt;
  &lt;xsl:iterate select="*/employee"&gt;
    &lt;xsl:param name="highest-earners" 
               as="map(xs:string, element(employee))" 
               select="{}"/&gt;
    &lt;xsl:on-completion&gt;
      &lt;xsl:for-each select="map:keys($highest-earners)"&gt;
        &lt;department name="{.}"&gt;
          &lt;xsl:copy-of select="$highest-earners(.)"/&gt;
        &lt;/department&gt;
      &lt;/xsl:for-each&gt;
    &lt;/xsl:on-completion&gt;           
    &lt;xsl:variable name="this" select="copy-of(.)" as="element(employee)"/&gt; 
    &lt;xsl:next-iteration&gt;
      &lt;xsl:with-param name="highest-earners"
          select="let $existing := $highest-earners($this/department)
                  return if ($existing/salary gt $this/salary)
                         then $highest-earners
                         else map:put($highest-earners, $this/department, $this)"/&gt;
    &lt;/xsl:next-iteration&gt;
  &lt;/xsl:iterate&gt;
&lt;/xsl:source-document&gt;
</eg></example><example id="example-complex-numbers"><head>Using Maps to Implement Complex Numbers</head><p>A complex number might be represented as a map with two entries, the keys being
                  the <code nobreak="false">xs:boolean</code> value <code nobreak="false">true</code> for the real part, and the
                     <code nobreak="false">xs:boolean</code> value <code nobreak="false">false</code> for the imaginary part. A
                  library for manipulation of complex numbers might include functions such as the
                  following:</p><eg role="xslt-declaration xmlns:i='i'" xml:space="preserve">

&lt;xsl:variable name="REAL" static="yes" as="xs:int" select="0"/&gt; 
&lt;xsl:variable name="IMAG" static="yes" as="xs:int" select="1"/&gt; 
                     
&lt;xsl:function name="i:complex" as="map(xs:int, xs:double)"&gt;
  &lt;xsl:param name="real" as="xs:double"/&gt;
  &lt;xsl:param name="imaginary" as="xs:double"/&gt;
  &lt;xsl:sequence select="{ $REAL: $real, $IMAG: $imaginary }"/&gt;
&lt;/xsl:function&gt;

&lt;xsl:function name="i:real" as="xs:double"&gt;
  &lt;xsl:param name="complex" as="map(xs:int, xs:double)"/&gt;
  &lt;xsl:sequence select="$complex($REAL)"/&gt;
&lt;/xsl:function&gt;

&lt;xsl:function name="i:imaginary" as="xs:double"&gt;
  &lt;xsl:param name="complex" as="map(xs:int, xs:double)"/&gt;
  &lt;xsl:sequence select="$complex($IMAG)"/&gt;
&lt;/xsl:function&gt;

&lt;xsl:function name="i:add" as="map(xs:int, xs:double)"&gt;
  &lt;xsl:param name="arg1" as="map(xs:int, xs:double)"/&gt;
  &lt;xsl:param name="arg2" as="map(xs:int, xs:double)"/&gt;
  &lt;xsl:sequence select="i:complex(i:real($arg1)+i:real($arg2), 
                                  i:imaginary($arg1)+i:imaginary($arg2)"/&gt;
&lt;/xsl:function&gt;

&lt;xsl:function name="i:multiply" as="map(xs:boolean, xs:double)"&gt;
  &lt;xsl:param name="arg1" as="map(xs:boolean, xs:double)"/&gt;
  &lt;xsl:param name="arg2" as="map(xs:boolean, xs:double)"/&gt;
  &lt;xsl:sequence select="i:complex(
      i:real($arg1)*i:real($arg2) - i:imaginary($arg1)*i:imaginary($arg2),
      i:real($arg1)*i:imaginary($arg2) + i:imaginary($arg1)*i:real($arg2))"/&gt;
&lt;/xsl:function&gt;
</eg></example><example id="map-as-index"><head>Using a Map as an Index</head><p>Given a set of <code nobreak="false">book</code> elements, it is possible to construct an index in
                  the form of a map allowing the books to be retrieved by ISBN number.</p><p>Assume the book elements have the form:</p><eg role="xml" xml:space="preserve">
&lt;book&gt;
  &lt;isbn&gt;0470192747&lt;/isbn&gt;
  &lt;author&gt;Michael H. Kay&lt;/author&gt;
  &lt;publisher&gt;Wiley&lt;/publisher&gt;
  &lt;title&gt;XSLT 2.0 and XPath 2.0 Programmer's Reference&lt;/title&gt;
&lt;/book&gt;</eg><p>An index may be constructed as follows: </p><eg role="xslt-declaration xmlns:map='http://www.w3.org/2005/xpath-functions/map" xml:space="preserve">
&lt;xsl:variable name="isbn-index" as="map(xs:string, element(book))"
    select="map:merge(for $b in //book return { $b/isbn: $b })"/&gt;</eg><p>This index may then be used to retrieve the book for a given ISBN using either of
                  the expressions <code nobreak="false">map:get($isbn-index, "0470192747")</code> or
                     <code nobreak="false">$isbn-index("0470192747")</code>.</p><p>In this simple form, this replicates the functionality available using
                     <elcode>xsl:key</elcode> and the <function>key</function> function. However, it
                  also provides capabilities not directly available using the
                     <function>key</function> function: for example, the index can include
                     <code nobreak="false">book</code> elements in multiple source documents. It also allows
                  processing of all the books using a construct such as <code nobreak="false">&lt;xsl:for-each
                     select="map:keys($isbn-index)"&gt;</code></p></example><example id="map-as-class"><head>A Map containing Named Functions</head><p>As in JavaScript, a map whose keys are strings and whose associated values are
                  function items can be used in a similar way to a class in object-oriented
                  programming languages.</p><p>Suppose an application needs to handle customer order information that may arrive
                  in three different formats, with different hierarchic arrangements:</p><olist><item><p>Flat structure:</p><eg role="xml" xml:space="preserve">
&lt;customer id="c123"&gt;...&lt;/customer&gt;
&lt;product id="p789"&gt;...&lt;/product&gt;
&lt;order customer="c123" product="p789"&gt;...&lt;/order&gt;</eg></item><item><p>Orders within customer elements:</p><eg role="xml" xml:space="preserve">
&lt;customer id="c123"&gt;
   &lt;order product="p789"&gt;...&lt;/order&gt;
&lt;/customer&gt;
&lt;product id="p789"&gt;...&lt;/product&gt;</eg></item><item><p>Orders within product elements:</p><eg role="xml" xml:space="preserve">
&lt;customer id="c123"&gt;...&lt;/customer&gt;
&lt;product id="p789"&gt;
  &lt;order customer="c123"&gt;...&lt;/order&gt;
&lt;/product&gt;</eg></item></olist><p>An application can isolate itself from these differences by defining a set of
                  functions to navigate the relationships between customers, orders, and products:
                     <code nobreak="false">orders-for-customer</code>, <code nobreak="false">orders-for-product</code>,
                     <code nobreak="false">customer-for-order</code>, <code nobreak="false">product-for-order</code>. These
                  functions can be implemented in different ways for the three different input
                  formats. For example, with the first format the implementation might be:</p><eg role="xslt-declaration" xml:space="preserve">
&lt;xsl:variable name="flat-input-functions" as="map(xs:string, fn(*))*"
  select="{
            'orders-for-customer' : 
                 fn($c as element(customer)) as element(order)* 
                    { $c/../order[@customer = $c/@id] },
            'orders-for-product' : 
                 fn($p as element(product)) as element(order)* 
                    { $p/../order[@product = $p/@id] },
            'customer-for-order' : 
                 fn($o as element(order)) as element(customer) 
                    { $o/../customer[@id = $o/@customer] },
            'product-for-order' : 
                 fn($o as element(order)) as element(product) 
                    { $o/../product[@id = $o/@product] } }
         "/&gt;</eg><p>Having established which input format is in use, the application can bind the
                  appropriate implementation of these functions to a variable such as
                     <code nobreak="false">$input-navigator</code>, and can then process the input using XPath
                  expressions such as the following, which selects all products for which there is
                  no order: <code nobreak="false">//product[empty($input-navigator("orders-for-product")(.))]</code>
               </p></example></div2></div1><div1 id="arrays"><head>Arrays</head><p>Arrays are defined in the XDM Data Model: see <xspecref spec="DM40" ref="array-items"/>.</p><div2 id="array-construction"><head>Array Construction</head><changes><change issue="113 2007" PR="406" date="2023-03-30">
                  The new instruction <elcode>xsl:array</elcode> is introduced
                  to allow construction of arrays.
               </change></changes><p>The instruction <elcode>xsl:array</elcode> constructs and returns a new array.</p><e:element-syntax xmlns:e="http://www.w3.org/1999/XSL/Spec/ElementSyntax" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" name="array">
      <e:in-category name="instruction"/>
      <e:attribute name="for-each" required="no">
         <e:data-type name="expression"/>
      </e:attribute>
      <e:attribute name="select" required="no">
         <e:data-type name="expression"/>
      </e:attribute>
      <e:model name="sequence-constructor"/>
      <e:allowed-parents>
         <e:parent-category name="sequence-constructor"/>
      </e:allowed-parents>
   </e:element-syntax><e:element-syntax xmlns:e="http://www.w3.org/1999/XSL/Spec/ElementSyntax" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" name="array-member">
      <e:in-category name="instruction"/>
      <e:attribute name="select" required="no">
         <e:data-type name="expression"/>
      </e:attribute>
      <e:model name="sequence-constructor"/>
      <e:allowed-parents>
         <e:parent-category name="sequence-constructor"/>
      </e:allowed-parents>
   </e:element-syntax><p>There are three typical ways an array might be constructed.</p><olist><item><p>An array whose members are all single items can be constructed using
                  an instruction such as:</p><eg xml:space="preserve">&lt;xsl:array select="'Mon', 'Tues', 'Weds', 'Thurs', 'Fri'"/&gt;</eg><p>This constructs an array of five strings: <code nobreak="false">['Mon', 'Tues', "Weds', "Thurs', 'Fri']</code></p><p>The values, of course, do not need to be literals.</p></item><item><p>An array whose members can be computed by applying a mapping to a sequence of items 
                     can be constructed using
                  an instruction such as:</p><eg xml:space="preserve">&lt;xsl:array for-each="'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday'"
       select="(., substring(., 1, 3))"/&gt;</eg><p>This constructs an array with five members, each being a sequence of two
                     strings: <code nobreak="false">[('Monday', 'Mon'), ('Tuesday', 'Tue'), ('Wednesday', 'Wed'), ('Thursday', 'Thu'), ('Friday', 'Fri')]</code></p><p>A more complex example might be:</p><eg xml:space="preserve">&lt;xsl:array for-each="unparsed-text-lines('data.txt')" select="tokenize(.)"/&gt;</eg><p>which creates an array with one member for each line of an input file, the relevant member
                  being a sequence of words appearing on that line.</p></item><item>An array with arbitrary content, that cannot readily be derived algorithmically
               from the items in a sequence. For example:</item><eg xml:space="preserve">&lt;xsl:array&gt;
   &lt;xsl:array-member select="1"/&gt;
   &lt;xsl:array-member select="1, 2"/&gt;
   &lt;xsl:array-member select="1, 3"/&gt;
   &lt;xsl:array-member select="1, 2, 4"/&gt;
   &lt;xsl:array-member select="1, 5"/&gt;
   &lt;xsl:array-member select="1, 2, 3, 6"/&gt;
   &lt;xsl:array-member select="1, 7"/&gt;
   &lt;xsl:array-member select="1, 2, 4, 8"/&gt;
   &lt;xsl:array-member select="1, 3, 9"/&gt;
   &lt;xsl:array-member select="1, 2, 5, 10"/&gt;
   &lt;xsl:array-member select="1, 11"/&gt;
   &lt;xsl:array-member select="1, 2, 3, 4, 6, 12"/&gt;
&lt;/xsl:array&gt;</eg><p>This returns an array of twelve members, each being a sequence of integers, for example the last
               member is the sequence <code nobreak="false">(1, 2, 3, 4, 6, 12)</code>.</p><p>Another example might be:</p><eg xml:space="preserve">&lt;xsl:array&gt;
   &lt;xsl:for-each-group select="1 to 10" split-when="$next mod 5 lt $next mod 3"&gt;
     &lt;xsl:array-member select="current-group()"/&gt;
   &lt;/xsl:for-each-group&gt;
&lt;/xsl:array&gt;</eg><p>This returns the array <code nobreak="false">[ (1, 2, 3, 4), (5, 6, 7, 8, 9), 10 ]</code>.</p></olist><p>The detailed rules follow.</p><olist><item><p>In these rules, the term <term>parcel</term> denotes a function item
               with arity zero having an implementation-defined 
                  <xtermref spec="DM40" ref="dt-function-annotation">function annotation</xtermref> that identifies
               it as having been constructed by the <elcode>xsl:array-member</elcode> instruction.
               The implementation-defined function annotation should use a reserved namespace such
               that functions with this annotation can be created only by using the
               <elcode>xsl:array-member</elcode> instruction.</p><p>A parcel encapsulates a value,
               which may be any sequence; the value of the parcel is the result of calling the
               corresponding function item with no arguments.</p></item><item><p>The effect of the <elcode>xsl:array-member</elcode> instruction is to return
               a <term>parcel</term> that encapsulates the sequence obtained by evaluating its
               <code nobreak="false">select</code> attribute or its contained sequence constructor.</p></item><item><p>The <elcode>xsl:array</elcode> instruction is evaluated as follows.</p></item><item><p>If the <code nobreak="false">for-each</code> attribute is absent, then:</p><olist><item><p>Let <var>S</var> be the sequence that results from
                     evaluation of the <code nobreak="false">select</code> expression or the contained
                     sequence constructor.</p></item><item><p>The result of the <elcode>xsl:array</elcode> instruction is
                     an array having one member for each item <var>S/i</var> in <var>S</var>,
                        retaining order:
                        <ulist><item><p>If <var>S/i</var> is a <term>parcel</term>, then
                           the array member is the value encapsulated by the parcel (which may
                           be any sequence).</p></item><item><p>Otherwise,
                           the array member is the singleton item <var>S/i</var>.</p></item></ulist>
                     </p></item></olist></item><item><p>If the <code nobreak="false">for-each</code> attribute is present, then:</p><olist><item><p>Let <var>F</var> = <var>F/1</var>, <var>F/2</var>, ..., <var>F/n</var>
                        be the sequence that results from evaluation
                     of the <code nobreak="false">for-each</code> attribute.</p></item><item><p>The resulting array contains one member for each item in <var>F</var>,
                     retaining order.</p></item><item><p>The member corresponding to a particular item <var>F/i</var> is
                     as follows:</p><olist><item><p>Let <var>S</var> be the result of evaluating the <code nobreak="false">select</code> expression 
                           or the contained sequence constructor with a <termref def="dt-focus"/>
                     in which the <termref def="dt-context-item"/> is <var>F/i</var>, the <termref def="dt-context-position"/>
                     is <var>i</var> (the 1-based position of <var>F/i</var> within <var>F</var>), 
                           and the <termref def="dt-context-size"/>
                     is <var>n</var> (the number of items in <var>F</var>). </p></item><item><p>If <var>S</var> contains a single item and that item is a <term>parcel</term>, 
                        then the array member is the value encapsulated by the parcel.</p></item><item><p>If <var>S</var> contains multiple items and one of those items is a <term>parcel</term>,
                        then a dynamic error is raised:</p><p><error spec="XT" type="dynamic" class="DE" code="4060"><p>It 
                           is a <termref def="dt-dynamic-error"/> if an <elcode>xsl:array</elcode>
                        instruction with a <code nobreak="false">for-each</code> attribute includes items constructed
                        using an <elcode>xsl:array-member</elcode> instruction mixed (in the same array member)
                        with items not so constructed.</p></error></p></item><item>Otherwise, the array member is the sequence <var>S</var>.</item></olist><note><p>When the <code nobreak="false">for-each</code> attribute is present, then it is not necessary
                        to use the <code nobreak="false">xsl:array-member</code> instruction, since each evaluation
                        of the <code nobreak="false">select</code> attribute or the containing sequence constructor
                        generates one array member. However, use of <code nobreak="false">xsl:array-member</code>
                        to construct the array member is permitted, provided that it constructs
                        the entire array member and not an individual item within it.</p></note></item></olist></item></olist><note><p>The content of an array is effectively a sequence of sequences, which the XDM data
            model cannot represent directly. Representing an array member as a <term>parcel</term> 
               (technically, a zero-arity function) provides
            a convenient workaround.</p><p><emph>As a general rule, <elcode>xsl:array-member</elcode> should be used
               if and only if the <code nobreak="false">select</code> and <code nobreak="false">for-each</code> attributes
               of <code nobreak="false">xsl:array</code> are both absent.</emph></p></note><p>If the <elcode>xsl:array</elcode> instruction has a <code nobreak="false">select</code> attribute then
            the sequence constructor must be empty, except for any <elcode>xsl:fallback</elcode> instructions
            (which an XSLT 4.0 processor ignores) <errorref spec="XT" class="SE" code="3185"/>.</p><p>If the <elcode>xsl:array-member</elcode> instruction has a <code nobreak="false">select</code> attribute then
            the sequence constructor must be empty, except for any <elcode>xsl:fallback</elcode> instructions
            (which an XSLT 4.0 processor ignores) <errorref spec="XT" class="SE" code="3185"/>.</p><example><head>Constructing an array whose members are single items</head><p>The following example constructs the array <code nobreak="false">[1, 2, 3, 4, 5]</code>:</p><eg xml:space="preserve">&lt;xsl:array select="1 to 5"/&gt;</eg><p>The following example constructs an array of text nodes:</p><eg xml:space="preserve">&lt;xsl:array select=".//text()"/&gt;</eg><p>The following example constructs an array by tokenizing a string:</p><eg xml:space="preserve">&lt;xsl:array select="tokenize('The cat sat on the mat')"/&gt;</eg><p>The result is the array <code nobreak="false">[ "The", "cat", "sat", "on", "the", "mat" ]</code>.</p><p>The following example constructs an array containing items computed using nested instructions:</p><eg xml:space="preserve">&lt;xsl:array&gt;
   &lt;xsl:for-each-group select="0 to 19" group-adjacent=". idiv 4"&gt;
     &lt;xsl:sequence select="string-join(current-group(), '-')"/&gt;
   &lt;/xsl:for-each-group&gt;
&lt;/xsl:array&gt;</eg><p>The result is the array <code nobreak="false">[ "0-1-2-3", "4-5-6-7", "8-9-10-11", "12-13-14-15", "16-17-18-19" ]</code>.</p><p>Note that in this last example, the <elcode>xsl:array-member</elcode> instruction could be used
               in place of <code nobreak="false">xsl:sequence</code>.</p></example><example><head>Constructing an array whose members are derived from the items in an input sequence</head><p>The following example constructs an array whose members are sequences:</p><eg xml:space="preserve">&lt;xsl:array for-each="para" select="distinct-values(tokenize(.))"/&gt;</eg><p>This returns an array with one member for each child paragraph, the content
               of the array member being the list of distinct words appearing in that paragraph.</p><p>The following example constructs an array in which the members are obtained
               by applying templates to the children of the context item:</p><eg xml:space="preserve">&lt;xsl:array for-each="*"&gt;                 
   &lt;xsl:apply-templates select="."/&gt;
&lt;/xsl:array&gt;</eg></example><example><head>Constructing a heterogeneous array</head><p>The following example constructs a heterogeneous array containing a number
               of properties of a supplied node, some of which are sequence-valued:</p><eg xml:space="preserve">&lt;xsl:array&gt;
     &lt;xsl:array-member select="local-name($node)"/&gt;
     &lt;xsl:array-member select="namespace-uri($node)"/&gt;
     &lt;xsl:array-member select="base-uri($node)"/&gt;
     &lt;xsl:array-member select="$node/namespace::*/string()"/&gt;
     &lt;xsl:array-member select="$node/@*/string()"/&gt;  
&lt;/xsl:array&gt;</eg><p>When applied to an input element such as</p><eg xml:space="preserve">&lt;e xmlns="http://example.com/ns" xml:base="http://example.com/loc" x="2"/&gt;</eg><p>the result would be the array:</p><eg xml:space="preserve">["e", 
 "http://example.com/ns", 
 "http://example.com/loc", 
 ("http://example.com/ns", "http://www.w3.org/XML/1998/namespace"),
 ("http://example.com/loc", "2")
]</eg></example><example><head>Constructing nested arrays</head><p>The <elcode>xsl:array</elcode> instruction can be nested. For example:</p><eg xml:space="preserve">&lt;xsl:array for-each="1 to 4"&gt;
   &lt;xsl:array select="(.*10 to .*10 + 2)"/&gt;
&lt;/xsl:array&gt;</eg><p>The result is <code nobreak="false">[ [ 10, 11, 12], [ 20, 21, 22 ], [ 30, 31, 32 ], [ 40, 41, 42 ] ]</code>.</p></example><example><head>Constructing arrays using template rules</head><p>Given a book containing chapters which in turn contain sections, the following code
               produces a nested array representing the (crude) word counts of the sections
               within each chapter:</p><eg xml:space="preserve">&lt;xsl:mode name="word-counts" on-no-match="shallow-skip"&gt;   
    &lt;xsl:template match="book"&gt;
        &lt;xsl:array&gt;
            &lt;xsl:apply-templates/&gt;
        &lt;/xsl:array&gt;
    &lt;/xsl:template&gt;
    &lt;xsl:template match="chapter"&gt;
        &lt;xsl:array&gt;
           &lt;xsl:apply-templates/&gt;
        &lt;/xsl:array&gt;   
    &lt;/xsl:template&gt;
    &lt;xsl:template match="section"&gt;
        &lt;xsl:sequence select="tokenize(.) =&gt; count()"/&gt;
    &lt;/xsl:template&gt;
&lt;/xsl:mode&gt;</eg><p>The result might be an array of the form <code nobreak="false">[[842, 316], [450, 217], ...]</code>
               indicating that the first section of the second chapter has a word count of 450.</p></example><example><head>Constructing an array based on an existing array</head><p>The <elcode>xsl:array</elcode> instruction can be used in conjunction with
               the <xfunction>array:members</xfunction> function to construct an array from the members
               of an existing array. For example, the following code combines two arrays <code nobreak="false">$A1</code>
                  and <code nobreak="false">$A2</code>, and sorts the result:</p><eg xml:space="preserve">&lt;xsl:array 
   for-each="(array:members($A1), array:members($A2)) =&gt; sort(fn{count(?value)})"
   select="?value"/&gt;</eg><p>The following code transposes a regular nested array (such as <code nobreak="false">[ [ 1, 2, 3 ], [ 4, 5, 6 ], [ 7, 8, 9 ] ]</code>)
               so the result is organized by columns rather than rows (<code nobreak="false">[ [ 1, 4, 7 ], [ 2, 5, 8 ], [ 3, 6, 9 ] ]</code>):</p><eg xml:space="preserve">&lt;xsl:array for-each="1 to array:size($input?1)"&gt;
   &lt;xsl:variable name="index" select="."/&gt;
   &lt;xsl:array select="$input/*[$index]"/&gt;
&lt;/xsl:array&gt;</eg></example></div2><div2 id="arrays-streaming"><head>Arrays and Streaming</head><p>As with maps (see <xspecref spec="SG40" ref="maps-streaming"/>) arrays cannot contain references to 
               <termref def="dt-streamed-node">streamed nodes</termref>, because all expressions, instructions,
            and functions that construct arrays are defined to have operand usage <xtermref spec="SG40" ref="dt-navigation"/>.</p><p>Unlike maps, array constructors have no special rules allowing the members of the array
            to be constructed using multiple consuming subexpressions.</p></div2></div1><div1 id="diagnostics"><head>Diagnostics</head><div2 id="message"><head>Messages</head><e:element-syntax xmlns:e="http://www.w3.org/1999/XSL/Spec/ElementSyntax" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" name="message">
      <e:in-category name="instruction"/>
      <e:attribute name="select">
         <e:data-type name="expression"/>
      </e:attribute>
      <e:attribute name="terminate" default="'no'">
         <e:attribute-value-template>
            <e:data-type name="boolean"/>
         </e:attribute-value-template>
      </e:attribute>
      <e:attribute name="error-code" default="'Q{http://www.w3.org/2005/xqt-errors}XTMM9000'">
         <e:attribute-value-template>
            <e:data-type name="eqname"/>
         </e:attribute-value-template>
      </e:attribute>
      <e:model name="sequence-constructor"/>
      <e:allowed-parents>
         <e:parent-category name="sequence-constructor"/>
      </e:allowed-parents>
   </e:element-syntax><p>The <elcode>xsl:message</elcode> instruction sends a message in an <termref def="dt-implementation-defined">implementation-defined</termref> way. The
                  <elcode>xsl:message</elcode> instruction causes the creation of a new document,
               which is typically serialized and output to an <termref def="dt-implementation-defined">implementation-defined</termref> destination. The
               result of the <elcode>xsl:message</elcode> instruction is the empty sequence.</p><p>The content of the message may be specified by using either or both of the optional
                  <code nobreak="false">select</code> attribute and the <termref def="dt-sequence-constructor">sequence constructor</termref> that forms the content of the
                  <elcode>xsl:message</elcode> instruction.</p><p>If the <elcode>xsl:message</elcode> instruction contains a <termref def="dt-sequence-constructor">sequence constructor</termref>, then the sequence
               obtained by evaluating this sequence constructor is used to construct the content of
               the new document node, as described in <specref ref="constructing-complex-content"/>.</p><p>If the <elcode>xsl:message</elcode> instruction has a <code nobreak="false">select</code> attribute,
               then the value of the attribute <rfc2119>must</rfc2119> be an XPath expression. The
               effect of the <elcode>xsl:message</elcode> instruction is then the same as if a
               single <elcode>xsl:copy-of</elcode> instruction with this <code nobreak="false">select</code>
               attribute were added to the start of the <termref def="dt-sequence-constructor">sequence constructor</termref>.</p><p>If the <elcode>xsl:message</elcode> instruction has no content and no
                  <code nobreak="false">select</code> attribute, then an empty message is produced.</p><imp-def-feature id="idf-err-messageformat">The destination and formatting of messages
               written using the <elcode>xsl:message</elcode> instruction are <termref def="dt-implementation-defined"/>.</imp-def-feature><p>The tree produced by the <elcode>xsl:message</elcode> instruction is not technically
               a <termref def="dt-final-result-tree">final result tree</termref>. The tree has no
               URI and processors are not <rfc2119>required</rfc2119> to make the tree accessible to
               applications.</p><note><p>In many cases, the XML document produced using <elcode>xsl:message</elcode> will
                  consist of a document node owning a single text node. However, it may contain a
                  more complex structure.</p></note><note><p>An implementation might implement <elcode>xsl:message</elcode> by popping up an
                  alert box or by writing to a log file. Because the order of execution of
                  instructions is implementation-defined, the order in which such messages appear is
                  not predictable.</p></note><p>The <code nobreak="false">terminate</code> attribute is interpreted as an <termref def="dt-attribute-value-template">attribute value template</termref>.</p><p>If the <termref def="dt-effective-value"/> of the
                  <code nobreak="false">terminate</code> attribute is <code nobreak="false">yes</code>, then the <termref def="dt-processor">processor</termref>
               <rfc2119>must</rfc2119>
               raise a <termref def="dt-dynamic-error"> dynamic error</termref> after
               sending the message. This error may be caught in the same
                  way as any other dynamic error using <elcode>xsl:catch</elcode>. The
               default value is <code nobreak="false">no</code>. Note that because the order of evaluation of
               instructions is <termref def="dt-implementation-dependent">implementation-dependent</termref>, this gives no guarantee that any particular
               instruction will or will not be evaluated before processing terminates.</p><p>The optional <code nobreak="false">error-code</code> attribute 
               (also interpreted as an <termref def="dt-attribute-value-template"/>)
               may be used to indicate the error code
               associated with the message. This may be used irrespective of the value of
                  <code nobreak="false">terminate</code>. The 
               <termref def="dt-effective-value"/> of the 
               error code attribute is expected to be an <termref def="dt-eqname">EQName</termref>. If no error code is specified, or if
               the <termref def="dt-effective-value"/> is not a valid EQName, the error code will have local part
                  <code nobreak="false">XTMM9000</code> and namespace URI
                  <code nobreak="false">http://www.w3.org/2005/xqt-errors</code>. User-defined error codes
                  <rfc2119>should</rfc2119> be in a namespace other than
                  <code nobreak="false">http://www.w3.org/2005/xqt-errors</code>. When the value of
                  <code nobreak="false">terminate</code> is <code nobreak="false">yes</code>, the error code may be matched in an
                  <elcode>xsl:catch</elcode> element to catch the error and cause processing to
               continue normally.</p><note><p>XPath 4.0 allows an <termref def="dt-eqname">EQName</termref> to include
            both a prefix and a URI, for example <code nobreak="false">error-code="{http://example.com/ns}my:error-code"</code>.</p></note><p>
               <error spec="XT" type="dynamic" class="MM" code="9000"><p>When a transformation is terminated by use of <code nobreak="false">&lt;xsl:message
                        terminate="yes"/&gt;</code>, the effect is the same as when a <termref def="dt-dynamic-error">
                        dynamic error</termref> occurs during the transformation. The default error code is <code nobreak="false">XTMM9000</code>; this may be
                        overridden using the <code nobreak="false">error-code</code> attribute of the
                           <elcode>xsl:message</elcode> instruction.</p></error>
            </p><example><head>Localizing Messages</head><p>One convenient way to do localization is to put the localized information (message
                  text, etc.) in an XML document, which becomes an additional input file to the
                     <termref def="dt-stylesheet">stylesheet</termref>. For example, suppose
                  messages for a language <code nobreak="false">
                     <var>L</var>
                  </code> are stored in an XML file <code nobreak="false">resources/<var>L</var>.xml</code> in the
                  form:</p><eg role="xml" xml:space="preserve">&lt;messages&gt;
  &lt;message name="problem"&gt;A problem was detected.&lt;/message&gt;
  &lt;message name="error"&gt;An error was detected.&lt;/message&gt;
&lt;/messages&gt;
</eg><p>Then a stylesheet could use the following approach to localize messages:</p><eg role="xslt-declarations" xml:space="preserve">&lt;xsl:param name="lang" select="'en'"/&gt;
&lt;xsl:variable name="messages"
  select="document(concat('resources/', $lang, '.xml'))/messages"/&gt;

&lt;xsl:template name="localized-message"&gt;
  &lt;xsl:param name="name"/&gt;
  &lt;xsl:message select="string($messages/message[@name=$name])"/&gt;
&lt;/xsl:template&gt;

&lt;xsl:template name="problem"&gt;
  &lt;xsl:call-template name="localized-message"&gt;
    &lt;xsl:with-param name="name"&gt;problem&lt;/xsl:with-param&gt;
  &lt;/xsl:call-template&gt;
&lt;/xsl:template&gt;</eg></example><p>Any <termref def="dt-dynamic-error">dynamic error</termref> that occurs while
               evaluating the <code nobreak="false">select</code> expression or the contained <termref def="dt-sequence-constructor">sequence constructor</termref>, and any <termref def="dt-serialization-error">serialization error</termref> that occurs while
               processing the result, does not cause the transformation to
                  fail; at worst, it means that no message is output, or that the only message that
                  is output is one that relates to the error that occurred.</p><note><p>An example of such an error is the serialization error that occurs when processing
                  the instruction <code nobreak="false">&lt;xsl:message select="@code"/&gt;</code> (on the grounds
                  that free-standing attributes cannot be serialized). Making such errors
                  recoverable means that it is implementation-defined whether or not they are
                  raised to the user and whether they cause termination of the transformation. If
                  the processor chooses to recover from the error, the content of any resulting
                  message is implementation-dependent.</p><p>One possible recovery action is to include a description of the error in the
                  generated message text.</p></note></div2><div2 id="assertions"><head>Assertions</head><p>The <elcode>xsl:assert</elcode> instruction is used to assert that the value of a
               particular expression is <code nobreak="false">true</code>; if the value of the expression is <code nobreak="false">false</code>, and
               assertions are enabled, then a dynamic error occurs.</p><e:element-syntax xmlns:e="http://www.w3.org/1999/XSL/Spec/ElementSyntax" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" name="assert">
      <e:in-category name="instruction"/>
      <e:attribute name="test" required="yes">
         <e:data-type name="expression"/>
      </e:attribute>
      <e:attribute name="select">
         <e:data-type name="expression"/>
      </e:attribute>
      <e:attribute name="error-code" default="'Q{http://www.w3.org/2005/xqt-errors}XTMM9001'">
         <e:attribute-value-template>
            <e:data-type name="eqname"/>
         </e:attribute-value-template>
      </e:attribute>
      <e:model name="sequence-constructor"/>
      <e:allowed-parents>
         <e:parent-category name="sequence-constructor"/>
      </e:allowed-parents>
   </e:element-syntax><p>By default, assertions are disabled.</p><p>An implementation <rfc2119>must</rfc2119> provide an external mechanism to enable or
               disable assertion checking. This may work either statically or dynamically, and may
               be at the level of the stylesheet as a whole, or at the level of an individual
               package, or otherwise. The detail of such mechanisms is <termref def="dt-implementation-defined"/>.</p><imp-def-feature id="idf-api-enablingassertions">The detail of any external mechanism
               allowing a processor to enable or disable checking of assertions is <termref def="dt-implementation-defined"/>.</imp-def-feature><p>If assertion checking is enabled, the instruction is evaluated as follows:</p><olist><item><p>The expression in the <code nobreak="false">test</code> attribute is evaluated. If the
                     effective boolean value of the result is <code nobreak="false">true</code>, the assertion
                     succeeds, and no further action is taken. If the effective boolean value is
                     <code nobreak="false">false</code>, or if a dynamic error occurs during evaluation of the expression, then
                     the assertion fails.</p></item><item><p>If the assertion fails, then the effect of the instruction is governed by the
                     rules for evaluation of an <elcode>xsl:message</elcode> instruction with the
                     same <code nobreak="false">select</code> attribute, <code nobreak="false">error-code</code> attribute, and
                     contained <termref def="dt-sequence-constructor"/>, and with the value
                        <code nobreak="false">terminate="yes"</code>. However, the default error code if the
                        <code nobreak="false">error-code</code> attribute is omitted is <code nobreak="false">XTMM9001</code> rather
                     than <code nobreak="false">XTMM9000</code>.</p><note><p>To the extent that the behavior of <elcode>xsl:message</elcode> is <termref def="dt-implementation-defined"/>, this rule does not prevent an
                        implementation treating <elcode>xsl:assert</elcode> and
                           <elcode>xsl:message</elcode> differently.</p></note><note><p>If evaluation of the <code nobreak="false">test</code> expression
                        fails with a dynamic error, the effect is exactly the same as if the
                        evaluation returns <code nobreak="false">false</code>, including the fact that the
                        instruction fails with error code <code nobreak="false">XTMM9001</code>.</p></note></item><item><p>If an assertion fails, then the following sibling
                     instructions of the <elcode>xsl:assert</elcode> instruction are not
                     evaluated.</p><note><p>This means that <elcode>xsl:assert</elcode> can
                        be used (rather like <elcode>xsl:if</elcode> and
                        <elcode>xsl:choose</elcode>) to prevent subsequent instructions from
                        executing if a particular precondition is not true, which might be useful if
                        the subsequent instructions have side-effects (for example, by calling
                        extension functions) or if they can fail in uncatchable ways (for example,
                        non-terminating recursion). It is worth noting that there are limits to this
                        guarantee. It does not ensure, for example, that when an assertion within a
                        template fails, the following siblings of the
                           <elcode>xsl:call-template</elcode> instruction that invokes that template
                        will not be evaluated; nor does it ensure that if an assertion fails while
                        processing the first item of a sequence using <elcode>xsl:for-each</elcode>,
                        then subsequent items in the sequence will not be processed. </p></note></item></olist><p>
               <error spec="XT" type="dynamic" class="MM" code="9001"><p>When a transformation is terminated by use of <elcode>xsl:assert</elcode>, the
                     effect is the same as when a <termref def="dt-dynamic-error"> dynamic error</termref> occurs during the
                     transformation. The default error code is <code nobreak="false">XTMM9001</code>; this may be
                     overridden using the <code nobreak="false">error-code</code> attribute of the
                        <elcode>xsl:assert</elcode> instruction.</p></error>
            </p><p>As with any other dynamic error, an error caused by an assertion failing may be
               trapped using <elcode>xsl:try</elcode>: see <specref ref="try-catch"/>.</p><p>The result of the <elcode>xsl:assert</elcode> instruction is the empty sequence.</p><example><head>Using Assertions with Static Parameters</head><p>The following example shows a stylesheet function that checks that the value of
                  its supplied argument is in range. The check is performed only if the <termref def="dt-static-parameter"/>
                  <code nobreak="false">$DEBUG</code> is set to <code nobreak="false">true</code>.</p><eg role="xslt-declarations" xml:space="preserve">
&lt;xsl:param name="DEBUG" as="xs:boolean" select="false()" 
           static="yes" required="no"/&gt;
&lt;xsl:function name="f:days-elapsed" as="xs:integer"&gt;
  &lt;xsl:param name="date" as="xs:date"/&gt;
  &lt;xsl:assert use-when="$DEBUG" test="$date lt current-date()"/&gt;
  &lt;xsl:sequence select="(current-date() - $since) 
                            div xs:dayTimeDuration('PT1D')"/&gt;
&lt;/xsl:function&gt;</eg></example><note><p>Implementations should avoid optimizing <elcode>xsl:assert</elcode> instructions
                  away. As a guideline, if the result of a sequence constructor is required by the
                  transformation, the implementation should ensure that all
                     <elcode>xsl:assert</elcode> instructions in that sequence constructor are
                  evaluated. Conversely, if the result of a sequence constructor is not required by
                  the transformation, its <elcode>xsl:assert</elcode> instructions should not be
                  evaluated.</p><p>This guidance is not intended to prevent optimizations such as lazy
                  evaluation, where evaluation of a sequence constructor may finish early, as soon
                  as enough information is available to evaluate the containing instruction.</p></note><p>An implementation <rfc2119>may</rfc2119> provide a user option allowing a processor
               to treat assertions as being true without explicit checking. This option
                  <rfc2119>must not</rfc2119> be enabled by default. If such an option is in force,
               the effect of any assertion not being true is <termref def="dt-implementation-dependent"/>.</p><note><p>For example, given the assertion <code nobreak="false">&lt;xsl:assert
                     test="count(//title)=1"/&gt;</code>, a processor might generate code for the
                  expression <code nobreak="false">&lt;xsl:value-of select="//title"/&gt;</code> that stops searching
                  for <code nobreak="false">title</code> elements after finding the first one. In the event that the
                  source document contains more than one <code nobreak="false">title</code>, execution of the
                  stylesheet may fail in arbitrary ways, or it may produce incorrect output.</p></note></div2></div1><div1 id="extension"><head>Extensibility and Fallback</head><changes><change date="2022-01-01">
               Functions that accept a lexical QName as an argument, such as <function>key</function>,
               <function>function-available</function>, <function>element-available</function>,
               <function>type-available</function>, <function>system-property</function>,
               <function>accumulator-before</function>, and <function>accumulator-after</function>,
               now have the option of supplying an <code nobreak="false">xs:QName</code> value instead.
               [This change was in the editor's draft accepted by the WG as its baseline when
               it started work.]
            </change></changes><p>XSLT allows three kinds of extension: extension attributes, extension instructions, 
            and extension functions.</p><p>
            <termdef id="dt-extension-attribute" term="extension attribute">An <term>extension attribute</term>
               is an attribute appearing on an <termref def="dt-xslt-element"/>, where the name
               of the attribute is in a non-null namespace other than the <termref def="dt-xslt-namespace"/>.</termdef>
         </p><p>
            <termdef id="dt-extension-instruction" term="extension instruction">An <term>extension
                  instruction</term> is an element within a <termref def="dt-sequence-constructor">sequence constructor</termref> that is in a namespace (not the <termref def="dt-xslt-namespace">XSLT namespace</termref>) designated as an extension
               namespace.</termdef>
         </p><p>
            <termdef id="dt-extension-function" term="extension function">An <term>extension
               function</term> is a named function introduced to the static or dynamic context 
               by mechanisms outside the scope of this specification.</termdef></p><p>This specification does not define any mechanism for creating or binding implementations
            of <termref def="dt-extension-attribute">extension attributes</termref>,
            <termref def="dt-extension-instruction">extension instructions</termref>,
            or <termref def="dt-extension-function">extension functions</termref>, and it is not
               <rfc2119>required</rfc2119> that implementations support any such mechanism. Such
            mechanisms, if they exist, are <termref def="dt-implementation-defined">implementation-defined</termref>. Therefore, an XSLT stylesheet that must be
            portable between XSLT implementations cannot rely on particular extensions being
            available. XSLT provides mechanisms that allow an XSLT stylesheet to determine whether
            the implementation makes particular extensions available, and to specify what happens if
            those extensions are not available. If an XSLT stylesheet is careful to make use of
            these mechanisms, it is possible for it to take advantage of extensions and still retain
            portability.</p><p>
            <error spec="XT" type="static" class="SE" code="0085"><p>It is a <termref def="dt-static-error"/> to use a <termref def="dt-reserved-namespace"/>
                  in the name of any <termref def="dt-extension-attribute"/>, 
                  <termref def="dt-extension-function"/>, or <termref def="dt-extension-instruction"/>,
                  other than a function or instruction defined in this specification or in a normatively 
                  referenced specification. It is a <termref def="dt-static-error"/> to use a prefix bound 
                  to a reserved namespace in the <code nobreak="false">[xsl:]extension-element-prefixes</code> attribute.
               </p></error>
         </p><div2 id="extension-attributes"><head>Extension Attributes</head><changes><change issue="2276" PR="2283" date="2025-11-12">The conformance requirements for extension
                  attributes have been relaxed: the requirement to maintain strict conformance
               to the specification in the presence of extension attributes is now a <rfc2119>should</rfc2119>
               rather than a <rfc2119>must</rfc2119>, and extension attributes are allowed to modify
               the form of serialized output without limitation.</change></changes><p>
               An element from the
                  XSLT namespace may have any attribute not from the XSLT namespace, provided that
                  the <termref def="dt-expanded-qname">expanded QName</termref> (see <bibref ref="xpath-40"/>) 
               of the attribute has a non-null namespace URI. These
                  attributes are referred to as <termref def="dt-extension-attribute">extension attributes</termref>.</p><p>It is not necessary to declare the namespace used for an extension attribute using
            <code nobreak="false">[xsl:]extension-element-prefixes</code> or otherwise.</p><p>The presence of an extension attribute <rfc2119>should not</rfc2119> 
               cause the <termref def="dt-principal-result"/> or any <termref def="dt-secondary-result"/> 
               of the transformation to be different from the results
                that a conformant XSLT 4.0
               processor might produce. They <rfc2119>should not</rfc2119> cause the processor to fail
               to raise an error that a conformant processor is required to raise. This means that
               an extension attribute <rfc2119>should not</rfc2119> change the effect of any 
               <termref def="dt-instruction">instruction</termref> except to the extent that the effect is
                  <termref def="dt-implementation-defined">implementation-defined</termref> or
                  <termref def="dt-implementation-dependent">implementation-dependent</termref>.</p><p>A processor <rfc2119>may</rfc2119> make an exception to the above rule in certain cases, for
            example:</p><ulist><item><p>To allow the user to opt out of some provision in the specification that has
               undesirable performance implications (for example, the requirement that functions like
               <xfunction>doc</xfunction> and <xfunction>collection</xfunction> be deterministic).</p></item><item><p>To enable interoperability with third-party software that is not otherwise
               achievable.</p></item><item><p>To allow the user to disable functionality for security reasons.</p></item></ulist><p>Extension attributes <rfc2119>may</rfc2119> change the form of serialized output
               in a way that overrides the provisions of <bibref ref="xslt-xquery-serialization-40"/>, 
               including the suppression of error conditions defined in that specification.</p><note><p>
                  <termref def="dt-extension-attribute">Extension attributes</termref> may be used
                  to modify the behavior of <termref def="dt-extension-function">extension
                     functions</termref> and <termref def="dt-extension-instruction">extension
                     instructions</termref>. They may be used to select processing options in cases
                  where the specification leaves the behavior 
                  <termref def="dt-implementation-defined">implementation-defined</termref> 
                  or <termref def="dt-implementation-dependent">implementation-dependent</termref>. They may
                  also be used for optimization hints, for diagnostics, or for documentation.</p><p>
                  <termref def="dt-extension-attribute">Extension attributes</termref> may also be
                  used to influence the behavior of the standard serialization methods <code nobreak="false">xml</code>,
                     <code nobreak="false">xhtml</code>, <code nobreak="false">html</code>, <code nobreak="false">text</code>, <code nobreak="false">json</code>, 
                  and <code nobreak="false">adaptive</code>. For example, an extension attribute might
                  be used to define the amount of indentation to be used when
                     <code nobreak="false">indent="yes"</code> is specified.</p><p>An implementation that does not recognize the name of an extension attribute, or
                  that does not recognize its value, must perform the transformation as if the
                  extension attribute were not present. As always, it is permissible to produce
                  warning messages.</p><p>The namespace used for an extension attribute will be copied to the <termref def="dt-result-tree">result tree</termref> in the normal way if it is in scope
                  for a <termref def="dt-literal-result-element">literal result element</termref>.
                  This can be prevented using the <code nobreak="false">[xsl:]exclude-result-prefixes</code>
                  attribute.</p></note><example><head>An Extension Attribute for <code nobreak="false">xsl:message</code>
               </head><p>The following code might be used to indicate to a particular implementation that
                  the <elcode>xsl:message</elcode> instruction is to ask the user for confirmation
                  before continuing with the transformation:</p><eg xml:space="preserve" role="xslt-instruction">&lt;xsl:message abc:pause="yes"
    xmlns:abc="http://vendor.example.com/xslt/extensions"&gt;
       Phase 1 complete
&lt;/xsl:message&gt;
</eg><p>Implementations that do not recognize the namespace
                     <code nobreak="false">http://vendor.example.com/xslt/extensions</code> will simply ignore the
                  extra attribute, and evaluate the <elcode>xsl:message</elcode> instruction in the
                  normal way.</p></example><p>
               <error spec="XT" type="static" class="SE" code="0090"><p>It is a <termref def="dt-static-error">static error</termref> for an element
                     from the XSLT namespace to have an attribute whose namespace is either null
                     (that is, an attribute with an unprefixed name) or the XSLT namespace, other
                     than attributes defined for the element in this document.</p></error>
            </p></div2><div2 id="extension-functions"><head>Extension Functions</head><p>The set of functions that can be called from a <xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="XP40" ref="prod-xpath40-FunctionCall" xlink:type="simple">FunctionCall</xnt> within an XPath <termref def="dt-expression">expression</termref> may include one or more <termref def="dt-extension-function">extension functions</termref>. The <termref def="dt-expanded-qname">expanded QName</termref> of an extension function always
               has a non-null namespace URI, which <rfc2119>must not</rfc2119> be the 
                  URI of a <termref def="dt-reserved-namespace"/>.</p><note><p>The definition of the term <termref def="dt-extension-function"/> is written to exclude
            user-written <termref def="dt-stylesheet-function">stylesheet functions</termref>,
            constructor functions for built-in and user-defined types, functions in the <code nobreak="false">fn</code>, <code nobreak="false">math</code>,
               <code nobreak="false">map</code>, and <code nobreak="false">array</code> namespaces,
            anonymous XPath inline functions, maps and arrays,
            and partial function applications (including partial applications of extension functions). It also excludes
            functions obtained by invoking XPath-defined functions such as
               <xfunction spec="FO40">load-xquery-module</xfunction>.
            The definition allows extension functions to be discovered at evaluation time (typically using
            <xfunction>function-lookup</xfunction>) rather than necessarily being known statically.
            </p><p>Technically, the definition of extension functions excludes anonymous functions
            obtained by calling or partially applying other extension functions. Since such functions are
            by their nature implementation-defined, they may however share some of the characteristics of
            extension functions.</p></note><div3 id="func-function-available"><head>fn:function-available</head><glist><gitem><label>Summary</label><def><p>Determines whether a particular function is or is not available for use. The function is
            particularly useful for calling within an <code nobreak="false">[xsl:]use-when</code> attribute (see
               <specref ref="conditional-inclusion"/>) to test whether a particular <termref def="dt-extension-function"/> is available.</p></def></gitem><gitem><label>Signature</label><def><example role="signature"><proto isOp="no" prefix="fn" name="function-available" return-type="xs:boolean" returnEmptyOk="no" returnSeq="no" returnVaries="no" isSchema="no" isDatatype="no" isSpecial="no"><arg name="name" type="(xs:string | xs:QName)"/><arg name="arity" type="xs:integer?" default="()"/></proto></example></def></gitem><gitem><label>Properties</label><def><p>This function is <xtermref spec="FO40" ref="dt-deterministic">deterministic</xtermref>, <xtermref spec="FO40" ref="dt-context-dependent">context-dependent</xtermref>,  and <xtermref spec="FO40" ref="dt-focus-independent">focus-independent</xtermref>.  It depends on 
		namespaces, and known function signatures.
	</p></def></gitem><gitem><label>Rules</label><def><p>A function is said to be available within an XPath expression if it is present in the
               <xtermref spec="XP40" ref="dt-statically-known-function-definitions">statically known function
               definitions</xtermref> for that expression (see <specref ref="static-context"/>).
            <phrase diff="chg" at="2022-11-27">Function definitions</phrase> in the static context are uniquely identified 
            by the name of the function (a QName) in combination with its
            <termref diff="chg" at="2022-11-27" def="dt-arity-range">arity range</termref>.</p><p>The value of <code nobreak="false">$name</code> <rfc2119>must</rfc2119> be 
            <phrase diff="add" at="2022-01-01">either an <code nobreak="false">xs:QName</code>, or </phrase>a
            string containing an <termref def="dt-eqname">EQName</termref>. A lexical QName is
            expanded into an <termref def="dt-expanded-qname">expanded QName</termref> using the
            namespace declarations in scope for the <termref def="dt-expression">expression</termref>. 
            If the value is an unprefixed lexical QName, then the <termref def="dt-standard-function-namespace">standard function namespace</termref> is used in
            the expanded QName.</p><p><phrase diff="chg" at="2023-02-16">When the <code nobreak="false">$arity</code> argument is present and non-empty,</phrase>
            the <function>function-available</function> function returns
            <code nobreak="false">true</code> if and only if there is an available function whose name matches the value of the
               <code nobreak="false">$function-name</code> argument and whose <termref def="dt-arity-range">arity range</termref> 
            includes the value of the <code nobreak="false">$arity</code> argument. </p><p><phrase diff="chg" at="2023-02-16">When the <code nobreak="false">$arity</code> argument is omitted or empty,</phrase>
            the <function>function-available</function> function
            returns <code nobreak="false">true</code> if and only if there is at least one available function (with some arity)
            whose name matches the value of the <code nobreak="false">$name</code> argument. </p><p>When the containing expression is evaluated with <termref def="dt-xpath-compat-mode">XPath 1.0 compatibility mode</termref> set to
               <code nobreak="false">true</code>, the <function>function-available</function> function returns <code nobreak="false">false</code> in
            respect of a function name and arity for which no implementation is available (other
            than the fallback error function that raises a dynamic error whenever it is called).
            This means that it is possible (as in XSLT 1.0) to use logic such as the following to
            test whether a function is available before calling it:</p><example><head>Calling an extension function with backwards compatibility enabled</head><eg xml:space="preserve">
&lt;summary xsl:version="1.0"&gt;
  &lt;xsl:choose&gt;
    &lt;xsl:when test="function-available('my:summary')"&gt;
      &lt;xsl:value-of select="my:summary()"/&gt;
    &lt;/xsl:when&gt;
    &lt;xsl:otherwise&gt;
      &lt;xsl:text&gt;Summary not available&lt;/xsl:text&gt;
    &lt;/xsl:otherwise&gt;
  &lt;/xsl:choose&gt;
&lt;/summary&gt;</eg></example></def></gitem><gitem><label>Error Conditions</label><def><p>
            <error spec="XT" type="dynamic" class="DE" code="1400"><p>It is a <termref def="dt-dynamic-error"> dynamic error</termref> if the 
                  <code nobreak="false">$name</code> argument
                     <error.extra>passed to the <function>function-available</function>
                     function</error.extra> <phrase diff="chg" at="2022-01-01">evaluates to a string that is not</phrase> a valid
                  <termref def="dt-eqname">EQName</termref>, or if the value is a
                  <termref def="dt-lexical-qname">lexical QName</termref> with a prefix for which no
                  namespace declaration is present in the static context. 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 raise this
                  as a <termref def="dt-static-error">static error</termref>.</p></error>
         </p></def></gitem><gitem><label>Notes</label><def><note><p>The fact that a function with a given name is available gives no guarantee that any
            particular call on the function will be successful. For example, it is not possible to
            determine the types of the arguments expected.</p><p>The introduction of the <xfunction>function-lookup</xfunction>
            function in XPath 3.0 reduces the need for <function>function-available</function>,
            since <xfunction>function-lookup</xfunction> not only tests whether a function is
            available, but also returns a function item that enables it to be dynamically
            called.</p><p>If a function is present in the static context but with no useful
            functionality (for example, if the system has been configured for security reasons so
            that <xfunction>available-environment-variables</xfunction> returns no information),
            then <function>function-available</function> when applied to that function should return
            <code nobreak="false">false</code>.</p><p>It is not necessary that there be a direct equivalence between the
            results of <function>function-available</function> and
               <xfunction>function-lookup</xfunction> in all cases. For example, there may be
               <termref def="dt-extension-function">extension functions</termref> whose side-effects
            are such that for security reasons, dynamic calls to the function are disallowed;
               <xfunction>function-lookup</xfunction> might then not provide access to the function.
            The main use-case for <function>function-available</function>, by contrast, is for use
            in <code nobreak="false">[xsl:]use-when</code> conditions to test whether static calls on the function
            are possible.</p><p>In XSLT 4.0, the argument can be supplied as a QName literal, for example
         <code nobreak="false">function-available( #fn:matches )</code>. Note that in this case the default function
         namespace is not used for unprefixed names.</p></note></def></gitem><gitem><label>Examples</label><def role="example"><table role="medium" border="1" cellpadding="5" width="100%"><tbody><tr><td colspan="2" rowspan="1" align="left" valign="top"><example><head>Stylesheet portable between XSLT 1.0, XSLT 2.0, and XSLT 3.0</head><p>A stylesheet that is designed to use XSLT 2.0 facilities when running under an
                     XSLT 2.0 or XSLT 3.0 processor, but to fall
                  back to XSLT 1.0 capabilities when not, might be written using the code:</p><eg xml:space="preserve">
&lt;out xsl:version="2.0"&gt;
  &lt;xsl:choose&gt;
    &lt;xsl:when test="function-available('matches')"&gt;
      &lt;xsl:value-of select="matches(/doc/title, '[a-z]*')"/&gt;
    &lt;/xsl:when&gt;
    &lt;xsl:otherwise&gt;
      &lt;xsl:value-of select="string-length(
	        translate(/doc/title, 'abcdefghijklmnopqrstuvwxyz', '')) = 0"/&gt;
    &lt;/xsl:otherwise&gt;
  &lt;/xsl:choose&gt;
&lt;/out&gt;</eg><p>Here an XSLT 2.0 or XSLT 3.0 processor will
                  always take the <elcode>xsl:when</elcode> branch, while a 1.0 processor will
                  follow the <elcode>xsl:otherwise</elcode> branch. The single-argument version of
                  the <function>function-available</function> function is used here, because that is
                  the only version available in XSLT 1.0. Under the rules of XSLT 1.0, the call on
                  the <code nobreak="false">matches</code> function is not an error, because it is never
                  evaluated.</p></example></td></tr><tr><td colspan="2" rowspan="1" align="left" valign="top"><example><head>Stylesheet portable between XSLT 3.0 and a future version of XSLT</head><p>A stylesheet that is designed to use facilities in some future XSLT version when
                  they are available, but to fall back to XSLT 2.0 or XSLT
                     3.0 capabilities when not, might be written using code such as the
                  following. This hypothesizes the availability in some future version of a function
                     <code nobreak="false">pad</code> which pads a string to a fixed length with spaces:</p><eg xml:space="preserve">
 &lt;xsl:value-of select="pad(/doc/title, 10)" 
               use-when="function-available('pad', 2)"/&gt;
 &lt;xsl:value-of select="concat(/doc/title, string-join(
                          for $i in 1 to 10 - string-length(/doc/title) 
						  return ' ', ''))"
               use-when="not(function-available('pad', 2))"/&gt;
 </eg><p>In this case the two-argument version of <function>function-available</function>
                  is used, because there is no requirement for this code to run under XSLT 1.0.</p></example></td></tr></tbody></table></def></gitem></glist></div3><div3 id="calling-extension-functions"><head>Calling Extension Functions</head><p>If the function name used in a <xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="XP40" ref="prod-xpath40-FunctionCall" xlink:type="simple">FunctionCall</xnt> within an XPath <termref def="dt-expression">expression</termref> identifies an extension function, then to evaluate the
                     <xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="XP40" ref="prod-xpath40-FunctionCall" xlink:type="simple">FunctionCall</xnt>, the
                  processor will first evaluate each of the arguments in the <xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="XP40" ref="prod-xpath40-FunctionCall" xlink:type="simple">FunctionCall</xnt>. If the processor has
                  information about the datatypes expected by the extension function, then it
                     <rfc2119>may</rfc2119> perform any necessary type conversions between the XPath
                  datatypes and those defined by the implementation language. If multiple extension
                  functions are available with the same name, the processor <rfc2119>may</rfc2119>
                  decide which one to invoke based on the number of arguments, the types of the
                  arguments, or any other criteria. The result returned by the implementation is
                  returned as the result of the function call, again after any necessary conversions
                  between the datatypes of the implementation language and those of XPath. The
                  details of such type conversions are outside the scope of this specification.</p><p>
                  <error spec="XT" type="dynamic" class="DE" code="1420"><p>It is a <termref def="dt-dynamic-error"> dynamic error</termref> if the arguments
                        supplied to a call on an extension function do not satisfy the rules defined
                        for that particular extension function, or if the extension function raises
                        an error, or if the result of the extension function cannot be converted to
                        an XPath value.</p></error>
               </p><note><p>Implementations may also provide mechanisms allowing extension functions to
                     raise recoverable dynamic errors, or to execute within an environment that
                     treats some or all of the errors listed above as recoverable.</p></note><p>
                  <error spec="XT" type="dynamic" class="DE" code="1425"><p>When the containing element is processed with
                              <termref def="dt-xslt-10-behavior">XSLT 1.0
                           behavior</termref>, it is a <termref def="dt-dynamic-error"> dynamic
                           error</termref> to evaluate an extension function call if no
                        implementation of the extension function is available.</p></error>
               </p><note><p>When XSLT 1.0 behavior is not enabled, this
                     is a static error <xerrorref spec="XP40" class="ST" code="0017"/>.</p></note><note><p>There is no prohibition on calling extension functions that have side-effects
                     (for example, an extension function that writes data to a file). However, the
                     order of execution of XSLT instructions is not defined in this specification,
                     so the effects of such functions are unpredictable.</p></note><p>Implementations are not <rfc2119>required</rfc2119> to perform full validation of
                  values returned by extension functions. It is an error for an extension function
                  to return a string containing characters that are not permitted in XML, but the
                  consequences of this error are <termref def="dt-implementation-defined">implementation-defined</termref>. The implementation <rfc2119>may</rfc2119>
                  raise an error, <rfc2119>may</rfc2119> convert the string to a string containing
                  valid characters only, or <rfc2119>may</rfc2119> treat the invalid characters as
                  if they were permitted characters.</p><imp-def-feature id="idf-ext-nonxmlstring">The effect of an extension function
                  returning a string containing characters that are not permitted in XML is
                  implementation-defined.</imp-def-feature><note><p>The ability to execute extension functions represents a potential security
                     weakness, since untrusted stylesheets may invoke code that has privileged
                     access to resources on the machine where the <termref def="dt-processor">processor</termref> executes. Implementations may therefore provide
                     mechanisms that restrict the use of extension functions by untrusted
                     stylesheets.</p></note><p>All observations in this section regarding the errors that can occur when invoking
                  extension functions apply equally when invoking <termref def="dt-extension-instruction">extension instructions</termref>.</p></div3><div3 id="external-objects"><head>External Objects</head><p>An implementation <rfc2119>may</rfc2119> allow an extension function to return an
                  object that does not have any natural representation in the XDM data model,
                  whether as an atomic item, a node, or a function
                     item. For example, an extension function <code nobreak="false">sql:connect</code>
                  might return an object that represents a connection to a relational database; the
                  resulting connection object might be passed as an argument to calls on other
                  extension functions such as <code nobreak="false">sql:insert</code> and
                  <code nobreak="false">sql:select</code>.</p><p>The way in which such objects are represented in the type system is <termref def="dt-implementation-defined">implementation-defined</termref>. They might be
                  represented by a completely new datatype, or they might be mapped to existing
                  datatypes such as <code nobreak="false">integer</code>, <code nobreak="false">string</code>, or
                     <code nobreak="false">anyURI</code>.</p><imp-def-feature id="idf-ext-externalobjects">The way in which external objects are
                  represented in the type system is implementation-defined.</imp-def-feature></div3><div3 id="func-type-available"><head>fn:type-available</head><glist><gitem><label>Summary</label><def><p>Used to control how a stylesheet behaves if a particular schema type is or is not
            available in the static context.</p></def></gitem><gitem><label>Signature</label><def><example role="signature"><proto isOp="no" prefix="fn" name="type-available" return-type="xs:boolean" returnEmptyOk="no" returnSeq="no" returnVaries="no" isSchema="no" isDatatype="no" isSpecial="no"><arg name="name" type="(xs:string | xs:QName)"/></proto></example></def></gitem><gitem><label>Properties</label><def><p>This function is <xtermref spec="FO40" ref="dt-deterministic">deterministic</xtermref>, <xtermref spec="FO40" ref="dt-context-dependent">context-dependent</xtermref>,  and <xtermref spec="FO40" ref="dt-focus-independent">focus-independent</xtermref>.  It depends on 
		namespaces, and schema definitions.
	</p></def></gitem><gitem><label>Rules</label><def><p>A schema type (that is, a simple type or a complex type) is said to be available within
            an XPath expression if it is a type definition that is present in the 
            <xtermref spec="XP40" ref="dt-is-types">in-scope schema types</xtermref> for that expression
            (see <specref ref="static-context"/>). This includes built-in types, types imported
            using <elcode>xsl:import-schema</elcode>, and extension types defined by the
            implementation.</p><p>The value of the <code nobreak="false">$name</code> argument <rfc2119>must</rfc2119> be 
            <phrase diff="add" at="2022-01-01">either an <code nobreak="false">xs:QName</code>, or</phrase> a string
            containing an <termref def="dt-eqname">EQName</termref>. The EQName is expanded into 
            an <termref def="dt-expanded-qname">expanded QName</termref> using the namespace declarations in
            scope for the <termref def="dt-expression">expression</termref>. If the value is an
            unprefixed lexical QName, then the default namespace is used in the expanded QName.</p><p>The function returns <code nobreak="false">true</code> if and only if there is an available type whose name matches
            the value of the <code nobreak="false">$name</code> argument. </p></def></gitem><gitem><label>Error Conditions</label><def><p>
            <error spec="XT" type="dynamic" class="DE" code="1428"><p>It is a <termref def="dt-dynamic-error"> dynamic error</termref> if the argument
                     <error.extra>passed to the <function>type-available</function>
                     function</error.extra> <phrase diff="chg" at="2022-01-01">evaluates to a string that is 
                        not</phrase> a valid <termref def="dt-eqname">EQName</termref>, or if the 
                  value is a <termref def="dt-lexical-qname">lexical QName</termref> with a prefix for which no
                  namespace declaration is present in the static context. 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 raise this
                  as a <termref def="dt-static-error">static error</termref>.</p></error>
         </p></def></gitem><gitem><label>Notes</label><def><note><p>The <function>type-available</function> function is of limited use within an
               <code nobreak="false">[xsl:]use-when</code> expression, because the static context for the expression
            does not include any user-defined types.</p><p>In XSLT 4.0, the argument can be supplied as a QName literal, for example
         <code nobreak="false">type-available( #xs:dateTimeStamp )</code>.</p></note></def></gitem></glist></div3></div2><div2 id="extension-instruction"><head>Extension Instructions</head><changes><change issue="168" date="2022-09-30">
                  It is possible to invoke a named template using an extension instruction, specifically,
                  an element whose name matches the name of the named template.
               </change></changes><p>
               <termdef id="dt-extension-namespace" term="extension namespace">The <termref def="dt-extension-instruction">extension instruction</termref> mechanism allows
                  namespaces to be designated as <term>extension namespaces</term>. When a namespace
                  is designated as an extension namespace and an element with a name from that
                  namespace occurs in a <termref def="dt-sequence-constructor">sequence
                     constructor</termref>, then the element is treated as an <termref def="dt-instruction">instruction</termref> rather than as a <termref def="dt-literal-result-element">literal result element</termref>.</termdef> The
               namespace determines the semantics of the instruction.</p><note><p>Since an element that is a child of an <elcode>xsl:stylesheet</elcode> element is
                  not occurring <emph>in a <termref def="dt-sequence-constructor">sequence
                        constructor</termref>
                  </emph>, <termref def="dt-data-element">user-defined data elements</termref> (see
                     <specref ref="user-defined-top-level"/>) are not extension elements as defined
                  here, and nothing in this section applies to them.</p></note><p>In XSLT 4.0 it is possible to use extension instructions to invoke named templates: see
               <specref ref="invoking-templates-with-extension-instructions"/>.
            </p><div3 id="designating-extension-namespace"><head>Designating an Extension Namespace</head><p>A namespace is designated as an extension namespace by using an
                     <code nobreak="false">[xsl:]extension-element-prefixes</code> attribute on an element in the
                  stylesheet (see <specref ref="standard-attributes"/>). The attribute
                     <rfc2119>must</rfc2119> be in the XSLT namespace only if its parent element is
                     <emph>not</emph> in the XSLT namespace. The value of the attribute is a
                  whitespace-separated list of namespace prefixes. The namespace bound to each of
                  the prefixes is designated as an extension namespace.</p><p>The default namespace (as declared by <code nobreak="false">xmlns</code>) may be designated as an
                  extension namespace by including <code nobreak="false">#default</code> in the list of namespace
                  prefixes.</p><p>A <termref def="dt-reserved-namespace"/> 
                  cannot be designated as an extension namespace: see <errorref spec="XT" class="SE" code="0085"/>.</p><p>
                  <error spec="XT" type="static" class="SE" code="1430"><p>It is a <termref def="dt-static-error">static error</termref> if there is no
                        namespace bound to the prefix on the element bearing the
                           <code nobreak="false">[xsl:]extension-element-prefixes</code> attribute or, when
                           <code nobreak="false">#default</code> is specified, if there is no default namespace.</p></error>
               </p><note><p>The prefix must be declared in a 
                  <termref def="dt-native-namespace-bindings">native namespace binding</termref>,
                  not in a <termref def="dt-fixed-namespace-bindings">fixed namespace binding</termref>.</p></note><p>The designation of a namespace as an extension namespace is effective for the
                  element bearing the <code nobreak="false">[xsl:]extension-element-prefixes</code> attribute and
                  for all descendants of that element within the same stylesheet module.</p></div3><div3 id="func-element-available"><head>fn:element-available</head><glist><gitem><label>Summary</label><def><p>Determines whether a particular instruction is or is not available for use. The function
            is particularly useful for calling within an <code nobreak="false">[xsl:]use-when</code> attribute (see
               <specref ref="conditional-inclusion"/>) to test whether a particular
            <termref def="dt-extension-instruction"/> is available.</p></def></gitem><gitem><label>Signature</label><def><example role="signature"><proto isOp="no" prefix="fn" name="element-available" return-type="xs:boolean" returnEmptyOk="no" returnSeq="no" returnVaries="no" isSchema="no" isDatatype="no" isSpecial="no"><arg name="name" type="(xs:string | xs:QName)"/></proto></example></def></gitem><gitem><label>Properties</label><def><p>This function is <xtermref spec="FO40" ref="dt-deterministic">deterministic</xtermref>, <xtermref spec="FO40" ref="dt-context-dependent">context-dependent</xtermref>,  and <xtermref spec="FO40" ref="dt-focus-independent">focus-independent</xtermref>.  It depends on 
		namespaces.
	</p></def></gitem><gitem><label>Rules</label><def><p>The value of the <code nobreak="false">$name</code> argument
               <rfc2119>must</rfc2119> be <phrase diff="add" at="2022-01-01">either an <code nobreak="false">xs:QName</code>,
               or</phrase> a string containing an <termref def="dt-eqname">EQName</termref>. 
            If it is a <termref def="dt-lexical-qname">lexical QName</termref>
            with a prefix, then it is expanded into an <termref def="dt-expanded-qname">expanded
               QName</termref> using the namespace declarations in the static context of the
               <termref def="dt-expression">expression</termref>. If there is a default namespace in
            scope, then it is used to expand an unprefixed <termref def="dt-lexical-qname">lexical
               QName</termref>.</p><p> If the resulting <termref def="dt-expanded-qname">expanded
               QName</termref> is in the <termref def="dt-xslt-namespace"/>, the function returns
            <code nobreak="false">true</code> if and only if the local name matches the name of an XSLT element that is defined
            in this specification and implemented by the XSLT processor.</p><p>If the <termref def="dt-expanded-qname">expanded QName</termref> has a null namespace
            URI, the <function>element-available</function> function will return <code nobreak="false">false</code>. </p><p>If the <termref def="dt-expanded-qname">expanded QName</termref> is not in the <termref def="dt-xslt-namespace">XSLT namespace</termref>, the function returns <code nobreak="false">true</code> if and
            only if the processor has an <phrase diff="add" at="2022-01-01">external</phrase> implementation 
            available of an <termref def="dt-extension-instruction">extension instruction</termref> with the given
            expanded QName. This applies whether or not the namespace has been designated as an
               <termref def="dt-extension-namespace">extension namespace</termref>.</p><p diff="add" at="2022-01-01">The term <term>external implementation</term> excludes the use of a 
            <termref def="dt-named-template"/> as the instruction’s implementation. The function does not return
         <code nobreak="false">true</code> simply because the name matches the name of a <termref def="dt-named-template"/>.</p><p>If the processor does not have an implementation of a particular extension instruction
            available, and such an extension instruction is evaluated, then the processor
               <rfc2119>must</rfc2119> perform fallback for the element as specified in <specref ref="fallback"/>. An implementation <rfc2119>must not</rfc2119> raise an error
            merely because the stylesheet contains an extension instruction for which no
            implementation is available.</p></def></gitem><gitem><label>Error Conditions</label><def><p>
            <error spec="XT" type="dynamic" class="DE" code="1440"><p>It is a <termref def="dt-dynamic-error"> dynamic error</termref> if the argument
                     <error.extra>passed to the <function>element-available</function>
                     function</error.extra> <phrase diff="chg" at="2022-01-01">evaluates to a string that is 
                        not</phrase> a valid <termref def="dt-eqname">EQName</termref>, or if the value 
                  is a <termref def="dt-lexical-qname">lexical QName</termref> with a prefix for which no
                  namespace declaration is present in the static context. 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 raise this
                  as a <termref def="dt-static-error">static error</termref>.</p></error>
         </p></def></gitem><gitem><label>Notes</label><def><note><p>For element names in the XSLT namespace:</p><ulist><item><p>This function can be useful to
                  distinguish processors that implement XSLT 3.0 from processors that implement
                  other (older or newer) versions of the specification, and to distinguish full
                  implementations from incomplete implementations. (Incomplete implementations,
                  of course, cannot be assumed to behave as described in this specification.)</p></item><item><p>In earlier versions of this specification,
                     <function>element-available</function> was defined to return <code nobreak="false">true</code> only for
                  elements classified as instructions. The distinction between instructions and
                  other elements, however, is sometimes rather technical, and in XSLT 3.0 the effect
                  of the function has therefore been aligned to do what its name might suggest.</p></item><item><p>If an instruction is recognized but offers no useful
                  functionality (for example, if the system has been configured for security reasons
                  so that <elcode>xsl:evaluate</elcode> always raises an error), then
                     <function>element-available</function> when applied to that instruction
                     <rfc2119>should</rfc2119> return <code nobreak="false">false</code>.</p></item></ulist><p>For element names in other namespaces:</p><ulist><item><p>The result of the <function>element-available</function> does not depend on
                  whether or not the namespace of the supplied instruction name has been designated
                  as an extension element namespace; it tests whether the instruction would be
                  available if the namespace were designated as such.</p></item></ulist><p>In XSLT 4.0, the argument can be supplied as a QName literal, for example
         <code nobreak="false">element-available( #xsl:switch )</code>. Note that in this case the default element
         namespace is not used for unprefixed names.</p></note></def></gitem></glist></div3><div3 id="fallback"><head>Fallback</head><e:element-syntax xmlns:e="http://www.w3.org/1999/XSL/Spec/ElementSyntax" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" name="fallback">
      <e:in-category name="instruction"/>
      <e:model name="sequence-constructor"/>
      <e:allowed-parents>
         <e:parent name="analyze-string"/>
         <e:parent name="evaluate"/>
         <e:parent name="fork"/>
         <e:parent name="merge"/>
         <e:parent name="next-match"/>
         <e:parent name="try"/>
         <e:parent-category name="sequence-constructor"/>
      </e:allowed-parents>
   </e:element-syntax><p>The content of an <elcode>xsl:fallback</elcode> element is a <termref def="dt-sequence-constructor">sequence constructor</termref>, and when
                  performing fallback, the value returned by the <elcode>xsl:fallback</elcode>
                  element is the result of evaluating this sequence constructor.</p><p>When not performing fallback, evaluating an <elcode>xsl:fallback</elcode> element
                  returns the empty sequence: the content of the <elcode>xsl:fallback</elcode>
                  element is not evaluated.</p><p>There are two situations where a <termref def="dt-processor">processor</termref>
                  performs fallback: when an extension instruction that is not available is
                  evaluated, and when an instruction in the XSLT namespace, that is not defined in
                  XSLT 3.0, is evaluated within a region of the
                  stylesheet for which <termref def="dt-forwards-compatible-behavior"/> is
                  enabled.</p><note><p>Fallback processing is not invoked in other situations, for example it is not
                     invoked when an XPath expression uses unrecognized syntax or contains a call to
                     an unknown function. To handle such situations dynamically, the stylesheet
                     should call functions such as <function>system-property</function> and
                        <function>function-available</function> to decide what capabilities are
                     available.</p></note><p>
                  <error spec="XT" type="dynamic" class="DE" code="1450"><p>When a <termref def="dt-processor">processor</termref> performs fallback for
                        an <termref def="dt-extension-instruction">extension instruction</termref>
                        that is not recognized, if the instruction element has one or more
                           <elcode>xsl:fallback</elcode> children, then the content of each of the
                           <elcode>xsl:fallback</elcode> children <rfc2119>must</rfc2119> be
                        evaluated; it is a <termref def="dt-dynamic-error"> dynamic error</termref> if it has no
                           <elcode>xsl:fallback</elcode> children.</p></error>
               </p><note><p>This is different from the situation with unrecognized <termref def="dt-xslt-element">XSLT elements</termref>. As explained in <specref ref="forwards"/>, an unrecognized XSLT element appearing within a <termref def="dt-sequence-constructor">sequence constructor</termref> is a static
                     error unless (a) <termref def="dt-forwards-compatible-behavior"/> is enabled,
                     and (b) the instruction has an <elcode>xsl:fallback</elcode> child.</p></note></div3></div2></div1><div1 id="result-trees"><head>Transformation Results</head><p>The output of a transformation includes a <termref def="dt-principal-result"/> and zero or more <termref def="dt-secondary-result">secondary results</termref>.</p><p>The way in which these results are
             delivered to an application is <termref def="dt-implementation-defined">implementation-defined</termref>.</p><imp-def-feature id="idf-api-results">The way in which the results of the transformation
            are delivered to an application is implementation-defined.</imp-def-feature><p>Serialization of results
             is described further in <specref ref="serialization"/>
         </p><div2 id="creating-result-trees"><head>Creating Secondary Results</head><changes><change issue="530" PR="534" date="2023-06-09">
                  A new serialization parameter <code nobreak="false">escape-solidus</code> is provided to control
                  whether the character <code nobreak="false">/</code> is escaped as <code nobreak="false">\/</code> by the
                  JSON serialization method.
               </change><change issue="1534" PR="1549" date="2024-11-12">
                  The input to the serializer can be defined using the <code nobreak="false">select</code> attribute
                  of <elcode>xsl:result-document</elcode> as an alternative to using a sequence constructor.
               </change><change issue="938" PR="2259" date="2025-11-02">
                  A new serialization parameter <code nobreak="false">canonical</code> is available to give control
                  over serialization of XML, XHTML, and JSON.
               </change><change issue="1538" PR="1497 1546" date="2024-11-13">
                  A new serialization parameter <code nobreak="false">json-lines</code> is available to enable
                  output as one JSON value per line.
               </change></changes><e:element-syntax xmlns:e="http://www.w3.org/1999/XSL/Spec/ElementSyntax" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" name="result-document">
      <e:in-category name="instruction"/>
      <e:attribute name="format">
         <e:attribute-value-template>
            <e:data-type name="eqname"/>
         </e:attribute-value-template>
      </e:attribute>
      <e:attribute name="href">
         <e:attribute-value-template>
            <e:data-type name="uri"/>
         </e:attribute-value-template>
      </e:attribute>
      <e:attribute name="select">
         <e:data-type name="expression"/>
      </e:attribute>
      <e:attribute name="validation">
         <e:constant value="strict"/>
         <e:constant value="lax"/>
         <e:constant value="preserve"/>
         <e:constant value="strip"/>
      </e:attribute>
      <e:attribute name="type">
         <e:data-type name="eqname"/>
      </e:attribute>
      <e:attribute name="method">
         <e:attribute-value-template>
            <e:constant value="xml"/>
            <e:constant value="html"/>
            <e:constant value="xhtml"/>
            <e:constant value="text"/>
            <e:constant value="json"/>
            <e:constant value="adaptive"/>
            <e:data-type name="eqname"/>
         </e:attribute-value-template>
      </e:attribute>
      <e:attribute name="allow-duplicate-names">
         <e:attribute-value-template>
            <e:data-type name="boolean"/>
         </e:attribute-value-template>
      </e:attribute>
      <e:attribute name="build-tree">
         <e:attribute-value-template>
            <e:data-type name="boolean"/>
         </e:attribute-value-template>
      </e:attribute>
      <e:attribute name="byte-order-mark">
         <e:attribute-value-template>
            <e:data-type name="boolean"/>
         </e:attribute-value-template>
      </e:attribute>
      <e:attribute name="canonical">
         <e:attribute-value-template>
            <e:data-type name="boolean"/>
         </e:attribute-value-template>
      </e:attribute>
      <e:attribute name="cdata-section-elements">
         <e:attribute-value-template>
            <e:data-type name="eqnames"/>
         </e:attribute-value-template>
      </e:attribute>
      <e:attribute name="doctype-public">
         <e:attribute-value-template>
            <e:data-type name="string"/>
         </e:attribute-value-template>
      </e:attribute>
      <e:attribute name="doctype-system">
         <e:attribute-value-template>
            <e:data-type name="string"/>
         </e:attribute-value-template>
      </e:attribute>
      <e:attribute name="encoding">
         <e:attribute-value-template>
            <e:data-type name="string"/>
         </e:attribute-value-template>
      </e:attribute>
      <e:attribute name="escape-solidus">
         <e:attribute-value-template>
            <e:data-type name="boolean"/>
         </e:attribute-value-template>
      </e:attribute>
      <e:attribute name="escape-uri-attributes">
         <e:attribute-value-template>
            <e:data-type name="boolean"/>
         </e:attribute-value-template>
      </e:attribute>
      <e:attribute name="html-version">
         <e:attribute-value-template>
            <e:data-type name="decimal"/>
         </e:attribute-value-template>
      </e:attribute>
      <e:attribute name="include-content-type">
         <e:attribute-value-template>
            <e:data-type name="boolean"/>
         </e:attribute-value-template>
      </e:attribute>
      <e:attribute name="indent">
         <e:attribute-value-template>
            <e:data-type name="boolean"/>
         </e:attribute-value-template>
      </e:attribute>
      <e:attribute name="item-separator">
         <e:attribute-value-template>
            <e:data-type name="string"/>
         </e:attribute-value-template>
      </e:attribute>
      <e:attribute name="json-lines">
         <e:attribute-value-template>
            <e:data-type name="boolean"/>
         </e:attribute-value-template>
      </e:attribute>
      <e:attribute name="json-node-output-method">
         <e:attribute-value-template>
            <e:constant value="xml"/>
            <e:constant value="html"/>
            <e:constant value="xhtml"/>
            <e:constant value="text"/>
            <e:data-type name="eqname"/>
         </e:attribute-value-template>
      </e:attribute>
      <e:attribute name="media-type">
         <e:attribute-value-template>
            <e:data-type name="string"/>
         </e:attribute-value-template>
      </e:attribute>
      <e:attribute name="normalization-form">
         <e:attribute-value-template>
            <e:constant value="NFC"/>
            <e:constant value="NFD"/>
            <e:constant value="NFKC"/>
            <e:constant value="NFKD"/>
            <e:constant value="fully-normalized"/>
            <e:constant value="none"/>
            <e:data-type name="nmtoken"/>
         </e:attribute-value-template>
      </e:attribute>
      <e:attribute name="omit-xml-declaration">
         <e:attribute-value-template>
            <e:data-type name="boolean"/>
         </e:attribute-value-template>
      </e:attribute>
      <e:attribute name="parameter-document">
         <e:attribute-value-template>
            <e:data-type name="uri"/>
         </e:attribute-value-template>
      </e:attribute>
      <e:attribute name="standalone">
         <e:attribute-value-template>
            <e:data-type name="boolean"/>
            <e:constant value="omit"/>
         </e:attribute-value-template>
      </e:attribute>
      <e:attribute name="suppress-indentation">
         <e:attribute-value-template>
            <e:data-type name="eqnames"/>
         </e:attribute-value-template>
      </e:attribute>
      <e:attribute name="undeclare-prefixes">
         <e:attribute-value-template>
            <e:data-type name="boolean"/>
         </e:attribute-value-template>
      </e:attribute>
      <e:attribute name="use-character-maps">
         <e:data-type name="eqnames"/>
      </e:attribute>
      <e:attribute name="output-version">
         <e:attribute-value-template>
            <e:data-type name="nmtoken"/>
         </e:attribute-value-template>
      </e:attribute>
      <e:model name="sequence-constructor"/>
      <e:allowed-parents>
         <e:parent-category name="sequence-constructor"/>
      </e:allowed-parents>
   </e:element-syntax><p>The <elcode>xsl:result-document</elcode> instruction is
               used to create a <termref def="dt-secondary-result"/>.</p><p>The <code nobreak="false">select</code> attribute and the contained <termref def="dt-sequence-constructor"/> are
               mutually exclusive; if the <code nobreak="false">select</code> attribute is present then the
               sequence constructor must be empty, and if the sequence constructor is non-empty
               then the <code nobreak="false">select</code> attribute must be absent <errorref spec="XT" class="SE" code="3185"/>. 
               The value of the <code nobreak="false">select</code> attribute or the <termref def="dt-immediate-result"/>
               of the contained <termref def="dt-sequence-constructor"/>
               is referred to as the <termref def="dt-raw-result"/>.</p><p>As with the <termref def="dt-principal-result"/> of the
            transformation, a <termref def="dt-secondary-result"/> may be delivered to the calling
            application in three ways (see <specref ref="post-processing"/>):</p><olist><item><p>The <termref def="dt-raw-result"/> may be delivered <emph>as is</emph>.</p></item><item><p>The <termref def="dt-raw-result"/> may be used to construct a <termref def="dt-final-result-tree"/>
               by invoking the process of <xtermref spec="SE40" ref="sequence-normalization"/>.</p></item><item><p>The <termref def="dt-raw-result"/> may be serialized to a sequence of octets (which
               may then, optionally, be saved to a persistent storage location).</p></item></olist><note><p>The name of the instruction, <elcode>xsl:result-document</elcode>, is a little
            misleading. The instruction does not necessarily deliver either an XML document tree
            nor a serialized XML document. Instead, for example, it might deliver an array, a map,
            serialized JSON, or a sequence of atomic items.</p></note><p>The decision whether or not to serialize the raw result depends on the 
               <termref def="dt-processor">processor</termref> and on the way it is invoked. This
               is <termref def="dt-implementation-defined"/>, and it is not controlled by anything
               in the stylesheet.</p><p>If the result is not serialized, then the decision whether to
               return the <termref def="dt-raw-result"/> or to construct a tree depends on the effective
               value of the <code nobreak="false">build-tree</code> attribute. If the <termref def="dt-effective-value"/> of
               the <code nobreak="false">build-tree</code> attribute is <code nobreak="false">yes</code>, then 
                  a <termref def="dt-final-result-tree"/> is created
               by invoking the process of <xtermref spec="SE40" ref="sequence-normalization"/>. 
               Conversely, if the result <emph>is</emph> serialized, then 
                  the decision whether or not to construct a tree depends on the choice of 
                  serialization method, and the <code nobreak="false">build-tree</code> attribute is then ignored. 
                  For example, with <code nobreak="false">method="xml"</code> a tree is always constructed, whereas 
                  with <code nobreak="false">method="json"</code> a tree is never constructed.
               </p><p>The <elcode>xsl:result-document</elcode> instruction
               defines a URI that may be used to identify the <termref def="dt-secondary-result"/>.
               The instruction may optionally specify the output format to be used for serializing the result.</p><p>Technically, the result of evaluating the <elcode>xsl:result-document</elcode>
               instruction is the empty sequence. This means it does not contribute anything to the
               result of the sequence constructor it is part of.</p><p>The <termref def="dt-effective-value"/> of the
                  <code nobreak="false">format</code> attribute, if specified, <rfc2119>must</rfc2119> be an <termref def="dt-eqname">EQName</termref>. The value is
               expanded using the namespace declarations in scope for the
                  <elcode>xsl:result-document</elcode> element. The resulting <termref def="dt-expanded-qname">expanded QName</termref>
               <rfc2119>must</rfc2119> match the expanded QName of a named <termref def="dt-output-definition">output definition</termref> in the <termref def="dt-stylesheet">stylesheet</termref>. This identifies the
                  <elcode>xsl:output</elcode> declaration that will control the serialization of the
                  <termref def="dt-final-result-tree">final result tree</termref> (see <specref ref="serialization"/>), if the result tree is serialized. If the
                  <code nobreak="false">format</code> attribute is omitted, the unnamed <termref def="dt-output-definition">output definition</termref> is used to control
               serialization of the result tree.</p><p>
               <error spec="XT" type="dynamic" class="DE" code="1460"><p>It is a <termref def="dt-dynamic-error"> dynamic error</termref> if the <termref def="dt-effective-value"/> of the
                        <code nobreak="false">format</code> attribute <error.extra>of an
                           <elcode>xsl:result-document</elcode> element</error.extra> is not a valid
                        <termref def="dt-eqname">EQName</termref>, or if it does not match the
                        <termref def="dt-expanded-qname">expanded QName</termref> of an <termref def="dt-output-definition">output definition</termref> in the containing <termref def="dt-package">package</termref>. If the processor is able to detect
                     the error statically (for example, when the <code nobreak="false">format</code> attribute
                     contains no curly brackets), then the processor <rfc2119>may</rfc2119>
                     optionally raise this as a <termref def="dt-static-error">static
                        error</termref>.</p></error>
            </p><note><p>The only way to select the unnamed <termref def="dt-output-definition">output
                     definition</termref> is to omit the <code nobreak="false">format</code> attribute.</p></note><p>The <code nobreak="false">parameter-document</code> attribute allows serialization
               parameters to be supplied in an external document. The external document must contain
               an <code nobreak="false">output:serialization-parameters</code> element with the format described in
                  <xspecref spec="SE40" ref="serparams-in-xdm-instance"/>, and the parameters are
               interpreted as described in that specification.</p><p>If present, the <termref def="dt-effective-value"/> of the URI supplied in the
                  <code nobreak="false">parameter-document</code> attribute is dereferenced, after resolution
               against the base URI of the <elcode>xsl:result-document</elcode> element if it is a
               relative reference. 
               The parameter document <rfc2119>should</rfc2119> be read during run-time evaluation of the stylesheet. 
               If the location of the stylesheet at development time is
               different from the deployed location, any relative reference should be resolved
               against the deployed location. A serialization error occurs if the result of
               dereferencing the URI is ill-formed or invalid; but if no document can be found at
               the specified location, the attribute <code nobreak="false">should</code> be ignored.</p><p>A serialization parameter specified in the
                  <code nobreak="false">parameter-document</code> takes precedence over a value supplied directly as
               an attribute of <elcode>xsl:result-document</elcode>, which in turn takes precedence
               over a value supplied in the selected output definition, except that the values of
               the <code nobreak="false">cdata-section-elements</code> and <code nobreak="false">suppress-indentation</code>
               attributes are merged in the same way as when multiple <elcode>xsl:output</elcode>
               declarations are merged.</p><p>The attributes <code nobreak="false">method</code>, <code nobreak="false">allow-duplicate-names</code>, <code nobreak="false">build-tree</code>, <code nobreak="false">byte-order-mark</code>
               <code nobreak="false">canonical</code>, <code nobreak="false">cdata-section-elements</code>, <code nobreak="false">doctype-public</code>,
                  <code nobreak="false">doctype-system</code>, <code nobreak="false">encoding</code>,
               <code diff="add" at="2023-03-31" nobreak="false">escape-solidus</code>
                  <code nobreak="false">escape-uri-attributes</code>, <code nobreak="false">html-version</code>, <code nobreak="false">indent</code>, <code nobreak="false">item-separator</code>,
               <code diff="add" at="2024-11-01" nobreak="false">json-lines</code>,
               <code nobreak="false">json-node-output-method</code>,
                  <code nobreak="false">media-type</code>, <code nobreak="false">normalization-form</code>,
                  <code nobreak="false">omit-xml-declaration</code>, <code nobreak="false">standalone</code>, <code nobreak="false">suppress-indentation</code>,
               
               <code nobreak="false">undeclare-prefixes</code>, <code nobreak="false">use-character-maps</code>, and
                  <code nobreak="false">output-version</code> may be used to override attributes defined in the
               selected <termref def="dt-output-definition">output definition</termref>.</p><p>With the exception of <code nobreak="false">use-character-maps</code>, these attributes are all
               defined as <termref def="dt-attribute-value-template">attribute value
                  templates</termref>, so their values may be set dynamically. For any of these
               attributes that is present on the <elcode>xsl:result-document</elcode> instruction,
               the <termref def="dt-effective-value"/> of the attribute
               overrides or supplements the corresponding value from the output definition. This
               works in the same way as when one <elcode>xsl:output</elcode> declaration overrides
               another. Some of the attributes have more specific
                  rules:</p><ulist><item><p>In the case of <code nobreak="false">cdata-section-elements</code>
                     and <code nobreak="false">suppress-indentation</code>, the
                     value of the serialization parameter is the union of the expanded names of the
                     elements named in this instruction and the elements named in the selected
                     output definition.</p></item><item><p>In the case of <code nobreak="false">use-character-maps</code>, the character maps referenced
                     in this instruction supplement and take precedence over those defined in the
                     selected output definition.</p></item><item><p>In the case of <code nobreak="false">doctype-public</code> and <code nobreak="false">doctype-system</code>,
                     setting the <termref def="dt-effective-value"/> of the attribute to a zero-length string has the
                     effect of overriding any value for these attributes obtained from the output
                     definition. The corresponding serialization parameter is not set (is
                     “absent”).</p></item><item><p>In the case of <code nobreak="false">item-separator</code>, setting the <termref def="dt-effective-value"/> of the
                     attribute to the special value <code nobreak="false">"#absent"</code> has the effect of
                     overriding any value for this attribute obtained from the output definition.
                     The corresponding serialization parameter is not set (is “absent”). It is not
                     possible to set the value of the serialization parameter to the literal
                     7-character string <code nobreak="false">"#absent"</code>. </p></item><item><p>In all other cases, the <termref def="dt-effective-value"/> of an attribute actually present on
                     this instruction takes precedence over the value defined in the selected output
                     definition.</p></item></ulist><p>In the case of the attributes <code nobreak="false">method</code>, <code nobreak="false">json-node-output-method</code>
                     <code nobreak="false">cdata-section-elements</code>, <code nobreak="false">suppress-indentation</code>, and
                     <code nobreak="false">use-character-maps</code>, the <termref def="dt-effective-value"/> of the attribute
                  contains an <termref def="dt-eqname">EQName</termref> or a space-separated list of
                     <termref def="dt-eqname">EQNames</termref>. Where lexical QNames are used in these attributes (whether prefixed
               or unprefixed), the namespace context is established in the same way as for the corresponding
               attributes of <elcode>xsl:output</elcode>: see <specref ref="id-default-serialization-parameters"/>.</p><p>The <code nobreak="false">output-version</code> attribute on the <elcode>xsl:result-document</elcode>
               instruction overrides the <code nobreak="false">version</code> attribute on
                  <elcode>xsl:output</elcode> (it has been renamed because <code nobreak="false">version</code> is
               available with a different meaning as a standard attribute: see <specref ref="standard-attributes"/>). In all other cases, attributes correspond if they
               have the same name.</p><p>There are some serialization parameters that apply to some output methods but not to
               others. For example, the <code nobreak="false">indent</code> attribute has no effect on the
                  <code nobreak="false">text</code> output method. If a value is supplied for an attribute that is
               inapplicable to the output method, its value is not passed to the serializer. The
               processor <rfc2119>may</rfc2119> validate the value of such an attribute, but is not
                  <rfc2119>required</rfc2119> to do so.</p><p>The <code nobreak="false">item-separator</code> serialization parameter
               is used when the <termref def="dt-raw-result"/> is used to construct a result tree
               by applying sequence normalization, and it is also used when the result tree is
               serialized. For example, if the sequence constructor delivers a sequence of
               integers, and the <code nobreak="false">text</code> serialization method is used, then the result of serialization
               will be a string obtained by converting each integer to a string, and separating the
               strings using the defined <code nobreak="false">item-separator</code>.</p><p>The <code nobreak="false">href</code> attribute is optional. The default value is the zero-length
               string. The <termref def="dt-effective-value"/> of the
               attribute <rfc2119>must</rfc2119> be a <termref def="dt-uri-reference">URI
                  Reference</termref>, which may be absolute or relative. If it is relative, then it is resolved against the <termref def="dt-base-output-uri"/>. There <rfc2119>may</rfc2119> be <termref def="dt-implementation-defined">implementation-defined</termref> restrictions on
               the form of absolute URI that may be used, but the implementation is not
                  <rfc2119>required</rfc2119> to enforce any restrictions. Any valid relative URI
                  reference
               <rfc2119>must</rfc2119> be accepted. Note that the zero-length string is a valid
               relative URI reference.</p><imp-def-feature id="idf-api-resultdocumenthref"> It is <termref def="dt-implementation-defined"/> how the URI appearing in the <code nobreak="false">href</code>
               attribute of <elcode>xsl:result-document</elcode> affects the way in which the result
               tree is delivered to the application. There <rfc2119>may</rfc2119> be restrictions on
               the form of this URI. </imp-def-feature><p>If the implementation provides an API to access <termref def="dt-secondary-result">secondary results</termref>, then it
                  <rfc2119>must</rfc2119> allow a secondary result to be identified by means of the
               absolutized value of the <code nobreak="false">href</code> attribute. In addition, if a <termref def="dt-final-result-tree"/> is constructed
               (that is, if the <termref def="dt-effective-value"/> of
                  <code nobreak="false">build-tree</code> is <code nobreak="false">yes</code>), then this value is used as the base
               URI of the document node at the root of the <termref def="dt-final-result-tree">final
                  result tree</termref>. </p><note><p>The base URI of the <termref def="dt-final-result-tree">final result
                     tree</termref> is not necessarily the same thing as the URI of its serialized
                  representation on disk, if any. For example, a server (or browser client) might
                  store final result trees only in memory, or in an internal disk cache. As long as
                  the processor satisfies requests for those URIs, it is irrelevant where they are
                  actually written on disk, if at all.</p></note><note><p>It will often be the case that one <termref def="dt-final-result-tree">final
                     result tree</termref> contains links to another final result tree produced
                  during the same transformation, in the form of a relative URI reference. The mechanism of associating a URI with a final
                  result tree has been chosen to allow the integrity of such links to be preserved
                  when the trees are serialized.</p><p>As well as being potentially significant in any API that provides access to final
                  result trees, the base URI of the new document node is relevant if the final
                  result tree, rather than being serialized, is supplied as input to a further
                  transformation.</p></note><p>The optional attributes <code nobreak="false">type</code> and <code nobreak="false">validation</code> may be used on
               the <elcode>xsl:result-document</elcode> instruction to validate the contents of
                  a <termref def="dt-final-result-tree"/>, and to determine the <termref def="dt-type-annotation">type
                  annotation</termref> that elements and attributes within the <termref def="dt-final-result-tree">final result tree</termref> will carry. The permitted
               values and their semantics are described in <specref ref="validating-document-nodes"/>. Any such validation is applied to the
               document node produced as the result of <xtermref spec="SE40" ref="sequence-normalization"/>.
               If sequence normalization does not take place (typically because the <termref def="dt-raw-result"/>
               is delivered to the application directly, or because the selected serialization method
               does not involve sequence normalization) then the <code nobreak="false">validation</code> and
               <code nobreak="false">type</code> attributes are ignored.</p><note><p>Validation applies after inserting item separators as determined by the
            <code nobreak="false">item-separator</code> serialization parameter, and an inappropriate choice
            of <code nobreak="false">item-separator</code> may cause the result to become invalid.</p></note><p>A <termref def="dt-processor">processor</termref>
               <rfc2119>may</rfc2119> allow a <termref def="dt-final-result-tree">final result
                  tree</termref> to be serialized. Serialization is described in <specref ref="serialization"/>. However, an implementation (for example, a <termref def="dt-processor">processor</termref> running in an environment with no access to
               writable filestore) is not <rfc2119>required</rfc2119> to support the serialization
               of <termref def="dt-final-result-tree">final result trees</termref>. An
               implementation that does not support the serialization of final result trees
                  <rfc2119>may</rfc2119> ignore the <code nobreak="false">format</code> attribute and the
               serialization attributes. Such an implementation <rfc2119>must</rfc2119> provide the
               application with some means of access to the (un-serialized) result tree, using its
               URI to identify it.</p><p>Implementations may provide additional mechanisms, outside the scope of this
               specification, for defining the way in which <termref def="dt-final-result-tree">final result trees</termref> are processed. Such mechanisms
                  <rfc2119>may</rfc2119> make use of the XSLT-defined attributes on the
                  <elcode>xsl:result-document</elcode> and/or <elcode>xsl:output</elcode> elements,
               or they <rfc2119>may</rfc2119> use additional elements or attributes in an <termref def="dt-implementation-defined">implementation-defined</termref> namespace.</p><example><head>Multiple Result Documents</head><p> The following example takes an XHTML document as input, and breaks it up so that
                  the text following each &lt;h1&gt; element is included in a separate document. A
                  new document <code nobreak="false">toc.html</code> is constructed to act as an index:</p><eg role="xslt-document" xml:space="preserve">&lt;xsl:stylesheet
	version="3.0"
	xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
	xmlns:xhtml="http://www.w3.org/1999/xhtml"&gt;
	
&lt;xsl:output name="toc-format" method="xhtml" indent="yes"
     doctype-system="http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"
     doctype-public="-//W3C//DTD XHTML 1.0 Strict//EN"/&gt;
            
&lt;xsl:output name="section-format" method="xhtml" indent="no"
     doctype-system="http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"
     doctype-public="-//W3C//DTD XHTML 1.0 Transitional//EN"/&gt;	
	 
&lt;xsl:template match="/"&gt;
  &lt;xsl:result-document href="toc.html" 
                       format="toc-format" 
                       validation="strict"&gt;
    &lt;html xmlns="http://www.w3.org/1999/xhtml"&gt;
      &lt;head&gt;&lt;title&gt;Table of Contents&lt;/title&gt;&lt;/head&gt;
      &lt;body&gt;
        &lt;h1&gt;Table of Contents&lt;/h1&gt;
        &lt;xsl:for-each select="/*/xhtml:body/(*[1] | xhtml:h1)"&gt;
          &lt;p&gt;
            &lt;a href="section{position()}.html"&gt;
              &lt;xsl:value-of select="."/&gt;
            &lt;/a&gt;
          &lt;/p&gt;
        &lt;/xsl:for-each&gt;
      &lt;/body&gt;
    &lt;/html&gt;
  &lt;/xsl:result-document&gt;
  &lt;xsl:for-each-group select="/*/xhtml:body/*" group-starting-with="xhtml:h1"&gt;
    &lt;xsl:result-document href="section{position()}.html" 
                         format="section-format" validation="strip"&gt;  	
      &lt;html xmlns="http://www.w3.org/1999/xhtml"&gt;
        &lt;head&gt;&lt;title&gt;&lt;xsl:value-of select="."/&gt;&lt;/title&gt;&lt;/head&gt;
        &lt;body&gt;
          &lt;xsl:copy-of select="current-group()"/&gt;
        &lt;/body&gt;
      &lt;/html&gt;
    &lt;/xsl:result-document&gt;
  &lt;/xsl:for-each-group&gt;
&lt;/xsl:template&gt;

&lt;/xsl:stylesheet&gt;</eg></example></div2><div2 id="result-document-restrictions"><head>Restrictions on the use of <elcode>xsl:result-document</elcode></head><p>There are restrictions on the use of the <elcode>xsl:result-document</elcode>
               instruction, designed to ensure that the results are fully interoperable even when
               processors optimize the sequence in which instructions are evaluated. Informally, the
               restriction is that the <elcode>xsl:result-document</elcode> instruction can only be
               used while writing a final result tree, not while writing to a temporary tree or a
               sequence. This restriction is defined formally as follows.</p><p>
               <termdef id="dt-output-state" term="output state">Each instruction in the <termref def="dt-stylesheet">stylesheet</termref> is evaluated in one of two possible
                     <term>output states</term>: <termref def="dt-final-output-state">final output
                     state</termref> or <termref def="dt-temporary-output-state">temporary output
                     state</termref>.</termdef></p><p>
               <termdef id="dt-final-output-state" term="final output state">The first of the two
                     <termref def="dt-output-state">output states</termref> is called <term>final
                     output</term> state. This state applies when instructions are writing to a
                     <termref def="dt-final-result-tree">final result tree</termref>.</termdef>
            </p><p>
               <termdef id="dt-temporary-output-state" term="temporary output state">The second of
                  the two <termref def="dt-output-state">output states</termref> is called
                     <term>temporary output</term> state. This state applies when instructions are
                  writing to a <termref def="dt-temporary-tree">temporary tree</termref> or any
                  other non-final destination.</termdef>
            </p><p>The instructions in the <termref def="dt-initial-named-template"/> are evaluated in
                  <termref def="dt-final-output-state">final output state</termref>. An instruction
               is evaluated in the same <termref def="dt-output-state">output state</termref> as its
               calling instruction, except that <elcode>xsl:variable</elcode>,
                  <elcode>xsl:param</elcode>, <elcode>xsl:with-param</elcode>, 
               <elcode>xsl:function</elcode>, <elcode>xsl:key</elcode>, <elcode>xsl:sort</elcode>,
                  <elcode>xsl:accumulator-rule</elcode>, and
                     <elcode>xsl:merge-key</elcode>
                always evaluate the instructions in their
               contained <termref def="dt-sequence-constructor">sequence constructor</termref> in
                  <termref def="dt-temporary-output-state">temporary output state</termref>.</p><p>
               <error spec="XT" type="dynamic" class="DE" code="1480"><p>It is a <termref def="dt-dynamic-error"> dynamic error</termref> to evaluate the
                        <elcode>xsl:result-document</elcode> instruction in <termref def="dt-temporary-output-state">temporary output state</termref>.</p></error>
            </p><p>
               <error spec="XT" type="dynamic" class="DE" code="1490"><p>It is a <termref def="dt-dynamic-error"> dynamic error</termref> for a transformation to
                     generate two or more <termref def="dt-final-result-tree">final result
                        trees</termref> with the same URI.</p></error>
            </p><note><p>Note, this means that it is an error to evaluate more than one
                     <elcode>xsl:result-document</elcode> instruction that omits the
                     <code nobreak="false">href</code> attribute, or to evaluate any
                     <elcode>xsl:result-document</elcode> instruction that omits the
                     <code nobreak="false">href</code> attribute if an initial <termref def="dt-final-result-tree">final result tree</termref> is created implicitly.</p></note><p>In addition, an implementation <rfc2119>may</rfc2119> raise this
               error if it is able to detect that two or more final result trees are generated with
               different URIs that refer to the same physical resource.</p><p>
               <error spec="XT" type="dynamic" class="DE" code="1500"><p>It is a <termref def="dt-dynamic-error"> dynamic error</termref> for a <termref def="dt-stylesheet">stylesheet</termref> to write to an external resource
                     and read from the same resource during a single transformation, if the same absolute URI is used to access the resource in
                        both cases. </p></error>
            </p><p>In addition, an implementation <rfc2119>may</rfc2119> raise this
               error if it is able to detect that a transformation writes to a resource and reads
               from the same resource using different URIs that refer to the same physical resource.
               Note that if the error is not detected, it is <termref def="dt-implementation-dependent"/> whether the document that is read from the
               resource reflects its state before or after the result tree is written.</p></div2><div2 id="current-output-uri"><head>The Current Output URI</head><p><termdef id="dt-current-output-uri" term="current output URI">The <term>current output URI</term> is the URI
                  associated with the <termref def="dt-principal-result"/> or <termref def="dt-secondary-result"/> that is currently being written.</termdef></p><div3 id="func-current-output-uri"><head>fn:current-output-uri</head><changes><change issue="407" PR="2274" date="2026-01-06">In XSLT 4.0, the function item <code nobreak="false">current-output-uri#0</code> retains the value of the current
         output URI within its captured context.</change></changes><glist><gitem><label>Summary</label><def><p>Returns the value of the <termref def="dt-current-output-uri"/>.</p></def></gitem><gitem><label>Signature</label><def><example role="signature"><proto isOp="no" prefix="fn" name="current-output-uri" return-type="xs:anyURI?" returnEmptyOk="no" returnSeq="no" returnVaries="no" isSchema="no" isDatatype="no" isSpecial="no"/></example></def></gitem><gitem><label>Properties</label><def><p>This function is <xtermref spec="FO40" ref="dt-deterministic">deterministic</xtermref>, <xtermref spec="FO40" ref="dt-focus-independent">focus-independent</xtermref>,  and <xtermref spec="FO40" ref="dt-context-dependent">context-dependent</xtermref>. </p></def></gitem><gitem><label>Rules</label><def><p>On initial invocation of a stylesheet component, the current output uri is set to the
         <termref def="dt-base-output-uri"/>.</p><p>During execution of an <elcode>xsl:result-document</elcode> instruction with an <code nobreak="false">href</code>
         attribute, the current output URI changes to the absolute URI obtained by resolving the <termref def="dt-effective-value"/>
         of the <code nobreak="false">href</code> attribute against the base output URI.</p><p>The current output URI is cleared (set to <termref def="dt-absent"/>) while evaluating stylesheet functions, 
            dynamic function calls, evaluation of global variables, stylesheet parameters, and patterns. 
            If the function is called when the current output URI is absent, the function returns the empty sequence.
         </p><p>The current output URI may also be <termref def="dt-absent"/> in the event that a stylesheet is invoked without supplying a
         <termref def="dt-base-output-uri"/>.</p></def></gitem><gitem><label>Notes</label><def><note><p>The current output URI is not cleared when evaluating a local variable, even though <elcode>xsl:result-document</elcode>
            cannot be used while evaluating a local variable. 
            The reason for this is to allow the value of <code nobreak="false">current-output-uri</code> to be set as the value of a 
            tunnel parameter, so that the original
            base output URI is accessible even when writing nested result documents.</p></note></def></gitem></glist></div3></div2><div2 id="validation"><head>Validation</head><changes><change issue="451" PR="635" date="2023-10-24">
                  The rules concerning the compatibility of schemas imported by different packages have 
                  been clarified. It is now explicitly stated that instructions that trigger validation 
                  must use the imported schema of the package in which validation is invoked. 
                  This differs from the current practice of some XSLT 3.0 processors, which may 
                  use (for example) a schema formed from the union of the imported schemas in all 
                  packages.
               </change><change issue="729" PR="1254" date="2024-06-08">
                  The rules concerning the interpretation of <code nobreak="false">xsi:schemaLocation</code>
                  and <code nobreak="false">xsi:noNamespaceSchemaLocation</code> attributes have been tightened up.
               </change><change issue="2029" PR="2030" date="2025-05-28">
                  In order to reduce duplication between the XSLT and XQuery specifications, description
                  of the validation process has been moved to the <emph>Functions and Operators</emph>
                  specification.
               </change></changes><p>It is possible to control the <termref def="dt-type-annotation"/> applied to
               individual element and attribute nodes as they are constructed. This is done using
               the <code nobreak="false">type</code> and <code nobreak="false">validation</code> attributes of the
                  <elcode>xsl:element</elcode>, <elcode>xsl:attribute</elcode>,
                  <elcode>xsl:copy</elcode>, <elcode>xsl:copy-of</elcode>,
                  <elcode>xsl:document</elcode>, and <elcode>xsl:result-document</elcode>
               instructions, or the <code nobreak="false">xsl:type</code> and <code nobreak="false">xsl:validation</code> attributes
               of a <termref def="dt-literal-result-element">literal result element</termref>.
                  The same attributes are used on
                     <elcode>xsl:source-document</elcode> and <elcode>xsl:merge-source</elcode> to control
                  validation of input documents.</p><p>The <code nobreak="false">[xsl:]type</code> attribute is used to request validation of an element or
               attribute against a specific simple or complex type defined in a schema. The
                  <code nobreak="false">[xsl:]validation</code> attribute is used to request validation against the
               global element or attribute declaration whose name matches the name of the element or
               attribute being validated.</p><p>The <code nobreak="false">[xsl:]type</code> and <code nobreak="false">[xsl:]validation</code> attributes are mutually
               exclusive. Both are optional, but if one is present then the other
                  <rfc2119>must</rfc2119> be omitted. If both attributes are omitted, the effect is
               the same as specifying the <code nobreak="false">validation</code> attribute with the value specified
               in the <code nobreak="false">[xsl:]default-validation</code> attribute of
                  the innermost containing element having such an attribute; if this is not
               specified, the effect is the same as specifying <code nobreak="false">validation="strip"</code>.</p><p>The <code nobreak="false">[xsl:]default-validation</code> attribute defines the
               default value of the <code nobreak="false">validation</code> attribute of all
                  <elcode>xsl:element</elcode>, <elcode>xsl:attribute</elcode>,
                  <elcode>xsl:copy</elcode>, <elcode>xsl:copy-of</elcode>,
                  <elcode>xsl:document</elcode>, and <elcode>xsl:result-document</elcode>
               instructions, and of the <code nobreak="false">xsl:validation</code> attribute of all
               <termref def="dt-literal-result-element">literal result elements</termref>,
               <phrase diff="chg" at="2022-01-01">appearing as descendants of the element 
                  on which the attribute appears, unless there is an inner element that defines 
                  a different default</phrase>. <phrase diff="del" at="2022-01-01">It also determines
               the validation applied to the implicit <termref def="dt-final-result-tree">final
                  result tree</termref> created in the absence of an
                  <elcode>xsl:result-document</elcode> instruction.</phrase> This default <phrase diff="del" at="2022-01-01">applies within the
               containing <termref def="dt-stylesheet-module">stylesheet module</termref> or
                  <termref def="dt-package"/>: it</phrase> does not extend to included or imported stylesheet
               modules or used packages. If the attribute is omitted, the default is
                  <code nobreak="false">strip</code>. The permitted values are <code nobreak="false">preserve</code> and
                  <code nobreak="false">strip</code>.</p><p diff="add" at="2022-01-01">
               The <code nobreak="false">default-validation</code> attribute on the outermost element of the principal
               stylesheet module of the <termref def="dt-top-level-package"/> also determines the validation 
               applied to the implicit final result tree created in the absence of an 
               <elcode>xsl:result-document</elcode> instruction. 
            </p><p>The <code nobreak="false">[xsl:]default-validation</code> attribute has no
               effect on the <elcode>xsl:source-document</elcode> and <elcode>xsl:merge-source</elcode>
               elements, which perform no validation unless explicitly requested.</p><p>
               <error spec="XT" type="static" class="SE" code="1505"><p>It is a <termref def="dt-static-error">static error</termref> if both the
                        <code nobreak="false">[xsl:]type</code> and <code nobreak="false">[xsl:]validation</code> attributes are
                     present on the <elcode>xsl:element</elcode>, <elcode>xsl:attribute</elcode>,
                        <elcode>xsl:copy</elcode>, <elcode>xsl:copy-of</elcode>,
                        <elcode>xsl:document</elcode>, <elcode>xsl:result-document</elcode>, <elcode>xsl:source-document</elcode>, or
                           <elcode>xsl:merge-source</elcode> elements, or on a <termref def="dt-literal-result-element">literal result element</termref>.</p></error>
            </p><p>Validation always uses the <xtermref spec="XP40" ref="dt-issd">in-scope schema definitions</xtermref>
               from the static context of the instruction that invokes validation.
               The relevant schema may be selected using the <code nobreak="false">[xsl:]schema-role</code> attribute of the instruction itself,
               or of a containing element. See also <specref ref="multiple-schemas"/>.</p><note><p>A stylesheet might take as its primary input a document conforming to schema <var>X</var>,
                  and produce as its primary output a document conforming to schema <var>Y</var>.
                  To be sure that the output is indeed valid against schema <var>Y</var>, the safest
                  course of action is to evaluate an <elcode>xsl:result-document</elcode> instruction using
                  an <code nobreak="false">[xsl:]schema-role</code> attribute that selects schema <var>Y</var> and nothing else. 
                  Otherwise, if the validation occurs within a module that imports both <var>X</var>
                  and <code nobreak="false">Y</code>, the outcome of validation might differ because of the
                  differences between the two schemas.</p></note><p>The detailed rules for validation vary depending on the kind of node being validated.
               The rules for element and attribute nodes are given in <specref ref="validating-constructed-nodes"/>, while those for document nodes are given in
                  <specref ref="validating-document-nodes"/>.</p><div3 id="validating-constructed-nodes"><head>Validating Constructed Elements and Attributes</head><div4 id="validating-using-validation-attribute"><head>Validation using the <code nobreak="false">[xsl:]validation</code> Attribute</head><p>The <code nobreak="false">[xsl:]validation</code> attribute defines the validation action to be
                     taken. It determines not only the <termref def="dt-type-annotation">type
                        annotation</termref> of the node that is constructed by the relevant
                     instruction itself, but also the type annotations of all element and attribute
                     nodes that have the constructed node as an ancestor. Conceptually, the
                     validation requested for a child element or attribute node is applied before
                     the validation requested for its parent element. For example, if the
                     instruction that constructs a child element specifies
                        <code nobreak="false">validation="strict"</code>, this will cause the child element to be
                     checked against an element declaration, but if the instruction that constructs
                     its parent element specifies <code nobreak="false">validation="strip"</code>, then the final
                     effect will be that the child node is annotated as <code nobreak="false">xs:untyped</code>.</p><p>In the paragraphs below, the term <emph>contained nodes</emph> means the
                     elements and attributes that have the newly constructed node as an
                     ancestor.</p><olist><item><p>The value <code nobreak="false">strip</code> indicates that the new node and each of the
                           contained nodes will have the <termref def="dt-type-annotation">type
                              annotation</termref>
                           <code nobreak="false">xs:untyped</code> if it is an element, or
                              <code nobreak="false">xs:untypedAtomic</code> if it is an attribute. Any previous type
                           annotation present on a contained element or attribute node (for example,
                           a type annotation that is present on an element copied from a source
                           document) is also replaced by <code nobreak="false">xs:untyped</code> or
                              <code nobreak="false">xs:untypedAtomic</code> as appropriate. The typed value of the
                           node is changed to be the same as its string value, as an instance of
                              <code nobreak="false">xs:untypedAtomic</code>. In the case of elements the
                              <code nobreak="false">nilled</code> property is set to <code nobreak="false">false</code>. The values
                           of the <code nobreak="false">is-id</code> and <code nobreak="false">is-idrefs</code> properties are
                           unchanged. Schema validation is not invoked.</p></item><item><p>The value <code nobreak="false">preserve</code> indicates that nodes that are copied will
                           retain their <termref def="dt-type-annotation">type
                           annotations</termref>, but nodes whose content is newly constructed will
                           be annotated as <code nobreak="false">xs:anyType</code> in the case of elements, or
                              <code nobreak="false">xs:untypedAtomic</code> in the case of attributes. Schema
                           validation is not invoked. The detailed effect depends on the
                           instruction:</p><olist><item><p>In the case of <elcode>xsl:element</elcode> and literal result
                                 elements, the new element has a <termref def="dt-type-annotation">type annotation</termref> of <code nobreak="false">xs:anyType</code>, and the
                                 type annotations of contained nodes are retained unchanged.</p><p>The <code nobreak="false">nilled</code>,
                                    <code nobreak="false">is-id</code> and <code nobreak="false">is-idrefs</code> properties on the
                                 new element are set to <code nobreak="false">false</code>.</p></item><item><p>In the case of <elcode>xsl:attribute</elcode>, the effect is
                                 exactly the same as specifying <code nobreak="false">validation="strip"</code>:
                                 that is, the new attribute will have the type annotation
                                    <code nobreak="false">xs:untypedAtomic</code>.</p><p>The <code nobreak="false">is-id</code> and
                                    <code nobreak="false">is-idrefs</code> properties on the new attribute are set
                                 to <code nobreak="false">false</code>.</p></item><item><p>In the case of <elcode>xsl:copy-of</elcode>, all the nodes that are
                                 copied will retain their type annotations unchanged. The values of their
                                       <code nobreak="false">nilled</code>, <code nobreak="false">is-id</code> and
                                       <code nobreak="false">is-idrefs</code> properties are also
                                 unchanged.</p></item><item><p>In the case of <elcode>xsl:copy</elcode>, the effect depends on the
                                 kind of node being copied.</p><olist><item><p>Where the node being copied is an attribute, the copied
                                       attribute will retain its <termref def="dt-type-annotation">type annotation</termref>
                                       and the values of its
                                             <code nobreak="false">is-id</code> and <code nobreak="false">is-idrefs</code>
                                          properties.</p></item><item><p>Where the node being copied is an element, the copied element
                                       will have a <termref def="dt-type-annotation">type
                                          annotation</termref> of <code nobreak="false">xs:anyType</code> (because
                                       this instruction does not copy the content of the element, it
                                       would be wrong to assume that the type is unchanged); but any
                                       contained nodes will have their type annotations retained in
                                       the same way as with <elcode>xsl:element</elcode>. The values of the
                                             <code nobreak="false">nilled</code>, <code nobreak="false">is-id</code>, and
                                             <code nobreak="false">is-idrefs</code> properties are handled in the
                                          same way as <elcode>xsl:element</elcode>.
                                    </p></item></olist></item></olist></item><item><p>The value <code nobreak="false">strict</code> indicates that 
                           schema validation is carried out according to the process described
                           in <xspecref spec="FO40" ref="xsd-validation"/>. The operand node
                           is the node being constructed, and the effective schema is
                           the in-scope schema definitions in the static context of the containing
                           instruction. The effect of constructing a node with
                           <code nobreak="false">[xsl:]validation="strict"</code> is equivalent to constructing
                           an untyped node <var>N</var>, and then validating it using the
                           expression;</p><eg xml:space="preserve"><code nobreak="false">fn:xsd-validator({'validation-mode':'strict'})(<var>N</var>) -&gt;
    if (?is-valid) then ?typed-node else error()</code></eg><p>More details on the error conditions appear below.</p></item><item><p>The value <code nobreak="false">lax</code> indicates that 
                           lax validation is carried out according to the process described
                           in <xspecref spec="FO40" ref="xsd-validation"/>. The operand node
                           is the node being constructed, and the effective schema is
                           the in-scope schema definitions in the static context of the containing
                           instruction. The effect of constructing a node with
                           <code nobreak="false">[xsl:]validation="lax"</code> is equivalent to constructing
                           an untyped node <var>N</var>, and then validating it using the
                           expression;</p><eg xml:space="preserve"><code nobreak="false">fn:xsd-validator({'validation-mode':'lax'})(<var>N</var>) -&gt;
    if (?is-valid) then ?typed-node else error()</code></eg><p>More details on the error conditions appear below.</p></item></olist><note><p>The effect of these rules is that when validation succeeds, the <code nobreak="false">validate</code>
         expression returns a copy of the operand node, augmented with type annotations and expanded
         default values. When validation fails (more accurately, when the outcome of validity assessment
         is that the operand node is found to be invalid), the expression raises a dynamic error.</p></note><note><p>If an element that is being validated has an <code nobreak="false">xsi:type</code>
                        attribute, then the value of the <code nobreak="false">xsi:type</code> attribute will
                        be taken into account when performing the validation. However, the
                        presence of an <code nobreak="false">xsi:type</code> attribute will not of itself
                        cause an element to be validated: if validation against a named type
                        is required, as distinct from validation against a top-level element
                        declaration, then it must be requested using the XSLT
                           <code nobreak="false">[xsl:]type</code> attribute on the instruction that invokes
                        the validation, as described in section <specref ref="validation-xsl-type"/>
                     </p></note><p>For reasons of backwards compatibility, the error conditions raised
                  by XSLT validation have their own error codes:</p><ulist><item><p>
                        <error spec="XT" type="type" class="TE" code="1510"><p>If the <code nobreak="false">validation</code> attribute of an
                                 <elcode>xsl:element</elcode>, <elcode>xsl:attribute</elcode>,
                                 <elcode>xsl:copy</elcode>, <elcode>xsl:copy-of</elcode>, or
                                 <elcode>xsl:result-document</elcode> instruction, or the
                                 <code nobreak="false">xsl:validation</code> attribute of a literal result element, has
                              the <termref def="dt-effective-value"/> <code nobreak="false">strict</code>, and schema validity assessment
                              concludes that the validity of the element or attribute is invalid or
                              unknown, a <termref def="dt-type-error">type error</termref> occurs. As
                              with other type errors, the error <rfc2119>may</rfc2119> be raised
                              statically if it can be detected statically. </p></error>
                     </p></item><item><p>
                        <error spec="XT" type="type" class="TE" code="1512"><p>If the <code nobreak="false">validation</code> attribute of an
                                 <elcode>xsl:element</elcode>, <elcode>xsl:attribute</elcode>,
                                 <elcode>xsl:copy</elcode>, <elcode>xsl:copy-of</elcode>, or
                                 <elcode>xsl:result-document</elcode> instruction, or the
                                 <code nobreak="false">xsl:validation</code> attribute of a literal result element, has
                              the <termref def="dt-effective-value"/> <code nobreak="false">strict</code>, and there is no matching
                              top-level declaration in the schema, then a <termref def="dt-type-error">type error</termref> occurs. As with other type errors, the error
                                 <rfc2119>may</rfc2119> be raised statically if it can be detected
                              statically. </p></error>
                     </p></item><item><p>
                        <error spec="XT" type="type" class="TE" code="1515"><p>If the <code nobreak="false">validation</code> attribute of an
                                 <elcode>xsl:element</elcode>, <elcode>xsl:attribute</elcode>,
                                 <elcode>xsl:copy</elcode>, <elcode>xsl:copy-of</elcode>, or
                                 <elcode>xsl:result-document</elcode> instruction, or the
                                 <code nobreak="false">xsl:validation</code> attribute of a literal result element, has
                              the <termref def="dt-effective-value"/> <code nobreak="false">lax</code>, and schema validity assessment
                              concludes that the element or attribute is invalid, a <termref def="dt-type-error">type error</termref> occurs. As with other type
                              errors, the error <rfc2119>may</rfc2119> be raised statically if it can
                              be detected statically. </p></error>
                     </p></item><item><p>
                     <error spec="XT" type="type" class="TE" code="1545"><p>A <termref def="dt-type-error">type error</termref> occurs if a
                              <code nobreak="false">type</code> or <code nobreak="false">validation</code> attribute is defined
                           (explicitly or implicitly) for an instruction that constructs a new
                           attribute node, if the effect of this is to cause the attribute value to
                           be validated against a type that is derived from, or constructed by list
                           or union from, the primitive types <code nobreak="false">xs:QName</code> or
                              <code nobreak="false">xs:NOTATION</code>.</p></error>
                  </p></item></ulist></div4><div4 id="validation-xsl-type"><head>Validation using the <code nobreak="false">[xsl:]type</code> Attribute</head><p>The <code nobreak="false">[xsl:]type</code> attribute takes as its value an 
                     <phrase diff="chg" at="2022-01-01"><xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="XP40" ref="prod-xpath40-EQName" xlink:type="simple"/></phrase>.
                     If it is a lexical QName with no prefix, it is
                     expanded using the default namespace for elements and types.
                     This <rfc2119>must</rfc2119> be the name of a type definition included in the
                        <termref def="dt-in-scope-schema-component">in-scope schema
                        components</termref> for the stylesheet. </p><p>If the <code nobreak="false">[xsl:]type</code> attribute is present, then the newly constructed
                     element or attribute is validated against the type definition identified by
                     this attribute. Schema validation is carried out according to the process described
                           in <xspecref spec="FO40" ref="xsd-validation"/>. The operand node
                           is the node being constructed, and the effective schema is
                           the in-scope schema definitions in the static context of the containing
                           instruction. The effect is equivalent to constructing
                           an untyped node <var>N</var>, and then validating it using the
                           expression, where <var>T</var> is the QName obtained by expanding the
                  value of the <code nobreak="false">[xsl:]type</code> attribute:</p><eg xml:space="preserve"><code nobreak="false">fn:xsd-validator(<var>N</var>, {'type':<var>T</var>})(<var>N</var>) -&gt;
    if (?is-valid) then ?typed-node else error()</code></eg><p>For reasons of backwards compatibility, the error conditions raised
                  by XSLT validation have their own error codes:</p><ulist><item><p>If the element or attribute is not considered valid, as defined above,
                           the transformation fails <errorref class="TE" code="1540"/>.</p></item><item><p>If an element node is validated against the type
                        <code nobreak="false">xs:untyped</code>, the effect is the same as specifying
                        <code nobreak="false">validation="strip"</code>: that is, the elements and attributes in the
                     subtree rooted at the target element are copied with a type annotation of
                        <code nobreak="false">xs:untyped</code> or <code nobreak="false">xs:untypedAtomic</code> respectively.</p></item><item><p>If an element or attribute node is validated against the type
                        <code nobreak="false">xs:untypedAtomic</code>, the effect is the same as specifying
                        <code nobreak="false">[xsl:]type="xs:string"</code> except that when validation succeeds,
                     the returned element or attribute has a type annotation of
                        <code nobreak="false">xs:untypedAtomic</code>. Validation fails in the case of an element
                     with element children.</p></item><item><p>
                     <error spec="XT" type="static" class="SE" code="1520"><p>It is a <termref def="dt-static-error">static error</termref> if the
                           value of the <code nobreak="false">type</code> attribute of an
                              <elcode>xsl:element</elcode>, <elcode>xsl:attribute</elcode>,
                              <elcode>xsl:copy</elcode>, <elcode>xsl:copy-of</elcode>,
                              <elcode>xsl:document</elcode>, <elcode>xsl:result-document</elcode>,
                           <phrase diff="add" at="E"><elcode>xsl:source-document</elcode>, or 
                              <elcode>xsl:merge-source</elcode></phrase>
                           instruction, or the <code nobreak="false">xsl:type</code> attribute of a literal result
                           element, is not a valid <code nobreak="false">QName</code>, or if it uses a prefix that
                           is not defined in <phrase diff="chg" at="2023-05-04">the <termref def="dt-applicable-static-namespaces"/>
                           of the containing instruction</phrase>, or if the QName is
                           not the name of a type definition included in the <termref def="dt-in-scope-schema-component">in-scope schema
                              components</termref> for the <termref def="dt-package">package</termref>.
                        </p></error>
                  </p></item><item><p>
                     <error spec="XT" type="static" class="SE" code="1530"><p>It is a <termref def="dt-static-error">static error</termref> if the
                           value of the <code nobreak="false">type</code> attribute of an
                              <elcode>xsl:attribute</elcode> instruction refers to a complex type
                           definition</p></error>.</p></item><item><p>
                     
                     <error spec="XT" type="type" class="TE" code="1535"><p>It is a <termref def="dt-type-error">type error</termref> if the value of
                           the <code nobreak="false">type</code> attribute of an <elcode>xsl:copy</elcode> or
                              <elcode>xsl:copy-of</elcode> instruction refers to a complex type
                           definition and one or more of the items being copied is an attribute
                           node.</p></error></p></item><item><p>
                     <error spec="XT" type="type" class="TE" code="1540"><p>It is a <termref def="dt-type-error">type error</termref> if an
                              <code nobreak="false">[xsl:]type</code> attribute is defined for a constructed element
                           or attribute, and the outcome of schema validity assessment against that
                           type is that the <code nobreak="false">validity</code> property of that element or
                           attribute information item is other than <code nobreak="false">valid</code>.</p></error>
                  </p><note><p>Like other type errors, this error may be raised statically if it can be
                        detected statically. For example, the instruction <code nobreak="false">&lt;xsl:attribute
                           name="dob" type="xs:date"&gt;1999-02-29&lt;/xsl:attribute&gt;</code> may
                        result in a static error being raised. If the error is not raised
                        statically, it will be raised when the instruction is evaluated.</p></note></item></ulist></div4><div4 id="id-xsi-schema-location"><head>The <code nobreak="false">xsi:schemaLocation</code> and <code nobreak="false">xsi:noNamespaceSchemaLocation</code> attributes</head><p>It is <termref def="dt-implementation-defined"/> whether the validity assessment
                  process takes account of any <code nobreak="false">xsi:schemaLocation</code> or <code nobreak="false">xsi:noNamespaceSchemaLocation</code>
                  attributes in the tree being validated. If it does so, then it <rfc2119>should</rfc2119>
                  adhere to the following rules:</p><olist><item><p>Any schema loaded using these attributes must be 
                        <xtermref spec="DM40" ref="dt-schema-compatible">compatible</xtermref> 
                     with the schema in the static context from which validation is invoked.</p></item><item><p>Any schema loaded using these attributes must not override
                     or redefine any schema components in the static context.</p></item><item><p>Any schema components loaded using this mechanism must be
                     used for this validity assessment only, and must not 
                     affect the outcome of any subsequent validity assessments of other documents.</p><note><p>A processor may choose to cache such schema components but the existence
                     of such a cache should only affect performance, not the validation outcome.</p></note></item></olist><p>A consequence of validating a document using schema components that are not 
                     in the static context is that nodes may be annotated with types 
                     that are not in the static context. But the rules for
                     <xtermref spec="DM40" ref="dt-schema-compatible">schema compatibility</xtermref>
                     mean that this is not a problem.</p></div4></div3><div3 id="validating-document-nodes"><head>Validating Document Nodes</head><p>It is possible to apply validation to a document node. This happens when a new
                  document node is constructed by one of the XSLT elements <elcode>xsl:source-document</elcode>, <elcode>xsl:merge-source</elcode>, <elcode>xsl:document</elcode>,
                     <elcode>xsl:result-document</elcode>, <elcode>xsl:copy</elcode>, or
                     <elcode>xsl:copy-of</elcode>, and this element has a <code nobreak="false">type</code>
                  attribute, or a <code nobreak="false">validation</code> attribute with the value
                     <code nobreak="false">strict</code> or <code nobreak="false">lax</code>.</p><p>Document-level validation is not applied to the document node that is created
                  implicitly when a variable-binding element has no <code nobreak="false">select</code> attribute
                  and no <code nobreak="false">as</code> attribute (see <specref ref="temporary-trees"/>). This is
                  equivalent to using <code nobreak="false">validation="preserve"</code> on
                     <elcode>xsl:document</elcode>: nodes within such trees retain their <termref def="dt-type-annotation">type annotation</termref>. Similarly, validation is
                  not applied to document nodes created using <elcode>xsl:message</elcode>
                  or <elcode>xsl:assert</elcode>. </p><p>The values <code nobreak="false">validation="preserve"</code> and <code nobreak="false">validation="strip"</code>
                  do not request validation. In the first case, all element and attribute nodes
                  within the tree rooted at the new document node retain their <termref def="dt-type-annotation">type annotations</termref>. In the second case,
                  elements within the tree have their type annotation set to
                  <code nobreak="false">xs:untyped</code>, while attributes have their type annotation set to
                     <code nobreak="false">xs:untypedAtomic</code>.</p><p>When validation is requested for a document node (that is, when
                     <code nobreak="false">validation</code> is set to <code nobreak="false">strict</code> or <code nobreak="false">lax</code>, or
                  when a <code nobreak="false">type</code> attribute is present), the following processing takes
                  place:</p><ulist><item><p>
                        <error spec="XT" type="type" class="TE" code="1550"><p>A <termref def="dt-type-error">type error</termref> occurs
                                 <error.extra>when a document node is validated</error.extra> unless
                              the children of the document node comprise exactly one element node,
                              no text nodes, and zero or more comment and processing instruction
                              nodes, in any order.</p></error>
                     </p></item><item><p>The single element node child is validated, using the supplied values of the
                           <code nobreak="false">validation</code> and <code nobreak="false">type</code> attributes, as described in
                           <specref ref="validating-constructed-nodes"/>.</p><note><p>The <code nobreak="false">type</code> attribute on <elcode>xsl:source-document</elcode>,
                              <elcode>xsl:document</elcode> and
                           <elcode>xsl:result-document</elcode>, and on <elcode>xsl:copy</elcode>
                           and <elcode>xsl:copy-of</elcode> when copying a document node, thus
                           refers to the required type of the element node that is the only element
                           child of the document node. It does not refer to the type of the document
                           node itself.</p></note></item><item><p>The validation rule <quote>Validation Root Valid (ID/IDREF)</quote> is
                        applied to the single element node child of the document node. This means
                        that validation will fail if there are non-unique ID values or dangling
                        IDREF values in the document tree.</p></item><item><p>Identity constraints, as defined in section 3.11 of <bibref ref="xmlschema-1"/>, are checked. (This refers to constraints defined
                        using <code nobreak="false">xs:unique</code>, <code nobreak="false">xs:key</code>, and
                           <code nobreak="false">xs:keyref</code>.)</p></item><item><p>There is no check that the tree contains unparsed entities whose names match
                        the values of nodes of type <code nobreak="false">xs:ENTITY</code> or
                           <code nobreak="false">xs:ENTITIES</code>. This is because there is no facility in XSLT
                           3.0 to create unparsed entities in a
                           <termref def="dt-result-tree">result tree</termref>. It is possible to
                        add unparsed entity declarations to the result document by referencing a
                        suitable DOCTYPE during serialization.</p></item><item><p>All other children of the document node (comments and processing
                        instructions) are copied unchanged.</p></item></ulist><p>
                  <error spec="XT" type="type" class="TE" code="1555"><p>It is a <termref def="dt-type-error">type error</termref> if, when
                        validating a document node, document-level constraints (such as ID/IDREF
                        constraints) are not satisfied. 
                        </p></error>
               </p></div3><div3 id="validating-xml-id"><head>Validating <code nobreak="false">xml:id</code> attributes</head><p>This section provides a non-normative summary of the effect of validation on
               attributes named <code nobreak="false">xml:id</code>. The normative rules can be inferred from rules
               given elsewhere in this section.</p><olist><item><p>When an attribute named <code nobreak="false">xml:id</code> is encountered
                  in the course of validation:</p><olist><item><p>A validation error occurs if it the attribute is not lexically valid against type <code nobreak="false">xs:ID</code>.</p></item><item><p>The typed value of the attribute is whitespace-normalized.</p></item><item><p>The attribute is labeled with type annotation <code nobreak="false">xs:ID</code>.</p></item><item><p>The attribute acquires the <code nobreak="false">is-id</code> property.</p></item></olist></item><item><p>The previous rule applies whether validation is strict, lax, or by type; 
                     validation will never fail (or be skipped) on the grounds
                  that no global attribute declaration named <code nobreak="false">xsl:id</code> is available.</p></item><item><p>Checking <code nobreak="false">xml:id</code> attributes for uniqueness happens if and only if
                  validation is applied at the level of a document node.</p></item></olist></div3></div2></div1><div1 id="serialization"><head>Serialization</head><p>A <termref def="dt-processor">processor</termref>
            <rfc2119>may</rfc2119> output a <termref def="dt-final-result-tree">final result
               tree</termref> as a sequence of octets, although it is not
               <rfc2119>required</rfc2119> to be able to do so (see <specref ref="conformance"/>).
            This process is described as <term>serialization</term>.
            Stylesheet authors can use <elcode>xsl:output</elcode> declarations to specify how they
            wish result trees to be serialized. If a processor serializes a final result tree, it
               <rfc2119>must</rfc2119> do so as specified by these declarations.</p><p>The rules governing the output of the serializer are defined in <bibref ref="xslt-xquery-serialization-40"/>. 
            The serialization is controlled using a number
            of serialization parameters. The values of these serialization parameters may be set
            within the <termref def="dt-stylesheet">stylesheet</termref>, using the
               <elcode>xsl:output</elcode>, <elcode>xsl:result-document</elcode>, and
               <elcode>xsl:character-map</elcode> declarations.</p><div2 id="id-xsl-output-declaration"><head>The <code nobreak="false">xsl:output</code> declaration</head><changes><change issue="530" PR="534" date="2023-06-09">
                  A new serialization parameter <code nobreak="false">escape-solidus</code> is provided to control
                  whether the character <code nobreak="false">/</code> is escaped as <code nobreak="false">\/</code> by the
                  JSON serialization method.
               </change><change issue="938" PR="2259" date="2025-11-02">
                  A new serialization parameter <code nobreak="false">canonical</code> is available to give control
                  over serialization of XML, XHTML, and JSON.
               </change><change issue="1538" PR="1497 1546" date="2024-11-13">
                  A new serialization parameter <code nobreak="false">json-lines</code> is available to enable
                  output as one JSON value per line.
               </change></changes><e:element-syntax xmlns:e="http://www.w3.org/1999/XSL/Spec/ElementSyntax" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" name="output">
      <e:in-category name="declaration"/>
      <e:attribute name="name">
         <e:data-type name="eqname"/>
      </e:attribute>
      <e:attribute name="method">
         <e:constant value="xml"/>
         <e:constant value="html"/>
         <e:constant value="xhtml"/>
         <e:constant value="text"/>
         <e:constant value="json"/>
         <e:constant value="adaptive"/>
         <e:data-type name="eqname"/>
      </e:attribute>
      <e:attribute name="allow-duplicate-names">
         <e:data-type name="boolean"/>
      </e:attribute>
      <e:attribute name="build-tree">
         <e:data-type name="boolean"/>
      </e:attribute>
      <e:attribute name="byte-order-mark">
         <e:data-type name="boolean"/>
      </e:attribute>
      <e:attribute name="canonical">
         <e:data-type name="boolean"/>
      </e:attribute>
      <e:attribute name="cdata-section-elements">
         <e:data-type name="eqnames"/>
      </e:attribute>
      <e:attribute name="doctype-public">
         <e:data-type name="string"/>
      </e:attribute>
      <e:attribute name="doctype-system">
         <e:data-type name="string"/>
      </e:attribute>
      <e:attribute name="encoding">
         <e:data-type name="string"/>
      </e:attribute>
      <e:attribute name="escape-solidus">
         <e:data-type name="boolean"/>
      </e:attribute>
      <e:attribute name="escape-uri-attributes">
         <e:data-type name="boolean"/>
      </e:attribute>
      <e:attribute name="html-version">
         <e:data-type name="decimal"/>
      </e:attribute>
      <e:attribute name="include-content-type">
         <e:data-type name="boolean"/>
      </e:attribute>
      <e:attribute name="indent">
         <e:data-type name="boolean"/>
      </e:attribute>
      <e:attribute name="item-separator">
         <e:data-type name="string"/>
      </e:attribute>
      <e:attribute name="json-lines">
         <e:data-type name="boolean"/>
      </e:attribute>
      <e:attribute name="json-node-output-method">
         <e:constant value="xml"/>
         <e:constant value="html"/>
         <e:constant value="xhtml"/>
         <e:constant value="text"/>
         <e:data-type name="eqname"/>
      </e:attribute>
      <e:attribute name="media-type">
         <e:data-type name="string"/>
      </e:attribute>
      <e:attribute name="normalization-form">
         <e:constant value="NFC"/>
         <e:constant value="NFD"/>
         <e:constant value="NFKC"/>
         <e:constant value="NFKD"/>
         <e:constant value="fully-normalized"/>
         <e:constant value="none"/>
         <e:data-type name="nmtoken"/>
      </e:attribute>
      <e:attribute name="omit-xml-declaration">
         <e:data-type name="boolean"/>
      </e:attribute>
      <e:attribute name="parameter-document">
         <e:data-type name="uri"/>
      </e:attribute>
      <e:attribute name="standalone">
         <e:data-type name="boolean"/>
         <e:constant value="omit"/>
      </e:attribute>
      <e:attribute name="suppress-indentation">
         <!--see bug 6535-->
         <e:data-type name="eqnames"/>
      </e:attribute>
      <e:attribute name="undeclare-prefixes">
         <e:data-type name="boolean"/>
      </e:attribute>
      <e:attribute name="use-character-maps">
         <e:data-type name="eqnames"/>
      </e:attribute>
      <e:attribute name="version">
         <e:data-type name="nmtoken"/>
      </e:attribute>
      <e:empty/>
      <e:allowed-parents>
         <e:parent name="package"/>
         <e:parent name="stylesheet"/>
         <e:parent name="transform"/>
      </e:allowed-parents>
   </e:element-syntax><p>The <elcode>xsl:output</elcode> declaration is optional; if used, it
               <rfc2119>must</rfc2119> always appear as a <termref def="dt-top-level">top-level</termref> element within a stylesheet module.</p><p>A <termref def="dt-stylesheet">stylesheet</termref> may contain multiple
               <elcode>xsl:output</elcode> declarations and may include or import stylesheet modules
            that also contain <elcode>xsl:output</elcode> declarations. The name of an
               <elcode>xsl:output</elcode> declaration is the value of its <code nobreak="false">name</code>
            attribute, if any.</p><p>
            <termdef id="dt-output-definition" term="output definition">All the
                  <elcode>xsl:output</elcode> declarations within a
                     <termref def="dt-package">package</termref> that share the same name
               are grouped into a named <term>output definition</term>; those that have no name are
               grouped into a single unnamed output definition.</termdef>
         </p><p>An output definition is scoped to a package. If this is a <termref def="dt-library-package">library package</termref> the output definition applies only
            to <elcode>xsl:result-document</elcode> instructions within the same package. If it is
            the <termref def="dt-top-level-package">top-level package</termref>, the output
            definition applies to <elcode>xsl:result-document</elcode> instructions within the same
            package and also to the implicit <termref def="dt-final-result-tree">final result
               tree</termref>.</p><p>A stylesheet always includes an unnamed <termref def="dt-output-definition">output
               definition</termref>; in the absence of an unnamed <elcode>xsl:output</elcode>
            declaration, the unnamed output definition is equivalent to the one that would be used
            if the stylesheet contained an <elcode>xsl:output</elcode> declaration having no
            attributes.</p><p>A named <termref def="dt-output-definition">output definition</termref> is used when its
            name matches the <code nobreak="false">format</code> attribute used in an
               <elcode>xsl:result-document</elcode> element. The unnamed output definition is used
            when an <elcode>xsl:result-document</elcode> element omits the <code nobreak="false">format</code>
            attribute. It is also used when serializing the <termref def="dt-principal-result"/>.
            .</p><p>All the <elcode>xsl:output</elcode> elements making up an <termref def="dt-output-definition">output definition</termref> are effectively merged. For
            those attributes whose values are namespace-sensitive, the merging is done after
               <termref def="dt-lexical-qname">lexical QNames</termref> have been converted into
               <termref def="dt-expanded-qname">expanded QNames</termref>. For the
               <code nobreak="false">cdata-section-elements</code>
            and <code nobreak="false">suppress-indentation</code> attributes, the
            output definition uses the union of the values from all the constituent
            <elcode>xsl:output</elcode> declarations. For the <code nobreak="false">use-character-maps</code>
            attribute, the output definition uses the concatenation of the sequences of <termref def="dt-expanded-qname">expanded QNames</termref> values from all the constituent
               <elcode>xsl:output</elcode> declarations, taking them in order of increasing <termref def="dt-import-precedence">import precedence</termref>, or where several have the
            same import precedence, in <termref def="dt-declaration-order">declaration
               order</termref>. For other attributes, the <termref def="dt-output-definition">output
               definition</termref> uses the value of that attribute from the
               <elcode>xsl:output</elcode> declaration with the highest <termref def="dt-import-precedence">import precedence</termref>.</p><p>The <code nobreak="false">parameter-document</code> attribute allows serialization
            parameters to be supplied in an external document. The external document must contain an
               <code nobreak="false">output:serialization-parameters</code> element with the format described in
               <xspecref spec="SE40" ref="serparams-in-xdm-instance"/>, and the parameters are
            interpreted as described in that specification.</p><p>If present, the URI supplied in the <code nobreak="false">parameter-document</code>
            attribute is dereferenced, after resolution against the base URI of the
               <elcode>xsl:output</elcode> element if it is a relative reference. 
            The parameter document <rfc2119>should</rfc2119> be read during static analysis of the stylesheet. 
            A serialization error occurs
            if the result of dereferencing the URI is ill-formed or invalid; but if no document can
            be found at the specified location, the attribute <rfc2119>should</rfc2119> be ignored.</p><p>A serialization parameter specified in the
               <code nobreak="false">parameter-document</code> takes precedence over a value supplied directly in
            the output declaration, except that the values of the
               <code nobreak="false">cdata-section-elements</code> and <code nobreak="false">suppress-indentation</code> attributes
            are merged in the same way as when multiple <elcode>xsl:output</elcode> declarations are
            merged.</p><p>
            <error spec="XT" type="static" class="SE" code="1560"><p>It is a <termref def="dt-static-error">static error</termref> if two
                     <elcode>xsl:output</elcode> declarations within an <termref def="dt-output-definition">output definition</termref> specify explicit values
                  for the same attribute (other than <code nobreak="false">cdata-section-elements</code>, <code nobreak="false">suppress-indentation</code>, and
                     <code nobreak="false">use-character-maps</code>), with the values of the attributes being not
                  equal, unless there is another <elcode>xsl:output</elcode> declaration within the
                  same <termref def="dt-output-definition">output definition</termref> that has
                  higher import precedence and that specifies an explicit value for the same
                  attribute. </p></error>
         </p><p diff="add" at="2022-01-01">
            If the result is not serialized, then the decision whether to return the raw result 
            or to construct a tree depends on the <termref def="dt-effective-value"/> of the <code nobreak="false">build-tree</code> attribute. 
            If the effective value of the <code nobreak="false">build-tree</code> attribute is <code nobreak="false">yes</code>, then a 
            final result tree is created by invoking the process of sequence normalization. Conversely, 
            if the result is serialized, then the decision whether or not to construct a tree depends 
            on the choice of serialization method, and the <code nobreak="false">build-tree</code> attribute is 
            then ignored. For example, with <code nobreak="false">method="xml"</code> a tree is always constructed, 
            whereas with <code nobreak="false">method="json"</code> a tree is never constructed.
         </p><note><p>The default for <code nobreak="false">build-tree</code> may differ for user-defined serialization
               methods or for serialization methods introduced in future versions of this
               specification.</p></note></div2><div2 id="id-default-serialization-parameters"><head>Serialization parameters</head><changes><change issue="1548" PR="1560" date="2024-11-09">
                  The default value for the <code nobreak="false">indent</code> parameter is now defined to be
                  <code nobreak="false">no</code> for all output methods other than <code nobreak="false">html</code> and <code nobreak="false">xhtml</code>.
               </change></changes><p>If none of the <elcode>xsl:output</elcode> declarations within an <termref def="dt-output-definition">output definition</termref> specifies a value for a
            particular attribute, then the corresponding serialization parameter takes a default
            value. The default value depends on the chosen output method.</p><p>There are some serialization parameters that apply to some output methods but not to
            others. For example, the <code nobreak="false">indent</code> attribute has no effect on the
               <code nobreak="false">text</code> output method. If a value is supplied for an attribute that is
            inapplicable to the output method, its value is not passed to the serializer. The
            processor <rfc2119>may</rfc2119> validate the value of such an attribute, but is not
               <rfc2119>required</rfc2119> to do so.</p><p>An implementation <rfc2119>may</rfc2119> allow the attributes of the
               <elcode>xsl:output</elcode> declaration to be overridden, or the default values to be
            changed, using the API that controls the transformation.</p><p>The location to which <termref def="dt-final-result-tree">final result trees</termref>
            are serialized (whether in filestore or elsewhere) is <termref def="dt-implementation-defined">implementation-defined</termref> (which in practice
               <rfc2119>may</rfc2119> mean that it is controlled using an implementation-defined
            API). However, these locations <rfc2119>must</rfc2119> satisfy the constraint that when
            two <termref def="dt-final-result-tree">final result trees</termref> are both created
            (implicitly or explicitly) using relative URI references in the <code nobreak="false">href</code> attribute of the
               <elcode>xsl:result-document</elcode> instruction, then these relative URI references may be used to construct references from one
            tree to the other, and such references <rfc2119>must</rfc2119> remain valid when both
            result trees are serialized. </p><imp-def-feature id="idf-api-serializationlocation">If serialization is supported, then the
            location to which a <termref def="dt-final-result-tree">final result tree</termref> is
            serialized is implementation-defined, subject to the constraint that relative URI
               references used to reference one tree from another
            remain valid.</imp-def-feature><p>The <code nobreak="false">method</code> attribute on the <elcode>xsl:output</elcode> element identifies
            the overall method that is to be used for outputting the <termref def="dt-final-result-tree">final result tree</termref>.</p><p>
            <error spec="XT" type="static" class="SE" code="1570"><p>The value <error.extra>of the <code nobreak="false">method</code> attribute on
                        <elcode>xsl:output</elcode>
                  </error.extra>
                  <rfc2119>must</rfc2119> (if present) be a valid <termref def="dt-eqname">EQName</termref>. 
                  If it is a <termref def="dt-lexical-qname">lexical
                     QName</termref> in no namespace, then it identifies a method specified in
                     <bibref ref="xslt-xquery-serialization-40"/> and <rfc2119>must</rfc2119> be one
                  of <code nobreak="false">xml</code>, <code nobreak="false">html</code>, <code nobreak="false">xhtml</code>, 
                  <code nobreak="false">text</code>, <code nobreak="false">json</code>, or <code nobreak="false">adaptive</code>.</p></error> If it is a <termref def="dt-lexical-qname">lexical QName</termref> with a
            prefix, then the <termref def="dt-lexical-qname">lexical QName</termref> is expanded
            into an <termref def="dt-expanded-qname">expanded QName</termref> as described in
               <specref ref="qname"/>. An <termref def="dt-expanded-qname">expanded QName</termref>
            with a non-absent namespace identifies an <termref def="dt-implementation-defined"/> output method 
            whose the behavior is not specified by this document.</p><p>The default for the <code nobreak="false">method</code> attribute depends on the contents of the tree
            being serialized, and is chosen as follows. If the document node of the <termref def="dt-final-result-tree">final result tree</termref> has an element child, and any
            text nodes preceding the first element child of the document node of the result tree
            contain only whitespace characters, then:</p><ulist><item><p>If the <termref def="dt-expanded-qname">expanded QName</termref> of this first
                  element child has local part <code nobreak="false">html</code> (in lower case), and namespace URI
                     <code nobreak="false">http://www.w3.org/1999/xhtml</code>, then the default output method is
                  normally <code nobreak="false">xhtml</code>. However, if the
                        <termref def="dt-effective-version"/> of the outermost element of the
                        <termref def="dt-principal-stylesheet-module">principal stylesheet
                        module</termref> in the <termref def="dt-top-level-package"/> has the value
                        <code nobreak="false">1.0</code>, and if the result tree is generated implicitly
                  (rather than by an explicit <elcode>xsl:result-document</elcode> instruction),
                  then the default output method in this situation is <code nobreak="false">xml</code>.</p></item><item><p>If the <termref def="dt-expanded-qname">expanded QName</termref> of this first
                  element child has local part <code nobreak="false">html</code> (in any combination of upper and
                  lower case) and a null namespace URI, then the default output method is
                     <code nobreak="false">html</code>.</p></item></ulist><p>In all other cases, the default output method is <code nobreak="false">xml</code>.</p><p>The default output method is used if the selected <termref def="dt-output-definition">output definition</termref> does not include a <code nobreak="false">method</code> attribute.</p><p>The other attributes on <elcode>xsl:output</elcode> provide parameters for the output
            method. The following attributes are allowed:</p><ulist><item><p> The value of the <code nobreak="false">encoding</code> attribute provides the value of the
                     <code nobreak="false">encoding</code> parameter to the serialization method. The default value
                  is <termref def="dt-implementation-defined"/>, but in the case of the
                     <code nobreak="false">xml</code> and <code nobreak="false">xhtml</code> methods it <rfc2119>must</rfc2119> be
                  either <code nobreak="false">UTF-8</code> or <code nobreak="false">UTF-16</code>. </p><imp-def-feature id="idf-defaults-serialization">The default value of the
                     <code nobreak="false">encoding</code> attribute of the <elcode>xsl:output</elcode> element is
                  implementation-defined. Where the encoding is UTF-8, the default for the
                     <code nobreak="false">byte-order-mark</code> attribute is
                  implementation-defined.</imp-def-feature></item><item><p>The <code nobreak="false">byte-order-mark</code> attribute defines whether a byte order mark is
                  written at the start of the file. If the value <code nobreak="false">yes</code> is specified, a
                  byte order mark is written; if <code nobreak="false">no</code> is specified, no byte order mark is
                  written. The default value depends on the encoding used. If the encoding is
                     <code nobreak="false">UTF-16</code>, the default is <code nobreak="false">yes</code>; for <code nobreak="false">UTF-8</code> it
                  is <termref def="dt-implementation-defined"/>, and for all other encodings it is
                     <code nobreak="false">no</code>. The value of the byte order mark indicates whether high order
                  bytes are written before or after low order bytes; the actual byte order used is
                     <termref def="dt-implementation-dependent">implementation-dependent</termref>,
                  unless it is defined by the selected encoding. </p></item><item><p> The value of the <code nobreak="false">canonical</code> attribute provides the value of the
                     <code nobreak="false">canonical</code> parameter to the serialization method. 
                  The default value is <code nobreak="false">no</code>.
               </p></item><item><p> The <code nobreak="false">cdata-section-elements</code> attribute is a whitespace-separated list
                  of QNames. The default value is an empty list. After expansion of these names
                  using the <phrase diff="chg" at="2023-05-04"><termref def="dt-applicable-static-namespaces"/></phrase> for the <elcode>xsl:output</elcode>
                  declaration in which they appear, this list of names provides the value of the
                     <code nobreak="false">cdata-section-elements</code> parameter to the serialization method. In
                  the case of an unprefixed name, the default namespace (that is, the namespace
                  declared using <code nobreak="false">xmlns="uri"</code>) is used. </p><note><p>This differs from the rule for most other QNames used in a stylesheet. The
                     reason is that these names refer to elements in the result document, and
                     therefore follow the same convention as the name of a literal result element or
                     the <code nobreak="false">name</code> attribute of <elcode>xsl:element</elcode>.</p></note></item><item><p> The value of the <code nobreak="false">doctype-system</code> attribute provides the value of the
                     <code nobreak="false">doctype-system</code> parameter to the serialization method. If the attribute is absent or has a zero-length
                     string as its value, then the serialization parameter is not set (is
                     “absent”).
               </p></item><item><p> The value of the <code nobreak="false">doctype-public</code> attribute provides the value of the
                     <code nobreak="false">doctype-public</code> parameter to the serialization method. If the attribute is absent or has a zero-length
                     string as its value, then the serialization parameter is not set (is
                     “absent”).
               </p><p>The value of <code nobreak="false">doctype-public</code> must conform to the rules for a <xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="XML" ref="PubidLiteral" xlink:type="simple">PubidLiteral</xnt> (see <bibref ref="REC-xml"/>).</p></item><item diff="add" at="2023-05-31"><p> The value of the <code nobreak="false">escape-solidus</code> attribute provides the value
                  of the <code nobreak="false">escape-solidus</code> parameter to the serialization method.
                  The default value is <code nobreak="false">yes</code>. </p></item><item><p> The value of the <code nobreak="false">escape-uri-attributes</code> attribute provides the value
                  of the <code nobreak="false">escape-uri-attributes</code> parameter to the serialization method.
                  The default value is <code nobreak="false">yes</code>. </p></item><item><p> The value of the <code nobreak="false">html-version</code> attribute provides
                  the value of the <code nobreak="false">html-version</code> parameter to the serialization method.
                  The set of permitted values, and the default value, are <termref def="dt-implementation-defined">implementation-defined</termref>. 
                  A <termref def="dt-serialization-error">serialization error</termref> will be raised if
                  the requested version is not supported by the implementation. </p><note><p>This serialization parameter is new in version 3.0. If it is
                     absent, the html output method uses the value of the <code nobreak="false">version</code>
                     parameter in its place. For XHTML serialization, the <code nobreak="false">html-version</code>
                     parameter indicates the version of XHTML to be used, while the
                        <code nobreak="false">version</code> parameter indicates the version of XML.</p></note></item><item><p> The value of the <code nobreak="false">include-content-type</code> attribute provides the value
                  of the <code nobreak="false">include-content-type</code> parameter to the serialization method.
                  The default value is <code nobreak="false">yes</code>. </p></item><item><p> The value of the <code nobreak="false">indent</code> attribute provides the value of the
                     <code nobreak="false">indent</code> parameter to the serialization method. The default value is
                     <code nobreak="false">yes</code> in the case of the <code nobreak="false">html</code> and <code nobreak="false">xhtml</code>
                  output methods, <code nobreak="false">no</code> in the case of all other output methods.
               </p></item><item><p> The value of the <code nobreak="false">item-separator</code> attribute provides the value of the
                     <code nobreak="false">item-separator</code> parameter to the serialization method. The value of
                  the serialization parameter can be any string (including a zero-length string), or
                  absent. To set the parameter to absent, the <code nobreak="false">item-separator</code> attribute
                  can either be omitted, or set to the special value
                     <code nobreak="false">item-separator="#absent"</code>; it is not possible to set the value of
                  the serialization parameter to the literal 7-character string <code nobreak="false">"#absent"</code>. </p><note><p>The <code nobreak="false">item-separator</code> attribute has no
                     effect if the sequence being serialized contains only one item<phrase diff="del" at="2022-01-01">, which will
                     always be the case if the <termref def="dt-effective-value"/> of <code nobreak="false">build-tree</code> is
                        <code nobreak="false">yes</code></phrase>. </p></note></item><item><p>The value of the <code nobreak="false">json-lines</code> attribute determines whether the JSON
                  output method should output multiple JSON values in json-lines format (one
                  value per line). The default value is <code nobreak="false">no</code>.
               </p></item><item><p>The value of the <code nobreak="false">json-node-output-method</code> attribute determines how
                  any nodes appearing within maps or arrays are serialized by the <code nobreak="false">json</code>
                  output method. The default value is <code nobreak="false">xml</code>. The syntax and semantics of
                  the value follow the same rules as the <code nobreak="false">method</code> attribute.
               </p></item><item><p> The value of the <code nobreak="false">media-type</code> attribute provides the value of the
                     <code nobreak="false">media-type</code> parameter to the serialization method. The default
                  value is <code nobreak="false">text/xml</code> in the case of the <code nobreak="false">xml</code> output method,
                     <code nobreak="false">text/html</code> in the case of the <code nobreak="false">html</code> and
                     <code nobreak="false">xhtml</code> output methods, and <code nobreak="false">text/plain</code> in the case of
                  the <code nobreak="false">text</code> output method. <phrase diff="add" at="2022-01-01">The default for 
                     the <code nobreak="false">json</code> output method is <code nobreak="false">application/json</code>; the default 
                     for the adaptive output method is <termref def="dt-implementation-defined"/>.
                  </phrase></p></item><item><p> The value of the <code nobreak="false">normalization-form</code> attribute provides the value of
                  the <code nobreak="false">normalization-form</code> parameter to the serialization method. A value
                  that is an <code nobreak="false">NMTOKEN</code> other than one of those enumerated for the
                     <code nobreak="false">normalization-form</code> attribute specifies an implementation-defined
                  normalization form; the behavior in this case is not specified by this document.
                  The default value is <code nobreak="false">none</code>. </p></item><item><p> The value of the <code nobreak="false">omit-xml-declaration</code> attribute provides the value
                  of the <code nobreak="false">omit-xml-declaration</code> parameter to the serialization method.
                  The default value is <code nobreak="false">no</code>. </p></item><item><p> The value of the <code nobreak="false">standalone</code> attribute provides the value of the
                     <code nobreak="false">standalone</code> parameter to the serialization method. The default
                  value is <code nobreak="false">omit</code>; this means that no <code nobreak="false">standalone</code> attribute
                  is to be included in the XML declaration. </p></item><item><p> The <code nobreak="false">suppress-indentation</code> attribute is a whitespace-separated list of
                  QNames. The default value is an empty list. After expansion of these names using
                  the <phrase diff="chg" at="2023-05-04"><termref def="dt-applicable-static-namespaces"/></phrase> 
                  for the <elcode>xsl:output</elcode>
                  declaration in which they appear, this list of names provides the value of the
                     <code nobreak="false">suppress-indentation</code> parameter to the serialization method. In the
                  case of an unprefixed name, the default namespace (that is, the namespace declared
                  using <code nobreak="false">xmlns="uri"</code>) is used. </p><note><p>This differs from the rule for most other QNames used in a stylesheet. The
                     reason is that these names refer to elements in the result document, and
                     therefore follow the same convention as the name of a literal result element or
                     the <code nobreak="false">name</code> attribute of <elcode>xsl:element</elcode>.</p></note></item><item><p> The value of the <code nobreak="false">undeclare-prefixes</code> attribute provides the value of the
                  <code nobreak="false">undeclare-prefixes</code> parameter to the serialization method. The default
                  value is <code nobreak="false">no</code>.</p></item><item><p>The <code nobreak="false">use-character-maps</code> attribute provides a list of named character
                  maps that are used in conjunction with this <termref def="dt-output-definition">output definition</termref>. The way this attribute is used is described in
                     <specref ref="character-maps"/>. The default value is an empty list.</p></item><item><p> The value of the <code nobreak="false">version</code> attribute provides the value of the
                     <code nobreak="false">version</code> parameter to the serialization method. The set of
                  permitted values, and the default value, are <termref def="dt-implementation-defined">implementation-defined</termref>. 
                  A <termref def="dt-serialization-error">serialization error</termref> will be raised if
                  the requested version is not supported by the implementation.
                  
               </p></item></ulist><imp-def-feature id="idf-spec-serversions">It is implementation-defined which versions of
            XML, HTML, and XHTML are supported in the <code nobreak="false">version</code> attribute of the
               <elcode>xsl:output</elcode> declaration.</imp-def-feature><p>If the processor performs serialization, then it must raise any  serialization errors that occur. These have the same
            effect as <termref def="dt-dynamic-error"> dynamic errors</termref>: that is, the processor must
            raise the error and must not finish as if the transformation had been successful.</p></div2><div2 id="character-maps"><head>Character Maps</head><p>
               <termdef id="dt-character-map" term="character map">A <term>character map</term>
                  allows a specific character appearing in a text or attribute node in the <termref def="dt-final-result-tree">final result tree</termref> to be substituted by a
                  specified string of characters during serialization.</termdef> The effect of
               character maps is defined in <bibref ref="xslt-xquery-serialization-40"/>.</p><p>The character map that is supplied as a parameter to the serializer is determined
               from the <elcode>xsl:character-map</elcode> elements referenced from the
                  <elcode>xsl:output</elcode> declaration for the selected <termref def="dt-output-definition">output definition</termref>.</p><p>The <elcode>xsl:character-map</elcode> element is a declaration that may appear as a
               child of the <elcode>xsl:stylesheet</elcode> element.</p><e:element-syntax xmlns:e="http://www.w3.org/1999/XSL/Spec/ElementSyntax" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" name="character-map">
      <e:in-category name="declaration"/>
      <e:attribute name="name" required="yes">
         <e:data-type name="eqname"/>
      </e:attribute>
      <e:attribute name="use-character-maps">
         <e:data-type name="eqnames"/>
      </e:attribute>
      <e:sequence>
         <e:element repeat="zero-or-more" name="output-character"/>
      </e:sequence>
      <e:allowed-parents>
         <e:parent name="package"/>
         <e:parent name="stylesheet"/>
         <e:parent name="transform"/>
      </e:allowed-parents>
   </e:element-syntax><p>The <elcode>xsl:character-map</elcode> declaration declares a character map with a
               name and a set of character mappings. The character mappings are specified by means
               of <elcode>xsl:output-character</elcode> elements contained either directly within
               the <elcode>xsl:character-map</elcode> element, or in further character maps
               referenced in the <code nobreak="false">use-character-maps</code> attribute.</p><p>The <rfc2119>required</rfc2119>
               <code nobreak="false">name</code> attribute provides a name for the character map. When a character
               map is used by an <termref def="dt-output-definition">output definition</termref> or
               another character map, the character map with the highest <termref def="dt-import-precedence">import precedence</termref> is used.</p><p>The name of a character map is local to the <termref def="dt-package">package</termref> in which its declaration appears; it may be
               referenced only from within the same package.</p><p>
               <error spec="XT" type="static" class="SE" code="1580"><p>It is a <termref def="dt-static-error">static error</termref> if a <termref def="dt-package">package</termref> contains two
                     or more character maps with the same name and the same <termref def="dt-import-precedence">import precedence</termref>, unless it also
                     contains another character map with the same name and higher import
                     precedence.</p></error>
            </p><p>The optional <code nobreak="false">use-character-maps</code> attribute lists the names of further
               character maps that are included into this character map.</p><p>
               <error spec="XT" type="static" class="SE" code="1590"><p>It is a <termref def="dt-static-error">static error</termref> if a name in the
                        <code nobreak="false">use-character-maps</code> attribute of the <elcode>xsl:output</elcode>
                     or <elcode>xsl:character-map</elcode> elements does not match the
                        <code nobreak="false">name</code> attribute of any <elcode>xsl:character-map</elcode> in the
                        containing <termref def="dt-package">package</termref>.</p></error>
            </p><p>
               <error spec="XT" type="static" class="SE" code="1600"><p>It is a <termref def="dt-static-error">static error</termref> if a character
                     map references itself, directly or indirectly, via a name in the
                        <code nobreak="false">use-character-maps</code> attribute.</p></error>
            </p><p>It is not an error if the same character map is referenced more than once, directly
               or indirectly.</p><p>For every <elcode>xsl:character-map</elcode> declaration in a <termref def="dt-package"/>,
            other than one that is overridden by another of higher <termref def="dt-import-precedence"/>,
            the static context of the package includes a named character map derived from the 
            <elcode>xsl:character-map</elcode> declaration. The name of the named character map is the
            QName formed by expanding the value of the <code nobreak="false">name</code> attribute, and the content is
            a map of type <code nobreak="false">map{xs:string, xs:string}</code> that maps characters (represented as 
            <code nobreak="false">xs:string</code> instances of length 1) to their replacement strings.</p><p>Recursive expansion of character maps using <code nobreak="false">use-character-maps</code>
               attributes may produce several mappings for the same character. In this situation,
               the last character mapping takes precedence. To establish the ordering, the following
               rules are used:</p><ulist><item><p>Within a single <elcode>xsl:character-map</elcode> element, the characters
                     defined in character maps referenced in the <code nobreak="false">use-character-maps</code>
                     attribute are considered before the characters defined in the child
                        <elcode>xsl:output-character</elcode> elements.</p></item><item><p>The character maps referenced in a single <code nobreak="false">use-character-maps</code>
                     attribute are considered in the order in which they are listed in that
                     attribute. The expansion is depth-first: each referenced character map is fully
                     expanded before the next one is considered.</p></item><item><p>Two <elcode>xsl:output-character</elcode> elements appearing as children of the
                     same <elcode>xsl:character-map</elcode> element are considered in document
                     order.</p></item></ulist><p>The <elcode>xsl:output-character</elcode> element is defined as follows:</p><e:element-syntax xmlns:e="http://www.w3.org/1999/XSL/Spec/ElementSyntax" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" name="output-character">
      <e:attribute name="character" required="yes">
         <e:data-type name="char"/>
      </e:attribute>
      <e:attribute name="string" required="yes">
         <e:data-type name="string"/>
      </e:attribute>
      <e:empty/>
      <e:allowed-parents>
         <e:parent name="character-map"/>
      </e:allowed-parents>
   </e:element-syntax><p>The character map that is passed as a parameter to the serializer contains a mapping
               for the character specified in the <code nobreak="false">character</code> attribute to the string
               specified in the <code nobreak="false">string</code> attribute. </p><p>Character mapping is not applied to characters for which output escaping has been
               disabled as described in <specref ref="disable-output-escaping"/>.</p><p>If a character is mapped, then it is not subjected to XML or HTML escaping.</p><example><head>Using Character Maps to Generate Non-XML Output</head><p>Character maps can be useful when producing serialized output in a format that
                  resembles, but is not strictly conformant to, HTML or XML. For example, when the
                  output is a JSP page, there might be a need to generate the output:</p><eg role="non-xml" xml:space="preserve">&lt;jsp:setProperty name="user" property="id" value='&lt;%= "id" + idValue %&gt;'/&gt;</eg><p>Although this output is not well-formed XML or HTML, it is valid in Java Server
                  Pages. This can be achieved by allocating three Unicode characters (which are not
                  needed for any other purpose) to represent the strings <code nobreak="false">&lt;%</code>,
                     <code nobreak="false">%&gt;</code>, and <code nobreak="false">"</code>, for example:</p><eg role="xslt-declaration" xml:space="preserve">&lt;xsl:character-map name="jsp"&gt;
  &lt;xsl:output-character character="«" string="&amp;lt;%"/&gt;   
  &lt;xsl:output-character character="»" string="%&amp;gt;"/&gt;
  &lt;xsl:output-character character="§" string='"'/&gt;
&lt;/xsl:character-map&gt;</eg><p>When this character map is referenced in the <elcode>xsl:output</elcode>
                  declaration, the required output can be produced by writing the following in the
                  stylesheet:</p><eg role="non-xml" xml:space="preserve">&lt;jsp:setProperty name="user" property="id" value='«= §id§ + idValue »'/&gt;</eg><p>This works on the assumption that when an apostrophe or quotation mark is
                  generated as part of an attribute value by the use of character maps, the
                  serializer will (where possible) use the other choice of delimiter around the
                  attribute value.</p></example><example><head>Constructing a Composite Character Map</head><p>The following example illustrates a composite character map constructed in a
                  modular fashion:</p><eg role="xslt-declarations" xml:space="preserve">
&lt;xsl:output name="htmlDoc" use-character-maps="htmlDoc" /&gt;

&lt;xsl:character-map name="htmlDoc"
  use-character-maps="html-chars doc-entities windows-format" /&gt;
  
&lt;xsl:character-map name="html-chars"
  use-character-maps="latin1 ..." /&gt;

&lt;xsl:character-map name="latin1"&gt;
  &lt;xsl:output-character character="&amp;#160;" string="&amp;amp;nbsp;" /&gt;
  &lt;xsl:output-character character="&amp;#161;" string="&amp;amp;iexcl;" /&gt;
  ...
&lt;/xsl:character-map&gt;

&lt;xsl:character-map name="doc-entities"&gt;
  &lt;xsl:output-character character="&amp;#xE400;" string="&amp;amp;t-and-c;" /&gt;
  &lt;xsl:output-character character="&amp;#xE401;" string="&amp;amp;chap1;" /&gt;
  &lt;xsl:output-character character="&amp;#xE402;" string="&amp;amp;chap2;" /&gt;
  ...
&lt;/xsl:character-map&gt;

&lt;xsl:character-map name="windows-format"&gt;
  &lt;!-- newlines as CRLF --&gt;
  &lt;xsl:output-character character="&amp;#xA;" string="&amp;#xD;&amp;#xA;" /&gt;

  &lt;!-- tabs as three spaces --&gt;
  &lt;xsl:output-character character="&amp;#x9;" string="   " /&gt;

  &lt;!-- images for special characters --&gt;
  &lt;xsl:output-character character="&amp;#xF001;"
    string="&amp;lt;img src='special1.gif' /&amp;gt;" /&gt;
  &lt;xsl:output-character character="&amp;#xF002;"
    string="&amp;lt;img src='special2.gif' /&amp;gt;" /&gt;
  ...
&lt;/xsl:character-map&gt;</eg></example><note><p>When character maps are used, there is no guarantee that the serialized output
                  will be well-formed XML (or HTML). Furthermore, the fact that the result tree was
                  validated against a schema gives no guarantee that the serialized output will
                  still be valid against the same schema. Conversely, it is possible to use
                  character maps to produce schema-valid output from a result tree that would fail
                  validation.</p></note><note><p>The value of the <code nobreak="false">string</code> attribute must be a literal string; this
               means it must consist entirely of characters that are valid in XML 1.0 or XML 1.1,
               depending on the version of XML used for the containing stylesheet module. The string
               can however be expressed as a shadow attribute (see <specref ref="shadow-attributes"/>), 
                  and this allows
               it to be defined using a <termref def="dt-static-expression"/>. For example, the 
               character <char>U+2398</char> might be mapped to the control character <char>U+000C</char>
               by writing <code nobreak="false">&lt;xsl:output-character char="&amp;#x2398;" _string="{char(0x0C)}"/&gt;</code>.
               This depends on the processor allowing the form-feed character to appear in strings:
               the data model allows this, but processors are not <rfc2119>required</rfc2119>
               to support it: see <xspecref spec="DM40" ref="xml-and-xsd-versions"/>.</p></note></div2><div2 id="character-map-function"><head>The <function>character-map</function> function</head><changes><change issue="1500" PR="1530" date="2024-10-30">
                  The contents of a character map declared using <elcode>xsl:character-map</elcode> are now
                  available dynamically via a new <function>character-map</function> function.
               </change></changes><p>The contents of a character map declared using <elcode>xsl:character-map</elcode> are 
                  available dynamically via the <function>character-map</function> function.</p><div3 id="func-character-map"><head>fn:character-map</head><changes><change>New in 4.0</change></changes><glist><gitem><label>Summary</label><def><p>Delivers the content of a character map declared using <elcode>xsl:character-map</elcode>.</p></def></gitem><gitem><label>Signature</label><def><example role="signature"><proto isOp="no" prefix="fn" name="character-map" return-type="map(xs:string, xs:string)?" returnEmptyOk="no" returnSeq="no" returnVaries="no" isSchema="no" isDatatype="no" isSpecial="no"><arg name="name" type="xs:QName"/></proto></example></def></gitem><gitem><label>Properties</label><def><p>This function is <xtermref spec="FO40" ref="dt-deterministic">deterministic</xtermref>, <xtermref spec="FO40" ref="dt-context-dependent">context-dependent</xtermref>,  and <xtermref spec="FO40" ref="dt-focus-independent">focus-independent</xtermref>.  It depends on 
		character maps.
	</p></def></gitem><gitem><label>Rules</label><def><p>The static context for a stylesheet package includes a set of named character maps. This function
         delivers the content of a character map if a character map with the given name is present in the
         static context of the containing package, or an empty sequence otherwise.</p></def></gitem><gitem><label>Notes</label><def><note><p>The returned character map is in a format suitable for use within the <code nobreak="false">$options</code>
         parameter of the <xfunction>serialize</xfunction> function.</p></note></def></gitem><gitem><label>Examples</label><def role="example"><table role="medium" border="1" cellpadding="5" width="100%"><tbody><tr><td colspan="2" rowspan="1" align="left" valign="top"><p>Consider the following character map declaration:</p></td></tr><tr><td colspan="2" rowspan="1" align="left" valign="top"><eg xml:space="preserve">
 &lt;xsl:character-map name="jsp"&gt;
  &lt;xsl:output-character character="«" string="&amp;lt;%"/&gt;   
  &lt;xsl:output-character character="»" string="%&amp;gt;"/&gt;
  &lt;xsl:output-character character="§" string='"'/&gt;
&lt;/xsl:character-map&gt;              
               </eg></td></tr><tr><td colspan="2" rowspan="1" align="left" valign="top"><p>Then the result of the function call <code nobreak="false">character-map( #jsp )</code> is the map:</p></td></tr><tr><td colspan="2" rowspan="1" align="left" valign="top"><eg xml:space="preserve">
{
  "«": "&lt;%",
  "»": "%&gt;",
  "§": '"'
}
               </eg></td></tr><tr><td colspan="2" rowspan="1" align="left" valign="top"><p>This might be used in a call to the function <xfunction>serialize</xfunction>, for example:</p></td></tr><tr><td colspan="2" rowspan="1" align="left" valign="top"><eg xml:space="preserve">
serialize($input, {
  'method': 'xml',
  'use-character-maps': character-map( #jsp )
})
               </eg></td></tr></tbody></table></def></gitem></glist></div3></div2><div2 id="disable-output-escaping"><head>Disabling Output Escaping</head><p>Normally, when using the XML, HTML, or XHTML output method, the serializer will
               escape special characters such as <code nobreak="false">&amp;</code> and <code nobreak="false">&lt;</code> when
               outputting text nodes. This ensures that the output is well-formed. However, it is
               sometimes convenient to be able to produce output that is almost, but not quite
               well-formed XML; for example, the output may include ill-formed sections which are
               intended to be transformed into well-formed XML by a subsequent non-XML-aware
               process. For this reason, XSLT defines a mechanism for disabling output escaping.</p><p>This feature is <termref def="dt-deprecated">deprecated</termref>.</p><p>This is an optional feature: it is not <rfc2119>required</rfc2119> that an XSLT
               processor that implements the serialization option <rfc2119>should</rfc2119> offer
               the ability to disable output escaping, and there is no conformance level that
               requires this feature.</p><p>This feature requires the serializer (described in <bibref ref="xslt-xquery-serialization-40"/>) 
               to be extended as follows. Conceptually, the <termref def="dt-final-result-tree">final result tree</termref> provides an additional
               boolean property <code nobreak="false">disable-escaping</code> associated with every character in a
               text node. When this property is set, the normal action of the serializer to escape
               special characters such as <code nobreak="false">&amp;</code> and <code nobreak="false">&lt;</code> is
               suppressed.</p><p>An <elcode>xsl:value-of</elcode> or <elcode>xsl:text</elcode> element may have a
                  <code nobreak="false">disable-output-escaping</code> attribute; the allowed values are
                  <code nobreak="false">yes</code> or <code nobreak="false">no</code>. The default is <code nobreak="false">no</code>; if the value
               is <code nobreak="false">yes</code>, then every character in the text node generated by evaluating
               the <elcode>xsl:value-of</elcode> or <elcode>xsl:text</elcode> element
                  <rfc2119>should</rfc2119> have the <code nobreak="false">disable-escaping</code> property set.</p><example><head>Disable Output Escaping</head><p>For example,</p><eg role="xslt-instruction" xml:space="preserve">&lt;xsl:text disable-output-escaping="yes"&gt;&amp;lt;&lt;/xsl:text&gt;</eg><p>should generate the single character <code nobreak="false">&lt;</code>.</p></example><p>If output escaping is disabled for an <elcode>xsl:value-of</elcode> or
                  <elcode>xsl:text</elcode> instruction evaluated when <termref def="dt-temporary-output-state">temporary output state</termref> is in effect, the
               request to disable output escaping is ignored.</p><p>Similarly, if an <elcode>xsl:value-of</elcode> or
                  <elcode>xsl:text</elcode> instruction specifies that output escaping is to be
               disabled when writing to a <termref def="dt-final-result-tree">final result
                  tree</termref> that is not being serialized, the request to disable output
               escaping is ignored.</p><note><p>Furthermore, a request to disable output escaping has no effect when the newly
               constructed text node is used to form the value of an attribute, comment, processing instruction,
               or namespace node. This is because the rules for constructing such nodes (see <specref ref="constructing-simple-content"/>)
               cause the text node to be atomized, and the process of atomizing a text node takes no
               account of the disable-escaping property.</p></note><p>If output escaping is disabled for text within an element that would normally be
               output using a CDATA section, because the element is listed in the
                  <code nobreak="false">cdata-section-elements</code>, then the relevant text will not be included
               in a CDATA section. In effect, CDATA is treated as an alternative escaping mechanism,
               which is disabled by the <code nobreak="false">disable-output-escaping</code> option.</p><example><head>Interaction of Output Escaping and CDATA</head><p>For example, if <code nobreak="false">&lt;xsl:output cdata-section-elements="title"/&gt;</code> is
                  specified, then the following instructions:</p><eg role="xslt-instruction" xml:space="preserve">&lt;title&gt;
  &lt;xsl:text disable-output-escaping="yes"&gt;This is not &amp;lt;hr/&amp;gt; 
                                          good coding practice&lt;/xsl:text&gt;
&lt;/title&gt;</eg><p>should generate the output:</p><eg role="xml" xml:space="preserve">&lt;title&gt;&lt;![CDATA[This is not ]]&gt;&lt;hr/&gt;&lt;![CDATA[ good coding practice]]&gt;&lt;/title&gt;</eg></example><p>The <code nobreak="false">disable-output-escaping</code> attribute may be used with the
                  <code nobreak="false">html</code> output method as well as with the <code nobreak="false">xml</code> output
               method. The <code nobreak="false">text</code> output method ignores the
                  <code nobreak="false">disable-output-escaping</code> attribute, since this method does not perform
               any output escaping.</p><p>A <termref def="dt-processor">processor</termref> will only be able to disable output
               escaping if it controls how the <termref def="dt-final-result-tree">final result
                  tree</termref> is output. This might not always be the case. For example, the
               result tree might be used as a <termref def="dt-source-tree">source tree</termref>
               for another XSLT transformation instead of being output. It is <termref def="dt-implementation-defined">implementation-defined</termref> whether (and
               under what circumstances) disabling output escaping is supported. If disabling output escaping is not supported, any request to disable
                  output escaping is ignored.</p><imp-def-feature id="idf-feature-doe">It is implementation-defined whether, and under
               what circumstances, disabling output escaping is supported.</imp-def-feature><p>If output escaping is disabled for a character that is not representable in the
               encoding that the <termref def="dt-processor">processor</termref> is using for
               output, the request to disable output escaping is ignored in respect of that
               character.</p><p>Since disabling output escaping might not work with all implementations and can
               result in XML that is not well-formed, it <rfc2119>should</rfc2119> be used only when
               there is no alternative.</p><note><p>When disable-output-escaping is used, there is no guarantee that the serialized
                  output will be well-formed XML (or HTML). Furthermore, the fact that the result
                  tree was validated against a schema gives no guarantee that the serialized output
                  will still be valid against the same schema. Conversely, it is possible to use
                  disable-output-escaping to produce schema-valid output from a result tree that
                  would fail validation.</p></note><note><p>The facility to define character maps for use during serialization, as described
                  in <specref ref="character-maps"/>, has been produced as an alternative mechanism
                  that can be used in many situations where disabling of output escaping was
                  previously necessary, without the same difficulties.</p></note></div2></div1><div1 id="conformance"><head>Conformance</head><changes><change issue="205" PR="326" date="2023-02-01">
               The higher-order-function feature no longer exists; higher-order functions
               are now a core part of XSLT, no longer an optional extra.
            </change><change issue="2047" PR="2213" date="2025-10-23">
               The dynamic evaluation feature no longer exists; processor are now required
               to support the <elcode>xsl:evaluate</elcode> instruction.
            </change></changes><p>A <termref def="dt-processor">processor</termref> that claims
            conformance with this specification <rfc2119>must</rfc2119> satisfy the conformance
            requirements for a <termref def="dt-basic-xslt-processor">basic XSLT processor</termref>
            and for each of the optional features with which it claims conformance.</p><p>The following optional features are defined:</p><olist><item><p>The schema-awareness feature, defined in <specref ref="schema-aware-conformance"/></p></item><item><p>The serialization feature, defined in <specref ref="serialization-feature"/></p></item><item><p>The backwards compatibility feature, defined in <specref ref="backwards-compatibility-feature"/></p></item><item><p>The streaming feature, defined in <specref ref="streaming-feature"/>.</p></item></olist><p>A processor that does not claim conformance with an optional feature
               <rfc2119>must</rfc2119> satisfy the requirements for processors that do not implement
            that feature.</p><p>An XSLT processor takes as its inputs a stylesheet and zero or more XDM trees conforming to the data model defined in <bibref ref="xpath-datamodel-40"/>. It is not <rfc2119>required</rfc2119> that the processor
            supports any particular method of constructing XDM trees, but conformance can only be
            tested if it provides a mechanism that enables XDM trees representing the stylesheet and
            primary source document to be constructed and supplied as input to the processor.</p><p>The output of the XSLT processor consists of zero or more <termref def="dt-final-result-tree">final result trees</termref>. It is not
               <rfc2119>required</rfc2119> that the processor supports any particular method of
            accessing a final result tree, but if it does not support the serialization feature, conformance can only be tested if it provides
            some alternative mechanism that enables access to the results of the transformation.</p><p>Certain facilities in this specification are described as producing <termref def="dt-implementation-defined">implementation-defined</termref> results. A claim
            that asserts conformance with this specification <rfc2119>must</rfc2119> be accompanied
            by documentation stating the effect of each implementation-defined feature. For
            convenience, a non-normative checklist of implementation-defined features is provided at
               <specref ref="implementation-defined-features"/>.</p><p>A conforming <termref def="dt-processor">processor</termref>
            <rfc2119>must</rfc2119> raise any <termref def="dt-static-error">static error</termref>
            occurring in the stylesheet, or in any XPath <termref def="dt-expression">expression</termref>, except where specified otherwise either for individual error
            conditions or under the general provisions for <termref def="dt-forwards-compatible-behavior"/> (see <specref ref="forwards"/>). After
            raising such an error, the processor <rfc2119>may</rfc2119> continue for the purpose
            of raising additional errors, but <rfc2119>must</rfc2119> terminate abnormally without
            performing any transformation.</p><p>When a <termref def="dt-dynamic-error">dynamic error</termref> occurs during the course
            of a transformation, and is not caught using
                  <elcode>xsl:catch</elcode>,
             the processor
               <rfc2119>must</rfc2119> raise it and <rfc2119>must</rfc2119> eventually terminate
            abnormally. </p><p>Some errors, notably <termref def="dt-type-error">type errors</termref>,
               <rfc2119>may</rfc2119> be treated as <termref def="dt-static-error">static
               errors</termref> or <termref def="dt-dynamic-error">dynamic errors</termref> at the
            discretion of the processor.</p><p>A conforming processor <rfc2119>may</rfc2119> impose limits on the processing resources
            consumed by the processing of a stylesheet.</p><p>A requirement is mandatory unless the specification includes wording (such as the use of
            the words <rfc2119>should</rfc2119> or <rfc2119>may</rfc2119>) that clearly indicates
            that it is optional.</p><p>Some of the optional features are defined in such a way that
         if the feature is not provided, the data model is constrained to exclude certain kinds of
         item. For example:</p><ulist><item><p>A processor that does not provide the <termref def="dt-schema-aware-xslt-processor">schema-awareness</termref>
            feature restricts the data model so that it does not contain atomic items of types other than the built-in types,
            or nodes with non-trivial type annotations.</p></item></ulist><p><error spec="XT" type="dynamic" class="DE" code="1665"><p>A <termref def="dt-dynamic-error"/> <rfc2119>may</rfc2119> be raised if the
               input to the processor includes an item that requires availability
               of an optional feature that the processor does not provide.</p></error></p><note><p>It is not necessarily possible to trigger this error. A processor that does
         not provide an optional feature might not define or recognize any representation of the items
         that are disallowed. The error code is provided for use in cases where a processor is able
         to interoperate with other software that does not have the same constraints — for example,
         where a package compiled with a non-schema-aware processor is able to invoke functions in a package
         that was compiled with a schema-aware processor. Even in that case,
         processors have the option of filtering or converting the input so that it meets the relevant
         constraints: for example, a non-schema-aware processor when presented with a schema-validated
         document in the form of a PSVI might simply ignore the properties it does not understand.</p><p>The dynamic error is optional: for example a processor might report no error
            if the offending item is not actually used.</p><p>The phrase <emph>input to the processor</emph> is deliberately wide: it includes (inter alia)
               the <termref def="dt-global-context-item"/>, items present in the <termref def="dt-initial-match-selection"/>, items passed as <termref def="dt-stylesheet-parameter">stylesheet parameters</termref>, items returned by functions such as 
                <function>document</function>, <xfunction>doc</xfunction>, and
               <xfunction>collection</xfunction>, items returned by <termref def="dt-extension-function">extension functions</termref> and <termref def="dt-extension-instruction">extension instructions</termref>,
            items supplied in function or template parameters or results across package boundaries, and nodes
            reachable from any of the above by axis navigation.</p></note><div2 id="basic-conformance"><head>Basic XSLT Processor</head><p>
               <termdef id="dt-basic-xslt-processor" term="basic XSLT processor">A <term>basic XSLT
                     processor</term> is an XSLT processor that implements all the mandatory
                  requirements of this specification with the exception of constructs explicitly
                  associated with an optional feature.</termdef> These constructs are listed
               below.</p></div2><div2 id="schema-aware-conformance"><head>Schema-Awareness Conformance Feature</head><p>A conformant processor <rfc2119>must</rfc2119> either be a conformant <termref def="dt-schema-aware-xslt-processor"/> or a conformant <termref def="dt-non-schema-aware-processor"/>.</p><p>
               <termdef id="dt-schema-aware-xslt-processor" term="schema-aware XSLT processor">A
                     <term>schema-aware XSLT processor</term> is an XSLT processor that implements
                  the mandatory requirements of this specification connected with the
                     <elcode>xsl:import-schema</elcode> declaration, the
                     <code nobreak="false">[xsl:]validation</code> and <code nobreak="false">[xsl:]type attributes</code>, and the
                  ability to handle input documents whose nodes have type annotations other than
                     <code nobreak="false">xs:untyped</code> and <code nobreak="false">xs:untypedAtomic</code>. The mandatory
                  requirements of this specification are taken to include the mandatory requirements
                  of XPath 4.0, as described in <bibref ref="xpath-40"/>. A requirement is mandatory unless the specification includes
                  wording (such as the use of the words <rfc2119>should</rfc2119> or
                     <rfc2119>may</rfc2119>) that clearly indicates that it is optional.</termdef>
            </p><p><termdef id="dt-non-schema-aware-processor" term="non-schema-aware processor">A <term>non-schema-aware processor</term> is a
                  processor that does not claim conformance with the schema-aware conformance
                  feature. Such a processor <rfc2119>must</rfc2119> handle constructs associated
                  with schema-aware processing as described in this section.</termdef></p><p>
               <error spec="XT" type="static" class="SE" code="1650"><p>A <termref def="dt-non-schema-aware-processor">non-schema-aware
                        processor</termref>
                     <rfc2119>must</rfc2119> raise a <termref def="dt-static-error">static
                        error</termref> if a <termref def="dt-package">package</termref> includes an
                        <elcode>xsl:import-schema</elcode> declaration.</p></error>
            </p><note><p>A processor that rejects an <elcode>xsl:import-schema</elcode> declaration will
                  also reject any reference to a user-defined type defined in a schema, or to a
                  user-defined element or attribute declaration; it will not, however, reject
                  references to the built-in types listed in <specref ref="built-in-types"/>.</p></note><p>A <termref def="dt-non-schema-aware-processor">non-schema-aware
                  processor</termref> is not able to validate input documents, and is not able to
               handle input documents containing type annotations other than <code nobreak="false">xs:untyped</code>
               or <code nobreak="false">xs:untypedAtomic</code>. Therefore, such a processor <rfc2119>must</rfc2119>
               treat any <code nobreak="false">[xsl:]validation</code> attribute
                  with a value of <code nobreak="false">preserve</code> or <code nobreak="false">lax</code>, or a
                     <code nobreak="false">[xsl:]default-validation</code> attribute with a value of
                     <code nobreak="false">preserve</code> as if the value were <code nobreak="false">strip</code>.</p><note><p>The values <code nobreak="false">lax</code> and <code nobreak="false">preserve</code> indicate that the validation
                  to be applied depends on the calling application, so it is appropriate for the
                  request to be treated differently by different kinds of processor. By contrast,
                  requesting <code nobreak="false">strict</code> validation, either through the
                     <code nobreak="false">[xsl:]validation</code> attribute or the <code nobreak="false">type</code> attribute,
                  indicates that the stylesheet is expecting to deal with typed data, and therefore
                  cannot be processed without performing the validation.</p></note><p>
               <error spec="XT" type="static" class="SE" code="1660"><p>A <termref def="dt-non-schema-aware-processor">non-schema-aware
                        processor</termref>
                     <rfc2119>must</rfc2119> raise a <termref def="dt-static-error">static
                        error</termref> if a <termref def="dt-package">package</termref> includes an
                        <code nobreak="false">[xsl:]type</code> attribute; or an <code nobreak="false">[xsl:]validation</code> or
                        <code nobreak="false">[xsl:]default-validation</code> attribute with a value other than
                        <code nobreak="false">strip</code>, <code nobreak="false">preserve</code>, or
                           <code nobreak="false">lax</code>; or an
                           <elcode>xsl:mode</elcode> element whose <code nobreak="false">typed</code> attribute is
                        equal to <code nobreak="false">yes</code> or <code nobreak="false">strict</code>; or an <code nobreak="false">as</code>
                              attribute whose value is a 
                              <termref def="dt-sequence-type"/> that can only match
                        nodes with a type annotation other than <code nobreak="false">xs:untyped</code> or
                           <code nobreak="false">xs:untypedAtomic</code> (for example, <code nobreak="false">as="element(*,
                           xs:integer)"</code>).</p></error>
            </p><p>A <termref def="dt-non-schema-aware-processor">non-schema-aware processor</termref>
               constrains the data model as follows, and raises a <termref def="dt-dynamic-error"/> (<errorref spec="XT" class="DE" code="1665"/>) if the
                  constraints are not satisfied:</p><ulist><item><p>Atomic items <rfc2119>must</rfc2119> belong to one of the atomic types listed
                     in <specref ref="built-in-types"/> (except as noted below).</p><p>An atomic item may also belong to an implementation-defined type that has been
                     added to the context for use with <termref def="dt-extension-function">extension functions</termref> or <termref def="dt-extension-instruction">extension instructions</termref>.</p><p>The set of constructor functions available are limited to those that construct
                     values of the above atomic types.</p><p>The static context, which defines the full set of type names recognized by an
                     XSLT processor and also by the XPath processor, includes these atomic types,
                     plus <code nobreak="false">xs:anyType</code>, <code nobreak="false">xs:anySimpleType</code>,
                        <code nobreak="false">xs:untyped</code>, and <code nobreak="false">xs:anyAtomicType</code>.</p></item><item><p>Element nodes <rfc2119>must</rfc2119> be annotated with the <termref def="dt-type-annotation">type annotation</termref>
                     <code nobreak="false">xs:untyped</code>, and attribute nodes with the type annotation
                        <code nobreak="false">xs:untypedAtomic</code>.</p></item></ulist></div2><div2 id="serialization-feature"><head>Serialization Feature</head><p>
               <termdef id="dt-serialization-feature" term="serialization feature">A processor that
                  claims conformance with the <term>serialization feature</term>
                  <rfc2119>must</rfc2119> support the conversion of a <termref def="dt-final-result-tree">final result tree</termref> to a sequence of octets
                  following the rules defined in <specref ref="serialization"/>.</termdef> It
                  <rfc2119>must</rfc2119> respect all the attributes of the
                  <elcode>xsl:output</elcode> and <elcode>xsl:character-map</elcode> declarations,
               and <rfc2119>must</rfc2119> provide all four output methods, <code nobreak="false">xml</code>,
                  <code nobreak="false">xhtml</code>, <code nobreak="false">html</code>, and <code nobreak="false">text</code>. Where the
               specification uses words such as <rfc2119>must</rfc2119> and
                  <rfc2119>required</rfc2119>, then it <rfc2119>must</rfc2119> serialize the result
               tree in precisely the way described; in other cases it <rfc2119>may</rfc2119> use an
               alternative, equivalent representation.</p><p>A processor may claim conformance with the serialization feature whether or not it
               supports the setting <code nobreak="false">disable-output-escaping="yes"</code> on
                  <elcode>xsl:text</elcode>, or <elcode>xsl:value-of</elcode>. </p><p>A processor that does not claim conformance with the serialization feature
                  <rfc2119>must not</rfc2119> raise an error merely because the <termref def="dt-stylesheet">stylesheet</termref> contains <elcode>xsl:output</elcode> or
                  <elcode>xsl:character-map</elcode> declarations, or serialization attributes on
               the <elcode>xsl:result-document</elcode> instruction. Such a processor
                  <rfc2119>may</rfc2119> check that these declarations and attributes have valid
               values, but is not <rfc2119>required</rfc2119> to do so. Apart from optional
               validation, these declarations <rfc2119>should</rfc2119> be ignored.</p><note><p>A processor that does not claim conformance with the serialization feature
               <rfc2119>may</rfc2119> offer alternative serialization capabilities, and these
               <rfc2119>may</rfc2119> make use of the serialization parameters defined on
               <elcode>xsl:output</elcode> and/or <elcode>xsl:result-document</elcode>.
                  <phrase diff="add" at="2022-01-01">Such a processor <rfc2119>may</rfc2119> implement 
                     selected parts of the serialization capabilities defined in this specification. 
                     For example, it may implement selected output methods, or selected serialization 
                     properties. It may implement sequence normalization using the <code nobreak="false">item-separator</code> 
                     property even if it has no other serialization capabilities. </phrase></p></note><p>If the processor claims conformance with 
               the serialization feature then it <rfc2119>must</rfc2119> fully implement the 
               <xfunction>serialize</xfunction> function defined in <phrase diff="chg" at="2022-01-01"><bibref ref="xpath-functions-40"/></phrase>,
               and <rfc2119>must not</rfc2119>
               raise error <xerrorref spec="FO40" code="0010" class="DC"/> as the result of such a call.</p><p>If the processor does not claim conformance with
               the serialization feature, then it <rfc2119>may</rfc2119> raise 
               error <xerrorref spec="FO40" code="0010" class="DC"/> in respect of some or
               all calls on the <xfunction>serialize</xfunction> function; it <rfc2119>must not</rfc2119>
               return a result from a call on this function unless the result is conformant with
               the specification, given the parameters actually supplied. 
            </p><p>A processor that claims conformance with the Serialization
               Feature must satisfy the mandatory requirements of <bibref ref="xslt-xquery-serialization-40"/>. It <rfc2119>must</rfc2119> provide a mode of
               operation which conforms to the 3.0 version of that specification. It
                  <rfc2119>may</rfc2119> also provide a mode of operation which conforms to a later
               version of that specification; in such cases the detail of how XSLT 3.0 interacts
               with new features introduced by such a version (for example, support for new
               serialization properties) is <termref def="dt-implementation-defined"/>.</p><imp-def-feature id="idf-spec-serialization">It is <termref def="dt-implementation-defined"/> whether (and if so how) an XSLT 3.0 processor is
               able to work with versions of <bibref ref="xslt-xquery-serialization-40"/> later than
               3.1.</imp-def-feature></div2><div2 id="backwards-compatibility-feature"><head>Compatibility Features</head><p>
               <termdef id="dt-1.0-compatibility-feature" term="XSLT 1.0 compatibility feature">A
                  processor that claims conformance with the <term>XSLT 1.0 compatibility
                     feature</term>
                  <rfc2119>must</rfc2119> support the processing of stylesheet instructions and
                  XPath expressions with <termref def="dt-xslt-10-behavior">XSLT
                     1.0 behavior</termref>, as defined in <specref ref="backwards"/>.</termdef>
            </p><p>Note that a processor that does not claim conformance with the <termref def="dt-1.0-compatibility-feature"/>
               <rfc2119>must</rfc2119> raise a <termref def="dt-dynamic-error"> dynamic error</termref> if an instruction is
               evaluated whose <termref def="dt-effective-version"/> is 1.0. <errorref spec="XT" class="DE" code="0160"/>.</p><note><p>The reason this is a dynamic error rather than a static error is to allow
                  stylesheets to contain conditional logic, following different paths depending on
                  whether the XSLT processor implements XSLT 1.0, 2.0, or
                     3.0. The selection of which path to use can be controlled by using the
                     <function>system-property</function> function to test the
                     <code nobreak="false">xsl:version</code> system property.</p></note><p>A processor that claims conformance with the <termref def="dt-1.0-compatibility-feature"/>
               <rfc2119>must</rfc2119> permit the use of the namespace axis in XPath expressions
               when backwards compatible behavior is enabled. In all other circumstances, support
               for the namespace axis is optional.</p><note><p>There are no incompatibilities between 3.0 and 2.0 that would
                  justify a 2.0-compatibility mode. When a 3.0 processor encounters a stylesheet
                  that specifies <code nobreak="false">version="2.0"</code>, evaluation therefore proceeds exactly
                  as if it specified <code nobreak="false">version="3.0"</code>. However, a software product may
                  invoke an XSLT 2.0 processor in preference to an XSLT 3.0 processor when the
                  stylesheet specifies <code nobreak="false">version="2.0"</code>, in which case any use of new 3.0
                  constructs will be rejected.</p><p>There are cases where setting <code nobreak="false">[xsl:]version</code> to a value less than
               4.0 affects the behavior of an XSLT 4.0 stylesheet: see <specref ref="incompatibilities"/>.
               However these are sufficiently minor that they do not warrant the introduction of a
               separate conformance option.</p></note></div2><div2 id="streaming-feature"><head>Streaming Feature</head><p>
               <termdef id="dt-streaming-feature" term="streaming feature">A processor that claims
                  conformance with the <term>streaming feature</term>
                  <rfc2119>must</rfc2119> use streamed processing in cases where (a) streaming is
                  requested (for example by using the attribute <code nobreak="false">streamable="yes"</code> on
                  <elcode>xsl:mode</elcode>, or on
                  the <elcode>xsl:source-document</elcode> instruction) and
                  (b) the constructs in question are <xtermref spec="SG40" ref="dt-guaranteed-streamable"/>
                  according to this specification.</termdef>
            </p><p>A processor that does not claim conformance with the streaming feature is not
               required to use streamed processing and is not required to determine whether any
               construct is guaranteed streamable. Such a processor must, however, implement the
               semantics of all constructs in the language provided that enough memory is available
               to perform the processing without streaming.</p><p>A processor that conforms with the feature <rfc2119>must</rfc2119>
               return the value <code nobreak="false">"yes"</code> in response to the function call
                  <code nobreak="false">system-property('xsl:supports-streaming')</code>; a processor that does not
               conform with the feature <rfc2119>must</rfc2119> return the value
               <code nobreak="false">"no"</code>.</p><note><p>The term <emph>streamed processing</emph> as used here means the ability to
                  process arbitrarily large input documents without ever-increasing memory
                  requirements.</p></note></div2></div1></body><back><div1 id="references"><head>References</head><div2 id="normative-references"><head>Normative References</head><blist><bibl xmlns:xlink="http://www.w3.org/1999/xlink" id="xpath-datamodel-40" key="XDM 4.0" xlink:type="simple" xlink:show="replace" xlink:actuate="onRequest"/><bibl xmlns:xlink="http://www.w3.org/1999/xlink" id="xpath-functions-40" key="Functions and Operators 4.0" xlink:type="simple" xlink:show="replace" xlink:actuate="onRequest">
                 <emph>CITATION: T.B.D.</emph>
               </bibl><bibl xmlns:xlink="http://www.w3.org/1999/xlink" id="xml-infoset" key="XML Information Set" xlink:type="simple" xlink:show="replace" xlink:actuate="onRequest"/><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. See <loc href="https://www.iso.org/obp/ui/#!iso:std:iso:15924:ed-1:v1:en" xlink:type="simple" xlink:show="replace" xlink:actuate="onRequest"/>.</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="ISO21320" key="ISO 21320" xlink:type="simple" xlink:show="replace" xlink:actuate="onRequest">ISO (International Organization for
                  Standardization) <emph>Information technology — Document Container File, Part 1: Core</emph> 
                  ISO 21320-1:2015, October 2015. See <loc href="https://www.iso.org/obp/ui/#iso:std:iso-iec:21320:-1:ed-1:v1:en" xlink:type="simple" xlink:show="replace" xlink:actuate="onRequest"/>.</bibl><bibl xmlns:xlink="http://www.w3.org/1999/xlink" id="xslt-xquery-serialization-40" key="Serialization 4.0" xlink:type="simple" xlink:show="replace" xlink:actuate="onRequest"/><bibl xmlns:xlink="http://www.w3.org/1999/xlink" id="rfc7595" key="RFC 7595" xlink:type="simple" xlink:show="replace" xlink:actuate="onRequest">IETF. <emph>Guidelines and Registration Procedures for URI Schemes.</emph>
                  June 2015. See <loc href="http://www.ietf.org/rfc/rfc7595.txt" xlink:type="simple" xlink:show="replace" xlink:actuate="onRequest">http://www.ietf.org/rfc/rfc7595.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>The JavaScript Object Notation (JSON)
                     Data Interchange Format.</emph>
                  March 2014. See <loc href="http://www.ietf.org/rfc/rfc7159.txt" xlink:type="simple" xlink:show="replace" xlink:actuate="onRequest">http://www.ietf.org/rfc/rfc7159.txt</loc>
               </bibl><bibl xmlns:xlink="http://www.w3.org/1999/xlink" id="UNICODE" key="UNICODE" xlink:type="simple" xlink:show="replace" xlink:actuate="onRequest">Unicode Consortium. <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"/> 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="dt-implementation-defined">implementation-defined</termref>, but
                  implementations are recommended to use the latest Unicode version.</bibl><bibl xmlns:xlink="http://www.w3.org/1999/xlink" id="UNICODE-TR10" key="UNICODE TR10" xlink:type="simple" xlink:show="replace" xlink:actuate="onRequest">Unicode Consortium. <emph>Unicode
                     Technical Standard #10. Unicode Collation Algorithm</emph>. Unicode Technical
                  Report. See <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="UNICODE TR35" xlink:type="simple" xlink:show="replace" xlink:actuate="onRequest">Unicode Consortium. <emph>Unicode
                     Technical Standard #35. Unicode Locale Data Markup Language</emph>. Unicode
                  Technical Report. See <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="REC-xml" key="XML 1.0" xlink:type="simple" xlink:show="replace" xlink:actuate="onRequest"> World Wide Web Consortium. <emph>Extensible Markup
                     Language (XML) 1.0. W3C Recommendation.</emph> See <loc href="https://www.w3.org/TR/REC-xml" xlink:type="simple" xlink:show="replace" xlink:actuate="onRequest">http://www.w3.org/TR/REC-xml/</loc>. The
                  edition of XML 1.0 must be no earlier than the Third Edition; the edition used is
                     <termref def="dt-implementation-defined"/>, but we recommend that
                  implementations use the latest version. </bibl><bibl xmlns:xlink="http://www.w3.org/1999/xlink" id="xml11" key="XML 1.1" xlink:type="simple" xlink:show="replace" xlink:actuate="onRequest"/><bibl xmlns:xlink="http://www.w3.org/1999/xlink" id="xmlbase" key="XML Base" xlink:type="simple" xlink:show="replace" xlink:actuate="onRequest"/><bibl xmlns:xlink="http://www.w3.org/1999/xlink" id="xml-id" key="xml:id" 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"/><bibl xmlns:xlink="http://www.w3.org/1999/xlink" id="xml-names11" key="Namespaces in XML 1.1" xlink:type="simple" xlink:show="replace" xlink:actuate="onRequest"/><bibl xmlns:xlink="http://www.w3.org/1999/xlink" id="xmlschema-1" key="XML Schema Part 1" 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" xlink:type="simple" xlink:show="replace" xlink:actuate="onRequest"/><bibl xmlns:xlink="http://www.w3.org/1999/xlink" id="xmlschema11-1" key="XML Schema 1.1 Part 1" xlink:type="simple" xlink:show="replace" xlink:actuate="onRequest"/><bibl xmlns:xlink="http://www.w3.org/1999/xlink" id="xmlschema11-2" key="XML Schema 1.1 Part 2" xlink:type="simple" xlink:show="replace" xlink:actuate="onRequest"/><bibl xmlns:xlink="http://www.w3.org/1999/xlink" id="xpath-40" key="XPath 4.0" xlink:type="simple" xlink:show="replace" xlink:actuate="onRequest">
                 <emph>CITATION: T.B.D.</emph>
               </bibl><bibl xmlns:xlink="http://www.w3.org/1999/xlink" id="XSLT-Mime-Type" key="XSLT Media Type" xlink:type="simple" xlink:show="replace" xlink:actuate="onRequest">World Wide Web Consortium.
                     <emph>Registration of MIME Media Type application/xslt+xml</emph>. In <loc href="https://www.w3.org/TR/2007/REC-xslt20-20070123/#media-type-registration" xlink:type="simple" xlink:show="replace" xlink:actuate="onRequest">Appendix B.1 of the XSLT 2.0 specification.</loc></bibl><bibl xmlns:xlink="http://www.w3.org/1999/xlink" id="xslt40streaming" key="XSLT 4.0 Streaming" xlink:type="simple" xlink:show="replace" xlink:actuate="onRequest"/></blist></div2><div2 id="other-references"><head>Other References</head><blist><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="DOM-Level-2-Core" key="DOM Level 2" xlink:type="simple" xlink:show="replace" xlink:actuate="onRequest"/><bibl xmlns:xlink="http://www.w3.org/1999/xlink" id="ECMA-404" key="ECMA-404" xlink:type="simple" xlink:show="replace" xlink:actuate="onRequest"> ECMA International. <emph>The JSON Data
                     Interchange Format</emph> October 2013. See <loc href="http://www.ecma-international.org/publications/files/ECMA-ST/ECMA-404.pdf" xlink:type="simple" xlink:show="replace" xlink:actuate="onRequest">http://www.ecma-international.org/publications/files/ECMA-ST/ECMA-404.pdf</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="rfc2119" key="RFC2119" xlink:type="simple" xlink:show="replace" xlink:actuate="onRequest">S. Bradner. <emph>Key words for use in RFCs to
                     Indicate Requirement Levels</emph>. IETF RFC 2119. See <loc href="http://www.ietf.org/rfc/rfc2119.txt" xlink:type="simple" xlink:show="replace" xlink:actuate="onRequest"/>.</bibl><bibl xmlns:xlink="http://www.w3.org/1999/xlink" id="RFC3986" key="RFC3986" xlink:type="simple" xlink:show="replace" xlink:actuate="onRequest"> T. Berners-Lee, R. Fielding, and L. Masinter.
                     <emph>Uniform Resource Identifiers (URI): Generic Syntax</emph>. IETF RFC 3986.
                  See <loc href="http://www.ietf.org/rfc/rfc3986.txt" xlink:type="simple" xlink:show="replace" xlink:actuate="onRequest"/>.</bibl><bibl xmlns:xlink="http://www.w3.org/1999/xlink" id="RFC3987" key="RFC3987" xlink:type="simple" xlink:show="replace" xlink:actuate="onRequest">M. Duerst, M. Suignard. <emph>Internationalized
                     Resource Identifiers (IRIs)</emph>. IETF RFC 3987. See <loc href="http://www.ietf.org/rfc/rfc3987.txt" xlink:type="simple" xlink:show="replace" xlink:actuate="onRequest"/>.</bibl><bibl xmlns:xlink="http://www.w3.org/1999/xlink" id="RFC4647" key="RFC4647" xlink:type="simple" xlink:show="replace" xlink:actuate="onRequest">A. Phillips and M. Davis. <emph>Matching of Language Tags</emph>. IETF RFC 4647. See <loc href="http://www.ietf.org/rfc/rfc4647.txt" xlink:type="simple" xlink:show="replace" xlink:actuate="onRequest"/>.</bibl><bibl xmlns:xlink="http://www.w3.org/1999/xlink" id="rfc7303" key="RFC7303" 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"/></bibl><bibl xmlns:xlink="http://www.w3.org/1999/xlink" id="SemVer" key="SemVer" xlink:type="simple" xlink:show="replace" xlink:actuate="onRequest">Tom Preston-Werner, <emph>Semantic Versioning
                     2.0.0</emph>. See <loc href="http://semver.org/" xlink:type="simple" xlink:show="replace" xlink:actuate="onRequest"/>. Undated (retrieved 1 August
                  2014).</bibl><bibl xmlns:xlink="http://www.w3.org/1999/xlink" id="STX" key="STX" xlink:type="simple" xlink:show="replace" xlink:actuate="onRequest">Petr Cimprich <emph>et al</emph>, <emph>Streaming
                     Transformations for XML (STX) Version 1.0</emph>. Working Draft 27 April 2007.
                  See <loc href="http://stx.sourceforge.net/documents/spec-stx-20070427.html" xlink:type="simple" xlink:show="replace" xlink:actuate="onRequest"/>
               </bibl><bibl xmlns:xlink="http://www.w3.org/1999/xlink" id="xlink" key="XLink" xlink:type="simple" xlink:show="replace" xlink:actuate="onRequest"/><bibl xmlns:xlink="http://www.w3.org/1999/xlink" id="SCHEMA-AND-XML-1.1" key="XML Schema 1.0 and XML 1.1" xlink:type="simple" xlink:show="replace" xlink:actuate="onRequest">World Wide Web
                  Consortium. <emph>Processing XML 1.1 documents with XML Schema 1.0
                     processors</emph>. W3C Working Group Note 11 May 2005. See <loc href="https://www.w3.org/TR/2005/NOTE-xml11schema10-20050511/" xlink:type="simple" xlink:show="replace" xlink:actuate="onRequest"/>
               </bibl><bibl xmlns:xlink="http://www.w3.org/1999/xlink" id="xml-stylesheet" key="XML Stylesheet" xlink:type="simple" xlink:show="replace" xlink:actuate="onRequest"/><bibl xmlns:xlink="http://www.w3.org/1999/xlink" id="xptr-framework" key="XPointer Framework" xlink:type="simple" xlink:show="replace" xlink:actuate="onRequest"/><bibl xmlns:xlink="http://www.w3.org/1999/xlink" id="xsl11" key="XSL-FO" xlink:type="simple" xlink:show="replace" xlink:actuate="onRequest"/><bibl xmlns:xlink="http://www.w3.org/1999/xlink" id="xslt" key="XSLT 1.0" xlink:type="simple" xlink:show="replace" xlink:actuate="onRequest"/><bibl xmlns:xlink="http://www.w3.org/1999/xlink" id="xslt20" key="XSLT 2.0" xlink:type="simple" xlink:show="replace" xlink:actuate="onRequest"/><bibl xmlns:xlink="http://www.w3.org/1999/xlink" id="xslt-30" key="XSLT 3.0" xlink:type="simple" xlink:show="replace" xlink:actuate="onRequest"/></blist></div2></div1><inform-div1 id="glossary"><head>Glossary</head><?glossary?></inform-div1><inform-div1 id="element-syntax-summary"><head>Element Syntax Summary</head><?element-syntax-summary?></inform-div1><inform-div1 id="error-summary"><head>Summary of Error Conditions</head><p>This appendix provides a summary of error conditions that a processor
            may raise. This list includes all error codes defined in this specification, but this
            is not an exhaustive list of all errors that can occur. Implementations
               <rfc2119>must</rfc2119> raise errors using these error codes, and applications can
            test for these codes; however, when more than one rule in the specification is violated,
            different processors will not necessarily raise the same error code. Implementations
            are not <rfc2119>required</rfc2119> to raise errors using the descriptive text used
            here.</p><note><p>The appendix is non-normative because the same information is given normatively
               elsewhere.</p></note><?error-summary?></inform-div1><inform-div1 id="pattern-syntax-summary"><head>Pattern Syntax Summary</head><p>This appendix gives the grammar for XSLT patterns. The top-level rule for
         patterns is <nt xmlns:xlink="http://www.w3.org/1999/xlink" def="doc-xslt40-Pattern" xlink:type="simple"/>.</p><p>This is an extension of the grammar for XPath expressions.
            The extended BNF notation is explained at <xspecref spec="XP40" ref="EBNFNotation"/>.</p><p>Productions that are identical to their counterparts in XPath 4.0 are suffixed
         <code nobreak="false">XP</code> and link to the corresponding production in the XPath 4.0 specification.
         Productions whose names end with <code nobreak="false">P</code> are restrictions of the corresponding
         XPath production: for example, <code nobreak="false">ArgumentListP</code> is a restricted form of the
         XPath production <code nobreak="false">ArgumentList</code>.</p><div2 id="ebnf-for-patterns"><scrap id="BNF-Grammar" role="non-terminal-structure-expand" headstyle="show"><prodgroup><prod id="prod-xslt40-AbbrevForwardStepP"><lhs>AbbrevForwardStepP</lhs><rhs>("@"  <xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="XP40" ref="prod-xpath40-NodeTest" xlink:type="simple">NodeTest</xnt>)  |  <xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="XP40" ref="prod-xpath40-SimpleNodeTest" xlink:type="simple">SimpleNodeTest</xnt></rhs></prod><prod id="prod-xslt40-AbbreviatedStep"><lhs>AbbreviatedStep</lhs><rhs>".."  |  ("@"  <xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="XP40" ref="prod-xpath40-NodeTest" xlink:type="simple">NodeTest</xnt>)  |  <xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="XP40" ref="prod-xpath40-SimpleNodeTest" xlink:type="simple">SimpleNodeTest</xnt></rhs></prod><prod id="prod-xslt40-AbsolutePathExpr"><lhs>AbsolutePathExpr</lhs><rhs>("/"  <xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="XP40" ref="prod-xpath40-RelativePathExpr" xlink:type="simple">RelativePathExpr</xnt>?)  |  ("//"  <xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="XP40" ref="prod-xpath40-RelativePathExpr" xlink:type="simple">RelativePathExpr</xnt>)</rhs></prod><prod id="prod-xslt40-AdditiveExpr"><lhs>AdditiveExpr</lhs><rhs><xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="XP40" ref="prod-xpath40-MultiplicativeExpr" xlink:type="simple">MultiplicativeExpr</xnt>  (("+"  |  "-")  <xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="XP40" ref="prod-xpath40-MultiplicativeExpr" xlink:type="simple">MultiplicativeExpr</xnt>)*</rhs></prod><prod id="prod-xslt40-AndExpr"><lhs>AndExpr</lhs><rhs><xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="XP40" ref="prod-xpath40-ComparisonExpr" xlink:type="simple">ComparisonExpr</xnt>  ("and"  <xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="XP40" ref="prod-xpath40-ComparisonExpr" xlink:type="simple">ComparisonExpr</xnt>)*</rhs></prod><prod id="prod-xslt40-AnyArrayType"><lhs>AnyArrayType</lhs><rhs>"array"  "("  "*"  ")"</rhs></prod><prod id="prod-xslt40-AnyFunctionType"><lhs>AnyFunctionType</lhs><rhs>("function"  |  "fn")  "("  "*"  ")"</rhs></prod><prod id="prod-xslt40-AnyItemType"><lhs>AnyItemType</lhs><rhs>"item"  "("  ")"</rhs></prod><prod id="prod-xslt40-AnyMapType"><lhs>AnyMapType</lhs><rhs>"map"  "("  "*"  ")"</rhs></prod><prod id="prod-xslt40-AnyXNodeType"><lhs>AnyXNodeType</lhs><rhs>"node"  "("  ")"</rhs></prod><prod id="prod-xslt40-Argument"><lhs>Argument</lhs><rhs><xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="XP40" ref="prod-xpath40-ExprSingle" xlink:type="simple">ExprSingle</xnt>  |  <xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="XP40" ref="prod-xpath40-ArgumentPlaceholder" xlink:type="simple">ArgumentPlaceholder</xnt></rhs></prod><prod id="prod-xslt40-ArgumentList"><lhs>ArgumentList</lhs><rhs>"("  ((<xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="XP40" ref="prod-xpath40-PositionalArguments" xlink:type="simple">PositionalArguments</xnt>  (","  <xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="XP40" ref="prod-xpath40-KeywordArguments" xlink:type="simple">KeywordArguments</xnt>)?)  |  <xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="XP40" ref="prod-xpath40-KeywordArguments" xlink:type="simple">KeywordArguments</xnt>)?  ")"</rhs></prod><prod id="prod-xslt40-ArgumentListP"><lhs>ArgumentListP</lhs><rhs>"("  (<nt xmlns:xlink="http://www.w3.org/1999/xlink" def="prod-xslt40-ArgumentP" xlink:type="simple">ArgumentP</nt> ** ",")  ")"</rhs></prod><prod id="prod-xslt40-ArgumentP"><lhs>ArgumentP</lhs><rhs><xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="XP40" ref="prod-xpath40-VarRef" xlink:type="simple">VarRef</xnt>  |  <xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="XP40" ref="prod-xpath40-Constant" xlink:type="simple">Constant</xnt></rhs></prod><prod id="prod-xslt40-ArgumentPlaceholder"><lhs>ArgumentPlaceholder</lhs><rhs>"?"</rhs></prod><prod id="prod-xslt40-ArrayConstructor"><lhs>ArrayConstructor</lhs><rhs><xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="XP40" ref="prod-xpath40-SquareArrayConstructor" xlink:type="simple">SquareArrayConstructor</xnt>  |  <xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="XP40" ref="prod-xpath40-CurlyArrayConstructor" xlink:type="simple">CurlyArrayConstructor</xnt></rhs></prod><prod id="prod-xslt40-ArrayType"><lhs>ArrayType</lhs><rhs><xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="XP40" ref="prod-xpath40-AnyArrayType" xlink:type="simple">AnyArrayType</xnt>  |  <xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="XP40" ref="prod-xpath40-TypedArrayType" xlink:type="simple">TypedArrayType</xnt></rhs></prod><prod id="prod-xslt40-ArrowExpr"><lhs>ArrowExpr</lhs><rhs><xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="XP40" ref="prod-xpath40-UnaryExpr" xlink:type="simple">UnaryExpr</xnt>  (<xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="XP40" ref="prod-xpath40-SequenceArrowTarget" xlink:type="simple">SequenceArrowTarget</xnt>  |  <xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="XP40" ref="prod-xpath40-MappingArrowTarget" xlink:type="simple">MappingArrowTarget</xnt>)*</rhs></prod><prod id="prod-xslt40-ArrowTarget"><lhs>ArrowTarget</lhs><rhs><xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="XP40" ref="prod-xpath40-FunctionCall" xlink:type="simple">FunctionCall</xnt>  |  <xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="XP40" ref="prod-xpath40-RestrictedDynamicCall" xlink:type="simple">RestrictedDynamicCall</xnt></rhs></prod><prod id="prod-xslt40-AttributeName"><lhs>AttributeName</lhs><rhs><xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="XP40" ref="prod-xpath40-EQName" xlink:type="simple">EQName</xnt></rhs></prod><prod id="prod-xslt40-AttributeNodeType"><lhs>AttributeNodeType</lhs><rhs>"attribute"  "("  (<xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="XP40" ref="prod-xpath40-NameTestUnion" xlink:type="simple">NameTestUnion</xnt>  (","  <xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="XP40" ref="prod-xpath40-TypeName" xlink:type="simple">TypeName</xnt>)?)?  ")"</rhs></prod><prod id="prod-xslt40-Axis"><lhs>Axis</lhs><rhs>("ancestor"  |  "ancestor-or-self"  |  "attribute"  |  "child"  |  "descendant"  |  "descendant-or-self"  |  "following"  |  "following-or-self"  |  "following-sibling"  |  "following-sibling-or-self"  |  "namespace"  |  "parent"  |  "preceding"  |  "preceding-or-self"  |  "preceding-sibling"  |  "preceding-sibling-or-self"  |  "self")  "::"</rhs></prod><prod id="prod-xslt40-AxisStep"><lhs>AxisStep</lhs><rhs>(<xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="XP40" ref="prod-xpath40-AbbreviatedStep" xlink:type="simple">AbbreviatedStep</xnt>  |  <xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="XP40" ref="prod-xpath40-FullStep" xlink:type="simple">FullStep</xnt>)  <xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="XP40" ref="prod-xpath40-Predicate" xlink:type="simple">Predicate</xnt>*</rhs></prod><prod id="prod-xslt40-AxisStepP"><lhs>AxisStepP</lhs><rhs><nt xmlns:xlink="http://www.w3.org/1999/xlink" def="prod-xslt40-ForwardStepP" xlink:type="simple">ForwardStepP</nt>  <xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="XP40" ref="prod-xpath40-Predicate" xlink:type="simple">Predicate</xnt>*</rhs></prod><prod id="prod-xslt40-BracedAction"><lhs>BracedAction</lhs><rhs><xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="XP40" ref="prod-xpath40-EnclosedExpr" xlink:type="simple">EnclosedExpr</xnt></rhs></prod><prod id="prod-xslt40-CastableExpr"><lhs>CastableExpr</lhs><rhs><xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="XP40" ref="prod-xpath40-CastExpr" xlink:type="simple">CastExpr</xnt>  ("castable"  "as"  <xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="XP40" ref="prod-xpath40-CastTarget" xlink:type="simple">CastTarget</xnt>  "?"?)?</rhs></prod><prod id="prod-xslt40-CastExpr"><lhs>CastExpr</lhs><rhs><xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="XP40" ref="prod-xpath40-PipelineExpr" xlink:type="simple">PipelineExpr</xnt>  ("cast"  "as"  <xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="XP40" ref="prod-xpath40-CastTarget" xlink:type="simple">CastTarget</xnt>  "?"?)?</rhs></prod><prod id="prod-xslt40-CastTarget"><lhs>CastTarget</lhs><rhs><xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="XP40" ref="prod-xpath40-TypeName" xlink:type="simple">TypeName</xnt></rhs></prod><prod id="prod-xslt40-ChoiceItemType"><lhs>ChoiceItemType</lhs><rhs>"("  (<xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="XP40" ref="prod-xpath40-ItemType" xlink:type="simple">ItemType</xnt> ++ "|")  ")"</rhs></prod><prod id="prod-xslt40-CommentNodeType"><lhs>CommentNodeType</lhs><rhs>"comment"  "("  ")"</rhs></prod><prod id="prod-xslt40-ComparisonExpr"><lhs>ComparisonExpr</lhs><rhs><xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="XP40" ref="prod-xpath40-OtherwiseExpr" xlink:type="simple">OtherwiseExpr</xnt>  ((<xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="XP40" ref="prod-xpath40-ValueComp" xlink:type="simple">ValueComp</xnt>  |  <xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="XP40" ref="prod-xpath40-GeneralComp" xlink:type="simple">GeneralComp</xnt>  |  <xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="XP40" ref="prod-xpath40-NodeComp" xlink:type="simple">NodeComp</xnt>)  <xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="XP40" ref="prod-xpath40-OtherwiseExpr" xlink:type="simple">OtherwiseExpr</xnt>)?</rhs></prod><prod id="prod-xslt40-Constant"><lhs>Constant</lhs><rhs><xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="XP40" ref="prod-xpath40-StringLiteral" xlink:type="simple">StringLiteral</xnt>  |  ("-"?  <xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="XP40" ref="prod-xpath40-NumericLiteral" xlink:type="simple">NumericLiteral</xnt>)  |  <xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="XP40" ref="prod-xpath40-QNameLiteral" xlink:type="simple">QNameLiteral</xnt>  |  ("true"  "("  ")")  |  ("false"  "("  ")")</rhs></prod><prod id="prod-xslt40-ContextValueRef"><lhs>ContextValueRef</lhs><rhs>"."</rhs></prod><prod id="prod-xslt40-CurlyArrayConstructor"><lhs>CurlyArrayConstructor</lhs><rhs>"array"  <xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="XP40" ref="prod-xpath40-EnclosedExpr" xlink:type="simple">EnclosedExpr</xnt></rhs></prod><prod id="prod-xslt40-DocumentNodeType"><lhs>DocumentNodeType</lhs><rhs>"document-node"  "("  (<xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="XP40" ref="prod-xpath40-ElementNodeType" xlink:type="simple">ElementNodeType</xnt>  |  <xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="XP40" ref="prod-xpath40-SchemaElementNodeType" xlink:type="simple">SchemaElementNodeType</xnt>  |  <xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="XP40" ref="prod-xpath40-NameTestUnion" xlink:type="simple">NameTestUnion</xnt>)?  ")"</rhs></prod><prod id="prod-xslt40-DynamicFunctionCall"><lhs>DynamicFunctionCall</lhs><rhs><xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="XP40" ref="prod-xpath40-PostfixExpr" xlink:type="simple">PostfixExpr</xnt>  <xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="XP40" ref="prod-xpath40-PositionalArgumentList" xlink:type="simple">PositionalArgumentList</xnt></rhs></prod><prod id="prod-xslt40-ElementName"><lhs>ElementName</lhs><rhs><xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="XP40" ref="prod-xpath40-EQName" xlink:type="simple">EQName</xnt></rhs></prod><prod id="prod-xslt40-ElementNodeType"><lhs>ElementNodeType</lhs><rhs>"element"  "("  (<xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="XP40" ref="prod-xpath40-NameTestUnion" xlink:type="simple">NameTestUnion</xnt>  (","  <xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="XP40" ref="prod-xpath40-TypeName" xlink:type="simple">TypeName</xnt>  "?"?)?)?  ")"</rhs></prod><prod id="prod-xslt40-EnclosedExpr"><lhs>EnclosedExpr</lhs><rhs>"{"  <xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="XP40" ref="prod-xpath40-Expr" xlink:type="simple">Expr</xnt>?  "}"</rhs></prod><prod id="prod-xslt40-EnumerationType"><lhs>EnumerationType</lhs><rhs>"enum"  "("  (<xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="XP40" ref="prod-xpath40-StringLiteral" xlink:type="simple">StringLiteral</xnt> ++ ",")  ")"</rhs></prod><prod id="prod-xslt40-EQName"><lhs>EQName</lhs><rhs><nt xmlns:xlink="http://www.w3.org/1999/xlink" def="prod-xslt40-QName" xlink:type="simple">QName</nt>  |  <xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="XP40" ref="prod-xpath40-URIQualifiedName" xlink:type="simple">URIQualifiedName</xnt></rhs></prod><prod id="prod-xslt40-Expr"><lhs>Expr</lhs><rhs>(<xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="XP40" ref="prod-xpath40-ExprSingle" xlink:type="simple">ExprSingle</xnt> ++ ",")</rhs></prod><prod id="prod-xslt40-ExprSingle"><lhs>ExprSingle</lhs><rhs><xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="XP40" ref="prod-xpath40-ForExpr" xlink:type="simple">ForExpr</xnt><br/>|  <xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="XP40" ref="prod-xpath40-LetExpr" xlink:type="simple">LetExpr</xnt><br/>|  <xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="XP40" ref="prod-xpath40-QuantifiedExpr" xlink:type="simple">QuantifiedExpr</xnt><br/>|  <xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="XP40" ref="prod-xpath40-IfExpr" xlink:type="simple">IfExpr</xnt></rhs></prod><prod id="prod-xslt40-FieldDeclaration"><lhs>FieldDeclaration</lhs><rhs><xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="XP40" ref="prod-xpath40-FieldName" xlink:type="simple">FieldName</xnt>  "?"?  ("as"  <xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="XP40" ref="prod-xpath40-SequenceType" xlink:type="simple">SequenceType</xnt>)?</rhs></prod><prod id="prod-xslt40-FieldName"><lhs>FieldName</lhs><rhs><xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="XP40" ref="prod-xpath40-NCName" xlink:type="simple">NCName</xnt>  |  <xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="XP40" ref="prod-xpath40-StringLiteral" xlink:type="simple">StringLiteral</xnt></rhs></prod><prod id="prod-xslt40-FilterExpr"><lhs>FilterExpr</lhs><rhs><xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="XP40" ref="prod-xpath40-PostfixExpr" xlink:type="simple">PostfixExpr</xnt>  <xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="XP40" ref="prod-xpath40-Predicate" xlink:type="simple">Predicate</xnt></rhs></prod><prod id="prod-xslt40-FilterExprAM"><lhs>FilterExprAM</lhs><rhs><xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="XP40" ref="prod-xpath40-PostfixExpr" xlink:type="simple">PostfixExpr</xnt>  "?["  <xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="XP40" ref="prod-xpath40-Expr" xlink:type="simple">Expr</xnt>  "]"</rhs></prod><prod id="prod-xslt40-ForBinding"><lhs>ForBinding</lhs><rhs><xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="XP40" ref="prod-xpath40-ForItemBinding" xlink:type="simple">ForItemBinding</xnt>  |  <xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="XP40" ref="prod-xpath40-ForMemberBinding" xlink:type="simple">ForMemberBinding</xnt>  |  <xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="XP40" ref="prod-xpath40-ForEntryBinding" xlink:type="simple">ForEntryBinding</xnt></rhs></prod><prod id="prod-xslt40-ForClause"><lhs>ForClause</lhs><rhs>"for"  (<xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="XP40" ref="prod-xpath40-ForBinding" xlink:type="simple">ForBinding</xnt> ++ ",")</rhs></prod><prod id="prod-xslt40-ForEntryBinding"><lhs>ForEntryBinding</lhs><rhs>((<xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="XP40" ref="prod-xpath40-ForEntryKeyBinding" xlink:type="simple">ForEntryKeyBinding</xnt>  <xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="XP40" ref="prod-xpath40-ForEntryValueBinding" xlink:type="simple">ForEntryValueBinding</xnt>?)  |  <xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="XP40" ref="prod-xpath40-ForEntryValueBinding" xlink:type="simple">ForEntryValueBinding</xnt>)  <xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="XP40" ref="prod-xpath40-PositionalVar" xlink:type="simple">PositionalVar</xnt>?  "in"  <xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="XP40" ref="prod-xpath40-ExprSingle" xlink:type="simple">ExprSingle</xnt></rhs></prod><prod id="prod-xslt40-ForEntryKeyBinding"><lhs>ForEntryKeyBinding</lhs><rhs>"key"  <xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="XP40" ref="prod-xpath40-VarNameAndType" xlink:type="simple">VarNameAndType</xnt></rhs></prod><prod id="prod-xslt40-ForEntryValueBinding"><lhs>ForEntryValueBinding</lhs><rhs>"value"  <xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="XP40" ref="prod-xpath40-VarNameAndType" xlink:type="simple">VarNameAndType</xnt></rhs></prod><prod id="prod-xslt40-ForExpr"><lhs>ForExpr</lhs><rhs><xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="XP40" ref="prod-xpath40-ForClause" xlink:type="simple">ForClause</xnt>  <xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="XP40" ref="prod-xpath40-ForLetReturn" xlink:type="simple">ForLetReturn</xnt></rhs></prod><prod id="prod-xslt40-ForItemBinding"><lhs>ForItemBinding</lhs><rhs><xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="XP40" ref="prod-xpath40-VarNameAndType" xlink:type="simple">VarNameAndType</xnt>  <xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="XP40" ref="prod-xpath40-PositionalVar" xlink:type="simple">PositionalVar</xnt>?  "in"  <xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="XP40" ref="prod-xpath40-ExprSingle" xlink:type="simple">ExprSingle</xnt></rhs></prod><prod id="prod-xslt40-ForLetReturn"><lhs>ForLetReturn</lhs><rhs><xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="XP40" ref="prod-xpath40-ForExpr" xlink:type="simple">ForExpr</xnt>  |  <xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="XP40" ref="prod-xpath40-LetExpr" xlink:type="simple">LetExpr</xnt>  |  ("return"  <xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="XP40" ref="prod-xpath40-ExprSingle" xlink:type="simple">ExprSingle</xnt>)</rhs></prod><prod id="prod-xslt40-ForMemberBinding"><lhs>ForMemberBinding</lhs><rhs>"member"  <xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="XP40" ref="prod-xpath40-VarNameAndType" xlink:type="simple">VarNameAndType</xnt>  <xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="XP40" ref="prod-xpath40-PositionalVar" xlink:type="simple">PositionalVar</xnt>?  "in"  <xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="XP40" ref="prod-xpath40-ExprSingle" xlink:type="simple">ExprSingle</xnt></rhs></prod><prod id="prod-xslt40-ForwardAxisP"><lhs>ForwardAxisP</lhs><rhs>("child"  "::")<br/>|  ("descendant"  "::")<br/>|  ("attribute"  "::")<br/>|  ("self"  "::")<br/>|  ("descendant-or-self"  "::")<br/>|  ("namespace"  "::")</rhs></prod><prod id="prod-xslt40-ForwardStepP"><lhs>ForwardStepP</lhs><rhs>(<nt xmlns:xlink="http://www.w3.org/1999/xlink" def="prod-xslt40-ForwardAxisP" xlink:type="simple">ForwardAxisP</nt>  <xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="XP40" ref="prod-xpath40-NodeTest" xlink:type="simple">NodeTest</xnt>)  |  <nt xmlns:xlink="http://www.w3.org/1999/xlink" def="prod-xslt40-AbbrevForwardStepP" xlink:type="simple">AbbrevForwardStepP</nt></rhs></prod><prod id="prod-xslt40-FullStep"><lhs>FullStep</lhs><rhs><xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="XP40" ref="prod-xpath40-Axis" xlink:type="simple">Axis</xnt>  <xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="XP40" ref="prod-xpath40-NodeTest" xlink:type="simple">NodeTest</xnt></rhs></prod><prod id="prod-xslt40-FunctionBody"><lhs>FunctionBody</lhs><rhs><xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="XP40" ref="prod-xpath40-EnclosedExpr" xlink:type="simple">EnclosedExpr</xnt></rhs></prod><prod id="prod-xslt40-FunctionCall"><lhs>FunctionCall</lhs><rhs><xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="XP40" ref="prod-xpath40-EQName" xlink:type="simple">EQName</xnt>  <xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="XP40" ref="prod-xpath40-ArgumentList" xlink:type="simple">ArgumentList</xnt></rhs><com><loc xmlns:xlink="http://www.w3.org/1999/xlink" href="#parse-note-reserved-function-names" xlink:type="simple" xlink:show="replace" xlink:actuate="onRequest">xgs: reserved-function-names</loc></com><com><loc xmlns:xlink="http://www.w3.org/1999/xlink" href="#parse-note-parens" xlink:type="simple" xlink:show="replace" xlink:actuate="onRequest">gn: parens</loc></com></prod><prod id="prod-xslt40-FunctionCallP"><lhs>FunctionCallP</lhs><rhs><nt xmlns:xlink="http://www.w3.org/1999/xlink" def="prod-xslt40-OuterFunctionName" xlink:type="simple">OuterFunctionName</nt>  <nt xmlns:xlink="http://www.w3.org/1999/xlink" def="prod-xslt40-ArgumentListP" xlink:type="simple">ArgumentListP</nt></rhs></prod><prod id="prod-xslt40-FunctionItemExpr"><lhs>FunctionItemExpr</lhs><rhs><xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="XP40" ref="prod-xpath40-NamedFunctionRef" xlink:type="simple">NamedFunctionRef</xnt>  |  <xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="XP40" ref="prod-xpath40-InlineFunctionExpr" xlink:type="simple">InlineFunctionExpr</xnt></rhs></prod><prod id="prod-xslt40-FunctionSignature"><lhs>FunctionSignature</lhs><rhs>"("  <xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="XP40" ref="prod-xpath40-ParamList" xlink:type="simple">ParamList</xnt>  ")"  <xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="XP40" ref="prod-xpath40-TypeDeclaration" xlink:type="simple">TypeDeclaration</xnt>?</rhs></prod><prod id="prod-xslt40-FunctionType"><lhs>FunctionType</lhs><rhs><xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="XP40" ref="prod-xpath40-AnyFunctionType" xlink:type="simple">AnyFunctionType</xnt><br/>|  <xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="XP40" ref="prod-xpath40-TypedFunctionType" xlink:type="simple">TypedFunctionType</xnt></rhs></prod><prod id="prod-xslt40-GeneralComp"><lhs>GeneralComp</lhs><rhs>"="  |  "!="  |  "&lt;"  |  "&lt;="  |  "&gt;"  |  "&gt;="</rhs></prod><prod id="prod-xslt40-GNodePattern"><lhs>GNodePattern</lhs><rhs><nt xmlns:xlink="http://www.w3.org/1999/xlink" def="prod-xslt40-UnionExprP" xlink:type="simple">UnionExprP</nt></rhs></prod><prod id="prod-xslt40-GNodeType"><lhs>GNodeType</lhs><rhs>"gnode"  "("  ")"</rhs></prod><prod id="prod-xslt40-IfExpr"><lhs>IfExpr</lhs><rhs>"if"  "("  <xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="XP40" ref="prod-xpath40-Expr" xlink:type="simple">Expr</xnt>  ")"  (<xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="XP40" ref="prod-xpath40-UnbracedActions" xlink:type="simple">UnbracedActions</xnt>  |  <xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="XP40" ref="prod-xpath40-BracedAction" xlink:type="simple">BracedAction</xnt>)</rhs></prod><prod id="prod-xslt40-InlineFunctionExpr"><lhs>InlineFunctionExpr</lhs><rhs>("function"  |  "fn")  <xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="XP40" ref="prod-xpath40-FunctionSignature" xlink:type="simple">FunctionSignature</xnt>?  <xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="XP40" ref="prod-xpath40-FunctionBody" xlink:type="simple">FunctionBody</xnt></rhs></prod><prod id="prod-xslt40-InstanceofExpr"><lhs>InstanceofExpr</lhs><rhs><xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="XP40" ref="prod-xpath40-TreatExpr" xlink:type="simple">TreatExpr</xnt>  ("instance"  "of"  <xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="XP40" ref="prod-xpath40-SequenceType" xlink:type="simple">SequenceType</xnt>)?</rhs></prod><prod id="prod-xslt40-IntersectExceptExpr"><lhs>IntersectExceptExpr</lhs><rhs><xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="XP40" ref="prod-xpath40-InstanceofExpr" xlink:type="simple">InstanceofExpr</xnt>  (("intersect"  |  "except")  <xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="XP40" ref="prod-xpath40-InstanceofExpr" xlink:type="simple">InstanceofExpr</xnt>)*</rhs></prod><prod id="prod-xslt40-IntersectExceptExprP"><lhs>IntersectExceptExprP</lhs><rhs><nt xmlns:xlink="http://www.w3.org/1999/xlink" def="prod-xslt40-PathExprP" xlink:type="simple">PathExprP</nt>  (("intersect"  |  "except")  <nt xmlns:xlink="http://www.w3.org/1999/xlink" def="prod-xslt40-PathExprP" xlink:type="simple">PathExprP</nt>)*</rhs></prod><prod id="prod-xslt40-ItemType"><lhs>ItemType</lhs><rhs><xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="XP40" ref="prod-xpath40-RegularItemType" xlink:type="simple">RegularItemType</xnt>  |  <xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="XP40" ref="prod-xpath40-FunctionType" xlink:type="simple">FunctionType</xnt>  |  <xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="XP40" ref="prod-xpath40-TypeName" xlink:type="simple">TypeName</xnt>  |  <xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="XP40" ref="prod-xpath40-ChoiceItemType" xlink:type="simple">ChoiceItemType</xnt></rhs></prod><prod id="prod-xslt40-JNodeType"><lhs>JNodeType</lhs><rhs>"jnode"  "("  (("*"  |  <xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="XP40" ref="prod-xpath40-JRootSelector" xlink:type="simple">JRootSelector</xnt>  |  <xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="XP40" ref="prod-xpath40-NCName" xlink:type="simple">NCName</xnt>  |  <xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="XP40" ref="prod-xpath40-Constant" xlink:type="simple">Constant</xnt>)  (","  <xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="XP40" ref="prod-xpath40-SequenceType" xlink:type="simple">SequenceType</xnt>)?)?  ")"</rhs></prod><prod id="prod-xslt40-JRootSelector"><lhs>JRootSelector</lhs><rhs>"("  ")"</rhs></prod><prod id="prod-xslt40-KeySpecifier"><lhs>KeySpecifier</lhs><rhs><xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="XP40" ref="prod-xpath40-NCName" xlink:type="simple">NCName</xnt>  |  <xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="XP40" ref="prod-xpath40-Literal" xlink:type="simple">Literal</xnt>  |  <xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="XP40" ref="prod-xpath40-ContextValueRef" xlink:type="simple">ContextValueRef</xnt>  |  <xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="XP40" ref="prod-xpath40-VarRef" xlink:type="simple">VarRef</xnt>  |  <xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="XP40" ref="prod-xpath40-ParenthesizedExpr" xlink:type="simple">ParenthesizedExpr</xnt>  |  <xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="XP40" ref="prod-xpath40-LookupWildcard" xlink:type="simple">LookupWildcard</xnt></rhs></prod><prod id="prod-xslt40-KeywordArgument"><lhs>KeywordArgument</lhs><rhs><xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="XP40" ref="prod-xpath40-EQName" xlink:type="simple">EQName</xnt>  ":="  <xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="XP40" ref="prod-xpath40-Argument" xlink:type="simple">Argument</xnt></rhs></prod><prod id="prod-xslt40-KeywordArguments"><lhs>KeywordArguments</lhs><rhs>(<xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="XP40" ref="prod-xpath40-KeywordArgument" xlink:type="simple">KeywordArgument</xnt> ++ ",")</rhs></prod><prod id="prod-xslt40-LetArrayBinding"><lhs>LetArrayBinding</lhs><rhs>"$"  "["  (<xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="XP40" ref="prod-xpath40-VarNameAndType" xlink:type="simple">VarNameAndType</xnt> ++ ",")  "]"  <xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="XP40" ref="prod-xpath40-TypeDeclaration" xlink:type="simple">TypeDeclaration</xnt>?  ":="  <xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="XP40" ref="prod-xpath40-ExprSingle" xlink:type="simple">ExprSingle</xnt></rhs></prod><prod id="prod-xslt40-LetBinding"><lhs>LetBinding</lhs><rhs><xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="XP40" ref="prod-xpath40-LetValueBinding" xlink:type="simple">LetValueBinding</xnt>  |  <xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="XP40" ref="prod-xpath40-LetSequenceBinding" xlink:type="simple">LetSequenceBinding</xnt>  |  <xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="XP40" ref="prod-xpath40-LetArrayBinding" xlink:type="simple">LetArrayBinding</xnt>  |  <xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="XP40" ref="prod-xpath40-LetMapBinding" xlink:type="simple">LetMapBinding</xnt></rhs></prod><prod id="prod-xslt40-LetClause"><lhs>LetClause</lhs><rhs>"let"  (<xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="XP40" ref="prod-xpath40-LetBinding" xlink:type="simple">LetBinding</xnt> ++ ",")</rhs></prod><prod id="prod-xslt40-LetExpr"><lhs>LetExpr</lhs><rhs><xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="XP40" ref="prod-xpath40-LetClause" xlink:type="simple">LetClause</xnt>  <xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="XP40" ref="prod-xpath40-ForLetReturn" xlink:type="simple">ForLetReturn</xnt></rhs></prod><prod id="prod-xslt40-LetMapBinding"><lhs>LetMapBinding</lhs><rhs>"$"  "{"  (<xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="XP40" ref="prod-xpath40-VarNameAndType" xlink:type="simple">VarNameAndType</xnt> ++ ",")  "}"  <xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="XP40" ref="prod-xpath40-TypeDeclaration" xlink:type="simple">TypeDeclaration</xnt>?  ":="  <xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="XP40" ref="prod-xpath40-ExprSingle" xlink:type="simple">ExprSingle</xnt></rhs></prod><prod id="prod-xslt40-LetSequenceBinding"><lhs>LetSequenceBinding</lhs><rhs>"$"  "("  (<xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="XP40" ref="prod-xpath40-VarNameAndType" xlink:type="simple">VarNameAndType</xnt> ++ ",")  ")"  <xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="XP40" ref="prod-xpath40-TypeDeclaration" xlink:type="simple">TypeDeclaration</xnt>?  ":="  <xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="XP40" ref="prod-xpath40-ExprSingle" xlink:type="simple">ExprSingle</xnt></rhs></prod><prod id="prod-xslt40-LetValueBinding"><lhs>LetValueBinding</lhs><rhs><xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="XP40" ref="prod-xpath40-VarNameAndType" xlink:type="simple">VarNameAndType</xnt>  ":="  <xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="XP40" ref="prod-xpath40-ExprSingle" xlink:type="simple">ExprSingle</xnt></rhs></prod><prod id="prod-xslt40-Literal"><lhs>Literal</lhs><rhs><xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="XP40" ref="prod-xpath40-NumericLiteral" xlink:type="simple">NumericLiteral</xnt>  |  <xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="XP40" ref="prod-xpath40-StringLiteral" xlink:type="simple">StringLiteral</xnt>  |  <xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="XP40" ref="prod-xpath40-QNameLiteral" xlink:type="simple">QNameLiteral</xnt></rhs></prod><prod id="prod-xslt40-Lookup"><lhs>Lookup</lhs><rhs>"?"  <xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="XP40" ref="prod-xpath40-KeySpecifier" xlink:type="simple">KeySpecifier</xnt></rhs></prod><prod id="prod-xslt40-LookupExpr"><lhs>LookupExpr</lhs><rhs><xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="XP40" ref="prod-xpath40-PostfixExpr" xlink:type="simple">PostfixExpr</xnt>  <xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="XP40" ref="prod-xpath40-Lookup" xlink:type="simple">Lookup</xnt></rhs></prod><prod id="prod-xslt40-LookupWildcard"><lhs>LookupWildcard</lhs><rhs>"*"</rhs></prod><prod id="prod-xslt40-MapConstructor"><lhs>MapConstructor</lhs><rhs>"map"?  "{"  (<xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="XP40" ref="prod-xpath40-MapConstructorEntry" xlink:type="simple">MapConstructorEntry</xnt> ** ",")  "}"</rhs></prod><prod id="prod-xslt40-MapConstructorEntry"><lhs>MapConstructorEntry</lhs><rhs><xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="XP40" ref="prod-xpath40-ExprSingle" xlink:type="simple">ExprSingle</xnt>  (":"  <xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="XP40" ref="prod-xpath40-ExprSingle" xlink:type="simple">ExprSingle</xnt>)?</rhs></prod><prod id="prod-xslt40-MappingArrowTarget"><lhs>MappingArrowTarget</lhs><rhs>"=!&gt;"  <xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="XP40" ref="prod-xpath40-ArrowTarget" xlink:type="simple">ArrowTarget</xnt></rhs></prod><prod id="prod-xslt40-MapType"><lhs>MapType</lhs><rhs><xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="XP40" ref="prod-xpath40-AnyMapType" xlink:type="simple">AnyMapType</xnt>  |  <xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="XP40" ref="prod-xpath40-TypedMapType" xlink:type="simple">TypedMapType</xnt></rhs></prod><prod id="prod-xslt40-MethodCall"><lhs>MethodCall</lhs><rhs><xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="XP40" ref="prod-xpath40-PostfixExpr" xlink:type="simple">PostfixExpr</xnt>  "=?&gt;"  <xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="XP40" ref="prod-xpath40-NCName" xlink:type="simple">NCName</xnt>  <xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="XP40" ref="prod-xpath40-PositionalArgumentList" xlink:type="simple">PositionalArgumentList</xnt></rhs></prod><prod id="prod-xslt40-MultiplicativeExpr"><lhs>MultiplicativeExpr</lhs><rhs><xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="XP40" ref="prod-xpath40-UnionExpr" xlink:type="simple">UnionExpr</xnt>  (("*"  |  "×"  |  "div"  |  "÷"  |  "idiv"  |  "mod")  <xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="XP40" ref="prod-xpath40-UnionExpr" xlink:type="simple">UnionExpr</xnt>)*</rhs></prod><prod id="prod-xslt40-NamedFunctionRef"><lhs>NamedFunctionRef</lhs><rhs><xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="XP40" ref="prod-xpath40-EQName" xlink:type="simple">EQName</xnt>  "#"  <nt xmlns:xlink="http://www.w3.org/1999/xlink" def="prod-xslt40-IntegerLiteral" xlink:type="simple">IntegerLiteral</nt></rhs><com><loc xmlns:xlink="http://www.w3.org/1999/xlink" href="#parse-note-reserved-function-names" xlink:type="simple" xlink:show="replace" xlink:actuate="onRequest">xgs: reserved-function-names</loc></com></prod><prod id="prod-xslt40-NamespaceNodeType"><lhs>NamespaceNodeType</lhs><rhs>"namespace-node"  "("  ")"</rhs></prod><prod id="prod-xslt40-NameTest"><lhs>NameTest</lhs><rhs><xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="XP40" ref="prod-xpath40-EQName" xlink:type="simple">EQName</xnt>  |  <xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="XP40" ref="prod-xpath40-Wildcard" xlink:type="simple">Wildcard</xnt></rhs></prod><prod id="prod-xslt40-NameTestUnion"><lhs>NameTestUnion</lhs><rhs>(<xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="XP40" ref="prod-xpath40-NameTest" xlink:type="simple">NameTest</xnt> ++ "|")</rhs></prod><prod id="prod-xslt40-NodeComp"><lhs>NodeComp</lhs><rhs>"is"  |  "is-not"  |  <xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="XP40" ref="prod-xpath40-NodePrecedes" xlink:type="simple">NodePrecedes</xnt>  |  <xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="XP40" ref="prod-xpath40-NodeFollows" xlink:type="simple">NodeFollows</xnt>  |  "precedes-or-is"  |  "follows-or-is"</rhs></prod><prod id="prod-xslt40-NodeFollows"><lhs>NodeFollows</lhs><rhs>"&gt;&gt;"  |  "follows"</rhs></prod><prod id="prod-xslt40-NodePrecedes"><lhs>NodePrecedes</lhs><rhs>"&lt;&lt;"  |  "precedes"</rhs></prod><prod id="prod-xslt40-NodeTest"><lhs>NodeTest</lhs><rhs><xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="XP40" ref="prod-xpath40-UnionNodeTest" xlink:type="simple">UnionNodeTest</xnt>  |  <xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="XP40" ref="prod-xpath40-SimpleNodeTest" xlink:type="simple">SimpleNodeTest</xnt></rhs></prod><prod id="prod-xslt40-NumericLiteral"><lhs>NumericLiteral</lhs><rhs><nt xmlns:xlink="http://www.w3.org/1999/xlink" def="prod-xslt40-IntegerLiteral" xlink:type="simple">IntegerLiteral</nt>  |  <nt xmlns:xlink="http://www.w3.org/1999/xlink" def="prod-xslt40-HexIntegerLiteral" xlink:type="simple">HexIntegerLiteral</nt>  |  <nt xmlns:xlink="http://www.w3.org/1999/xlink" def="prod-xslt40-BinaryIntegerLiteral" xlink:type="simple">BinaryIntegerLiteral</nt>  |  <nt xmlns:xlink="http://www.w3.org/1999/xlink" def="prod-xslt40-DecimalLiteral" xlink:type="simple">DecimalLiteral</nt>  |  <nt xmlns:xlink="http://www.w3.org/1999/xlink" def="prod-xslt40-DoubleLiteral" xlink:type="simple">DoubleLiteral</nt></rhs></prod><prod id="prod-xslt40-OccurrenceIndicator"><lhs>OccurrenceIndicator</lhs><rhs>"?"  |  "*"  |  "+"</rhs><com><loc xmlns:xlink="http://www.w3.org/1999/xlink" href="#parse-note-occurrence-indicators" xlink:type="simple" xlink:show="replace" xlink:actuate="onRequest">xgs: occurrence-indicators</loc></com></prod><prod id="prod-xslt40-OrExpr"><lhs>OrExpr</lhs><rhs><xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="XP40" ref="prod-xpath40-AndExpr" xlink:type="simple">AndExpr</xnt>  ("or"  <xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="XP40" ref="prod-xpath40-AndExpr" xlink:type="simple">AndExpr</xnt>)*</rhs></prod><prod id="prod-xslt40-OtherwiseExpr"><lhs>OtherwiseExpr</lhs><rhs><xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="XP40" ref="prod-xpath40-StringConcatExpr" xlink:type="simple">StringConcatExpr</xnt>  ("otherwise"  <xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="XP40" ref="prod-xpath40-StringConcatExpr" xlink:type="simple">StringConcatExpr</xnt>)*</rhs></prod><prod id="prod-xslt40-OuterFunctionName"><lhs>OuterFunctionName</lhs><rhs><xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="XP40" ref="prod-xpath40-EQName" xlink:type="simple">EQName</xnt></rhs></prod><prod id="prod-xslt40-ParamList"><lhs>ParamList</lhs><rhs>(<xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="XP40" ref="prod-xpath40-VarNameAndType" xlink:type="simple">VarNameAndType</xnt> ** ",")</rhs></prod><prod id="prod-xslt40-ParenthesizedExpr"><lhs>ParenthesizedExpr</lhs><rhs>"("  <xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="XP40" ref="prod-xpath40-Expr" xlink:type="simple">Expr</xnt>?  ")"</rhs></prod><prod id="prod-xslt40-ParenthesizedPattern"><lhs>ParenthesizedPattern</lhs><rhs>"("  <nt xmlns:xlink="http://www.w3.org/1999/xlink" def="prod-xslt40-Pattern" xlink:type="simple">Pattern</nt>  ")"</rhs></prod><prod id="prod-xslt40-PathExpr"><lhs>PathExpr</lhs><rhs><xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="XP40" ref="prod-xpath40-AbsolutePathExpr" xlink:type="simple">AbsolutePathExpr</xnt><br/>|  <xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="XP40" ref="prod-xpath40-RelativePathExpr" xlink:type="simple">RelativePathExpr</xnt></rhs><com><loc xmlns:xlink="http://www.w3.org/1999/xlink" href="#parse-note-leading-lone-slash" xlink:type="simple" xlink:show="replace" xlink:actuate="onRequest">xgs: leading-lone-slash</loc></com></prod><prod id="prod-xslt40-PathExprP"><lhs>PathExprP</lhs><rhs><nt xmlns:xlink="http://www.w3.org/1999/xlink" def="prod-xslt40-RootedPath" xlink:type="simple">RootedPath</nt><br/>|  ("/"  <nt xmlns:xlink="http://www.w3.org/1999/xlink" def="prod-xslt40-RelativePathExprP" xlink:type="simple">RelativePathExprP</nt>?)<br/>|  ("//"  <nt xmlns:xlink="http://www.w3.org/1999/xlink" def="prod-xslt40-RelativePathExprP" xlink:type="simple">RelativePathExprP</nt>)<br/>|  <nt xmlns:xlink="http://www.w3.org/1999/xlink" def="prod-xslt40-RelativePathExprP" xlink:type="simple">RelativePathExprP</nt></rhs><com><loc xmlns:xlink="http://www.w3.org/1999/xlink" href="#parse-note-leading-lone-slash" xlink:type="simple" xlink:show="replace" xlink:actuate="onRequest">xgs: leading-lone-slash</loc></com></prod><prod id="prod-xslt40-Pattern"><lhs>Pattern</lhs><rhs><nt xmlns:xlink="http://www.w3.org/1999/xlink" def="prod-xslt40-PredicatePattern" xlink:type="simple">PredicatePattern</nt>  |  <nt xmlns:xlink="http://www.w3.org/1999/xlink" def="prod-xslt40-TypePattern" xlink:type="simple">TypePattern</nt>  |  <nt xmlns:xlink="http://www.w3.org/1999/xlink" def="prod-xslt40-GNodePattern" xlink:type="simple">GNodePattern</nt></rhs></prod><prod id="prod-xslt40-PipelineExpr"><lhs>PipelineExpr</lhs><rhs><xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="XP40" ref="prod-xpath40-ArrowExpr" xlink:type="simple">ArrowExpr</xnt>  ("-&gt;"  <xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="XP40" ref="prod-xpath40-ArrowExpr" xlink:type="simple">ArrowExpr</xnt>)*</rhs></prod><prod id="prod-xslt40-PositionalArgumentList"><lhs>PositionalArgumentList</lhs><rhs>"("  <xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="XP40" ref="prod-xpath40-PositionalArguments" xlink:type="simple">PositionalArguments</xnt>?  ")"</rhs></prod><prod id="prod-xslt40-PositionalArguments"><lhs>PositionalArguments</lhs><rhs>(<xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="XP40" ref="prod-xpath40-Argument" xlink:type="simple">Argument</xnt> ++ ",")</rhs></prod><prod id="prod-xslt40-PositionalVar"><lhs>PositionalVar</lhs><rhs>"at"  <xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="XP40" ref="prod-xpath40-VarName" xlink:type="simple">VarName</xnt></rhs></prod><prod id="prod-xslt40-PostfixExpr"><lhs>PostfixExpr</lhs><rhs><xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="XP40" ref="prod-xpath40-PrimaryExpr" xlink:type="simple">PrimaryExpr</xnt>  |  <xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="XP40" ref="prod-xpath40-FilterExpr" xlink:type="simple">FilterExpr</xnt>  |  <xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="XP40" ref="prod-xpath40-DynamicFunctionCall" xlink:type="simple">DynamicFunctionCall</xnt>  |  <xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="XP40" ref="prod-xpath40-LookupExpr" xlink:type="simple">LookupExpr</xnt>  |  <xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="XP40" ref="prod-xpath40-MethodCall" xlink:type="simple">MethodCall</xnt>  |  <xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="XP40" ref="prod-xpath40-FilterExprAM" xlink:type="simple">FilterExprAM</xnt></rhs></prod><prod id="prod-xslt40-PostfixExprP"><lhs>PostfixExprP</lhs><rhs>(<nt xmlns:xlink="http://www.w3.org/1999/xlink" def="prod-xslt40-FunctionCallP" xlink:type="simple">FunctionCallP</nt>  |  <nt xmlns:xlink="http://www.w3.org/1999/xlink" def="prod-xslt40-ParenthesizedPattern" xlink:type="simple">ParenthesizedPattern</nt>)  <xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="XP40" ref="prod-xpath40-Predicate" xlink:type="simple">Predicate</xnt>*</rhs></prod><prod id="prod-xslt40-Predicate"><lhs>Predicate</lhs><rhs>"["  <xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="XP40" ref="prod-xpath40-Expr" xlink:type="simple">Expr</xnt>  "]"</rhs></prod><prod id="prod-xslt40-PredicatePattern"><lhs>PredicatePattern</lhs><rhs>"."  <xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="XP40" ref="prod-xpath40-Predicate" xlink:type="simple">Predicate</xnt>*</rhs></prod><prod id="prod-xslt40-PrimaryExpr"><lhs>PrimaryExpr</lhs><rhs><xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="XP40" ref="prod-xpath40-Literal" xlink:type="simple">Literal</xnt><br/>|  <xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="XP40" ref="prod-xpath40-VarRef" xlink:type="simple">VarRef</xnt><br/>|  <xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="XP40" ref="prod-xpath40-ParenthesizedExpr" xlink:type="simple">ParenthesizedExpr</xnt><br/>|  <xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="XP40" ref="prod-xpath40-ContextValueRef" xlink:type="simple">ContextValueRef</xnt><br/>|  <xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="XP40" ref="prod-xpath40-FunctionCall" xlink:type="simple">FunctionCall</xnt><br/>|  <xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="XP40" ref="prod-xpath40-FunctionItemExpr" xlink:type="simple">FunctionItemExpr</xnt><br/>|  <xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="XP40" ref="prod-xpath40-MapConstructor" xlink:type="simple">MapConstructor</xnt><br/>|  <xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="XP40" ref="prod-xpath40-ArrayConstructor" xlink:type="simple">ArrayConstructor</xnt><br/>|  <xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="XP40" ref="prod-xpath40-StringTemplate" xlink:type="simple">StringTemplate</xnt><br/>|  <xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="XP40" ref="prod-xpath40-UnaryLookup" xlink:type="simple">UnaryLookup</xnt></rhs></prod><prod id="prod-xslt40-ProcessingInstructionNodeType"><lhs>ProcessingInstructionNodeType</lhs><rhs>"processing-instruction"  "("  (<xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="XP40" ref="prod-xpath40-NCName" xlink:type="simple">NCName</xnt>  |  <xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="XP40" ref="prod-xpath40-StringLiteral" xlink:type="simple">StringLiteral</xnt>)?  ")"</rhs></prod><prod id="prod-xslt40-QNameLiteral"><lhs>QNameLiteral</lhs><rhs>"#"  <xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="XP40" ref="prod-xpath40-EQName" xlink:type="simple">EQName</xnt></rhs></prod><prod id="prod-xslt40-QuantifiedExpr"><lhs>QuantifiedExpr</lhs><rhs>("some"  |  "every")  (<xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="XP40" ref="prod-xpath40-QuantifierBinding" xlink:type="simple">QuantifierBinding</xnt> ++ ",")  "satisfies"  <xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="XP40" ref="prod-xpath40-ExprSingle" xlink:type="simple">ExprSingle</xnt></rhs></prod><prod id="prod-xslt40-QuantifierBinding"><lhs>QuantifierBinding</lhs><rhs><xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="XP40" ref="prod-xpath40-VarNameAndType" xlink:type="simple">VarNameAndType</xnt>  "in"  <xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="XP40" ref="prod-xpath40-ExprSingle" xlink:type="simple">ExprSingle</xnt></rhs></prod><prod id="prod-xslt40-RangeExpr"><lhs>RangeExpr</lhs><rhs><xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="XP40" ref="prod-xpath40-AdditiveExpr" xlink:type="simple">AdditiveExpr</xnt>  ("to"  <xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="XP40" ref="prod-xpath40-AdditiveExpr" xlink:type="simple">AdditiveExpr</xnt>)?</rhs></prod><prod id="prod-xslt40-RecordType"><lhs>RecordType</lhs><rhs>"record"  "("  (<xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="XP40" ref="prod-xpath40-FieldDeclaration" xlink:type="simple">FieldDeclaration</xnt> ** ",")  ")"</rhs></prod><prod id="prod-xslt40-RegularItemType"><lhs>RegularItemType</lhs><rhs><xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="XP40" ref="prod-xpath40-AnyItemType" xlink:type="simple">AnyItemType</xnt>  |  <xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="XP40" ref="prod-xpath40-XNodeType" xlink:type="simple">XNodeType</xnt>  |  <xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="XP40" ref="prod-xpath40-GNodeType" xlink:type="simple">GNodeType</xnt>  |  <xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="XP40" ref="prod-xpath40-JNodeType" xlink:type="simple">JNodeType</xnt>  |  <xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="XP40" ref="prod-xpath40-MapType" xlink:type="simple">MapType</xnt>  |  <xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="XP40" ref="prod-xpath40-ArrayType" xlink:type="simple">ArrayType</xnt>  |  <xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="XP40" ref="prod-xpath40-RecordType" xlink:type="simple">RecordType</xnt>  |  <xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="XP40" ref="prod-xpath40-EnumerationType" xlink:type="simple">EnumerationType</xnt></rhs></prod><prod id="prod-xslt40-RelativePathExpr"><lhs>RelativePathExpr</lhs><rhs><xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="XP40" ref="prod-xpath40-StepExpr" xlink:type="simple">StepExpr</xnt>  (("/"  |  "//")  <xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="XP40" ref="prod-xpath40-StepExpr" xlink:type="simple">StepExpr</xnt>)*</rhs></prod><prod id="prod-xslt40-RelativePathExprP"><lhs>RelativePathExprP</lhs><rhs><nt xmlns:xlink="http://www.w3.org/1999/xlink" def="prod-xslt40-StepExprP" xlink:type="simple">StepExprP</nt>  (("/"  |  "//")  <nt xmlns:xlink="http://www.w3.org/1999/xlink" def="prod-xslt40-StepExprP" xlink:type="simple">StepExprP</nt>)*</rhs></prod><prod id="prod-xslt40-RestrictedDynamicCall"><lhs>RestrictedDynamicCall</lhs><rhs>(<xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="XP40" ref="prod-xpath40-VarRef" xlink:type="simple">VarRef</xnt>  |  <xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="XP40" ref="prod-xpath40-ParenthesizedExpr" xlink:type="simple">ParenthesizedExpr</xnt>  |  <xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="XP40" ref="prod-xpath40-FunctionItemExpr" xlink:type="simple">FunctionItemExpr</xnt>  |  <xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="XP40" ref="prod-xpath40-MapConstructor" xlink:type="simple">MapConstructor</xnt>  |  <xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="XP40" ref="prod-xpath40-ArrayConstructor" xlink:type="simple">ArrayConstructor</xnt>)  <xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="XP40" ref="prod-xpath40-PositionalArgumentList" xlink:type="simple">PositionalArgumentList</xnt></rhs></prod><prod id="prod-xslt40-RootedPath"><lhs>RootedPath</lhs><rhs><xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="XP40" ref="prod-xpath40-VarRef" xlink:type="simple">VarRef</xnt>  <xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="XP40" ref="prod-xpath40-Predicate" xlink:type="simple">Predicate</xnt>*  (("/"  |  "//")  <nt xmlns:xlink="http://www.w3.org/1999/xlink" def="prod-xslt40-RelativePathExprP" xlink:type="simple">RelativePathExprP</nt>)?</rhs></prod><prod id="prod-xslt40-SchemaAttributeNodeType"><lhs>SchemaAttributeNodeType</lhs><rhs>"schema-attribute"  "("  <xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="XP40" ref="prod-xpath40-AttributeName" xlink:type="simple">AttributeName</xnt>  ")"</rhs></prod><prod id="prod-xslt40-SchemaElementNodeType"><lhs>SchemaElementNodeType</lhs><rhs>"schema-element"  "("  <xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="XP40" ref="prod-xpath40-ElementName" xlink:type="simple">ElementName</xnt>  ")"</rhs></prod><prod id="prod-xslt40-Selector"><lhs>Selector</lhs><rhs><xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="XP40" ref="prod-xpath40-EQName" xlink:type="simple">EQName</xnt>  |  <xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="XP40" ref="prod-xpath40-Wildcard" xlink:type="simple">Wildcard</xnt>  |  ("get"  "("  <xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="XP40" ref="prod-xpath40-ExprSingle" xlink:type="simple">ExprSingle</xnt>  ")")</rhs></prod><prod id="prod-xslt40-SequenceArrowTarget"><lhs>SequenceArrowTarget</lhs><rhs>"=&gt;"  <xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="XP40" ref="prod-xpath40-ArrowTarget" xlink:type="simple">ArrowTarget</xnt></rhs></prod><prod id="prod-xslt40-SequenceType"><lhs>SequenceType</lhs><rhs>("empty-sequence"  "("  ")")<br/>|  (<xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="XP40" ref="prod-xpath40-ItemType" xlink:type="simple">ItemType</xnt>  <xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="XP40" ref="prod-xpath40-OccurrenceIndicator" xlink:type="simple">OccurrenceIndicator</xnt>?)</rhs></prod><prod id="prod-xslt40-SimpleMapExpr"><lhs>SimpleMapExpr</lhs><rhs><xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="XP40" ref="prod-xpath40-PathExpr" xlink:type="simple">PathExpr</xnt>  ("!"  <xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="XP40" ref="prod-xpath40-PathExpr" xlink:type="simple">PathExpr</xnt>)*</rhs></prod><prod id="prod-xslt40-SimpleNodeTest"><lhs>SimpleNodeTest</lhs><rhs><xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="XP40" ref="prod-xpath40-TypeTest" xlink:type="simple">TypeTest</xnt>  |  <xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="XP40" ref="prod-xpath40-Selector" xlink:type="simple">Selector</xnt></rhs></prod><prod id="prod-xslt40-SquareArrayConstructor"><lhs>SquareArrayConstructor</lhs><rhs>"["  (<xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="XP40" ref="prod-xpath40-ExprSingle" xlink:type="simple">ExprSingle</xnt> ** ",")  "]"</rhs></prod><prod id="prod-xslt40-StepExpr"><lhs>StepExpr</lhs><rhs><xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="XP40" ref="prod-xpath40-PostfixExpr" xlink:type="simple">PostfixExpr</xnt>  |  <xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="XP40" ref="prod-xpath40-AxisStep" xlink:type="simple">AxisStep</xnt></rhs></prod><prod id="prod-xslt40-StepExprP"><lhs>StepExprP</lhs><rhs><nt xmlns:xlink="http://www.w3.org/1999/xlink" def="prod-xslt40-PostfixExprP" xlink:type="simple">PostfixExprP</nt>  |  <nt xmlns:xlink="http://www.w3.org/1999/xlink" def="prod-xslt40-AxisStepP" xlink:type="simple">AxisStepP</nt></rhs></prod><prod id="prod-xslt40-StringConcatExpr"><lhs>StringConcatExpr</lhs><rhs><xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="XP40" ref="prod-xpath40-RangeExpr" xlink:type="simple">RangeExpr</xnt>  ("||"  <xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="XP40" ref="prod-xpath40-RangeExpr" xlink:type="simple">RangeExpr</xnt>)*</rhs></prod><prod id="prod-xslt40-StringTemplate"><lhs>StringTemplate</lhs><rhs>"`"  (<xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="XP40" ref="prod-xpath40-StringTemplateFixedPart" xlink:type="simple">StringTemplateFixedPart</xnt>  |  <xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="XP40" ref="prod-xpath40-StringTemplateVariablePart" xlink:type="simple">StringTemplateVariablePart</xnt>)*  "`"</rhs><com><loc xmlns:xlink="http://www.w3.org/1999/xlink" href="#ws-explicit" xlink:type="simple" xlink:show="replace" xlink:actuate="onRequest">ws: explicit</loc></com></prod><prod id="prod-xslt40-StringTemplateFixedPart"><lhs>StringTemplateFixedPart</lhs><rhs>((<nt xmlns:xlink="http://www.w3.org/1999/xlink" def="prod-xslt40-Char" xlink:type="simple">Char</nt> - ('{' | '}' | '`'))  |  "{{"  |  "}}"  |  "``")+</rhs><com><loc xmlns:xlink="http://www.w3.org/1999/xlink" href="#ws-explicit" xlink:type="simple" xlink:show="replace" xlink:actuate="onRequest">ws: explicit</loc></com></prod><prod id="prod-xslt40-StringTemplateVariablePart"><lhs>StringTemplateVariablePart</lhs><rhs><xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="XP40" ref="prod-xpath40-EnclosedExpr" xlink:type="simple">EnclosedExpr</xnt></rhs></prod><prod id="prod-xslt40-TextNodeType"><lhs>TextNodeType</lhs><rhs>"text"  "("  ")"</rhs></prod><prod id="prod-xslt40-TreatExpr"><lhs>TreatExpr</lhs><rhs><xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="XP40" ref="prod-xpath40-CastableExpr" xlink:type="simple">CastableExpr</xnt>  ("treat"  "as"  <xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="XP40" ref="prod-xpath40-SequenceType" xlink:type="simple">SequenceType</xnt>)?</rhs></prod><prod id="prod-xslt40-TypedArrayType"><lhs>TypedArrayType</lhs><rhs>"array"  "("  <xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="XP40" ref="prod-xpath40-SequenceType" xlink:type="simple">SequenceType</xnt>  ")"</rhs></prod><prod id="prod-xslt40-TypeDeclaration"><lhs>TypeDeclaration</lhs><rhs>"as"  <xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="XP40" ref="prod-xpath40-SequenceType" xlink:type="simple">SequenceType</xnt></rhs></prod><prod id="prod-xslt40-TypedFunctionParam"><lhs>TypedFunctionParam</lhs><rhs>("$"  <xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="XP40" ref="prod-xpath40-EQName" xlink:type="simple">EQName</xnt>  "as")?  <xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="XP40" ref="prod-xpath40-SequenceType" xlink:type="simple">SequenceType</xnt></rhs></prod><prod id="prod-xslt40-TypedFunctionType"><lhs>TypedFunctionType</lhs><rhs>("function"  |  "fn")  "("  (<xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="XP40" ref="prod-xpath40-TypedFunctionParam" xlink:type="simple">TypedFunctionParam</xnt> ** ",")  ")"  "as"  <xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="XP40" ref="prod-xpath40-SequenceType" xlink:type="simple">SequenceType</xnt></rhs></prod><prod id="prod-xslt40-TypedMapType"><lhs>TypedMapType</lhs><rhs>"map"  "("  <xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="XP40" ref="prod-xpath40-ItemType" xlink:type="simple">ItemType</xnt>  ","  <xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="XP40" ref="prod-xpath40-SequenceType" xlink:type="simple">SequenceType</xnt>  ")"</rhs></prod><prod id="prod-xslt40-TypeName"><lhs>TypeName</lhs><rhs><xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="XP40" ref="prod-xpath40-EQName" xlink:type="simple">EQName</xnt></rhs></prod><prod id="prod-xslt40-TypePattern"><lhs>TypePattern</lhs><rhs>"~"  <xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="XP40" ref="prod-xpath40-ItemType" xlink:type="simple">ItemType</xnt>  <xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="XP40" ref="prod-xpath40-Predicate" xlink:type="simple">Predicate</xnt>*</rhs></prod><prod id="prod-xslt40-TypeTest"><lhs>TypeTest</lhs><rhs><xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="XP40" ref="prod-xpath40-GNodeType" xlink:type="simple">GNodeType</xnt>  |  <xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="XP40" ref="prod-xpath40-XNodeType" xlink:type="simple">XNodeType</xnt>  |  <xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="XP40" ref="prod-xpath40-JNodeType" xlink:type="simple">JNodeType</xnt></rhs></prod><prod id="prod-xslt40-UnaryExpr"><lhs>UnaryExpr</lhs><rhs>("-"  |  "+")*  <xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="XP40" ref="prod-xpath40-ValueExpr" xlink:type="simple">ValueExpr</xnt></rhs></prod><prod id="prod-xslt40-UnaryLookup"><lhs>UnaryLookup</lhs><rhs><xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="XP40" ref="prod-xpath40-Lookup" xlink:type="simple">Lookup</xnt></rhs></prod><prod id="prod-xslt40-UnbracedActions"><lhs>UnbracedActions</lhs><rhs>"then"  <xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="XP40" ref="prod-xpath40-ExprSingle" xlink:type="simple">ExprSingle</xnt>  "else"  <xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="XP40" ref="prod-xpath40-ExprSingle" xlink:type="simple">ExprSingle</xnt></rhs></prod><prod id="prod-xslt40-UnionExpr"><lhs>UnionExpr</lhs><rhs><xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="XP40" ref="prod-xpath40-IntersectExceptExpr" xlink:type="simple">IntersectExceptExpr</xnt>  (("union"  |  "|")  <xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="XP40" ref="prod-xpath40-IntersectExceptExpr" xlink:type="simple">IntersectExceptExpr</xnt>)*</rhs></prod><prod id="prod-xslt40-UnionExprP"><lhs>UnionExprP</lhs><rhs><nt xmlns:xlink="http://www.w3.org/1999/xlink" def="prod-xslt40-IntersectExceptExprP" xlink:type="simple">IntersectExceptExprP</nt>  (("union"  |  "|")  <nt xmlns:xlink="http://www.w3.org/1999/xlink" def="prod-xslt40-IntersectExceptExprP" xlink:type="simple">IntersectExceptExprP</nt>)*</rhs></prod><prod id="prod-xslt40-UnionNodeTest"><lhs>UnionNodeTest</lhs><rhs>"("  (<xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="XP40" ref="prod-xpath40-SimpleNodeTest" xlink:type="simple">SimpleNodeTest</xnt> ++ "|")  ")"</rhs></prod><prod id="prod-xslt40-ValueComp"><lhs>ValueComp</lhs><rhs>"eq"  |  "ne"  |  "lt"  |  "le"  |  "gt"  |  "ge"</rhs></prod><prod id="prod-xslt40-ValueExpr"><lhs>ValueExpr</lhs><rhs><xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="XP40" ref="prod-xpath40-SimpleMapExpr" xlink:type="simple">SimpleMapExpr</xnt></rhs></prod><prod id="prod-xslt40-VarName"><lhs>VarName</lhs><rhs>"$"  <xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="XP40" ref="prod-xpath40-EQName" xlink:type="simple">EQName</xnt></rhs></prod><prod id="prod-xslt40-VarNameAndType"><lhs>VarNameAndType</lhs><rhs>"$"  <xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="XP40" ref="prod-xpath40-EQName" xlink:type="simple">EQName</xnt>  <xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="XP40" ref="prod-xpath40-TypeDeclaration" xlink:type="simple">TypeDeclaration</xnt>?</rhs></prod><prod id="prod-xslt40-VarRef"><lhs>VarRef</lhs><rhs>"$"  <xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="XP40" ref="prod-xpath40-EQName" xlink:type="simple">EQName</xnt></rhs></prod><prod id="prod-xslt40-Wildcard"><lhs>Wildcard</lhs><rhs>"*"<br/>|  (<nt xmlns:xlink="http://www.w3.org/1999/xlink" def="prod-xslt40-NCName" xlink:type="simple">NCName</nt>  ":"  "*")<br/>|  ("*"  ":"  <nt xmlns:xlink="http://www.w3.org/1999/xlink" def="prod-xslt40-NCName" xlink:type="simple">NCName</nt>)<br/>|  (<nt xmlns:xlink="http://www.w3.org/1999/xlink" def="prod-xslt40-BracedURILiteral" xlink:type="simple">BracedURILiteral</nt>  "*")</rhs><com><loc xmlns:xlink="http://www.w3.org/1999/xlink" href="#ws-explicit" xlink:type="simple" xlink:show="replace" xlink:actuate="onRequest">ws: explicit</loc></com></prod><prod id="prod-xslt40-XNodeType"><lhs>XNodeType</lhs><rhs><xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="XP40" ref="prod-xpath40-DocumentNodeType" xlink:type="simple">DocumentNodeType</xnt><br/>|  <xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="XP40" ref="prod-xpath40-ElementNodeType" xlink:type="simple">ElementNodeType</xnt><br/>|  <xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="XP40" ref="prod-xpath40-AttributeNodeType" xlink:type="simple">AttributeNodeType</xnt><br/>|  <xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="XP40" ref="prod-xpath40-SchemaElementNodeType" xlink:type="simple">SchemaElementNodeType</xnt><br/>|  <xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="XP40" ref="prod-xpath40-SchemaAttributeNodeType" xlink:type="simple">SchemaAttributeNodeType</xnt><br/>|  <xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="XP40" ref="prod-xpath40-ProcessingInstructionNodeType" xlink:type="simple">ProcessingInstructionNodeType</xnt><br/>|  <xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="XP40" ref="prod-xpath40-CommentNodeType" xlink:type="simple">CommentNodeType</xnt><br/>|  <xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="XP40" ref="prod-xpath40-TextNodeType" xlink:type="simple">TextNodeType</xnt><br/>|  <xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="XP40" ref="prod-xpath40-NamespaceNodeType" xlink:type="simple">NamespaceNodeType</xnt><br/>|  <xnt xmlns:xlink="http://www.w3.org/1999/xlink" spec="XP40" ref="prod-xpath40-AnyXNodeType" xlink:type="simple">AnyXNodeType</xnt></rhs></prod></prodgroup></scrap></div2><div2 id="terminal-symbols"><head>Terminal Symbols</head><scrap headstyle="show"><head/><prod id="prod-xslt40-IntegerLiteral"><lhs>IntegerLiteral</lhs><rhs><nt xmlns:xlink="http://www.w3.org/1999/xlink" def="prod-xslt40-Digits" xlink:type="simple">Digits</nt></rhs><com><loc xmlns:xlink="http://www.w3.org/1999/xlink" href="#ws-explicit" xlink:type="simple" xlink:show="replace" xlink:actuate="onRequest">ws: explicit</loc></com></prod><prod id="prod-xslt40-HexIntegerLiteral"><lhs>HexIntegerLiteral</lhs><rhs>"0x"  <nt xmlns:xlink="http://www.w3.org/1999/xlink" def="prod-xslt40-HexDigits" xlink:type="simple">HexDigits</nt></rhs><com><loc xmlns:xlink="http://www.w3.org/1999/xlink" href="#ws-explicit" xlink:type="simple" xlink:show="replace" xlink:actuate="onRequest">ws: explicit</loc></com></prod><prod id="prod-xslt40-BinaryIntegerLiteral"><lhs>BinaryIntegerLiteral</lhs><rhs>"0b"  <nt xmlns:xlink="http://www.w3.org/1999/xlink" def="prod-xslt40-BinaryDigits" xlink:type="simple">BinaryDigits</nt></rhs><com><loc xmlns:xlink="http://www.w3.org/1999/xlink" href="#ws-explicit" xlink:type="simple" xlink:show="replace" xlink:actuate="onRequest">ws: explicit</loc></com></prod><prod id="prod-xslt40-DecimalLiteral"><lhs>DecimalLiteral</lhs><rhs>("."  <nt xmlns:xlink="http://www.w3.org/1999/xlink" def="prod-xslt40-Digits" xlink:type="simple">Digits</nt>)  |  (<nt xmlns:xlink="http://www.w3.org/1999/xlink" def="prod-xslt40-Digits" xlink:type="simple">Digits</nt>  "."  <nt xmlns:xlink="http://www.w3.org/1999/xlink" def="prod-xslt40-Digits" xlink:type="simple">Digits</nt>?)</rhs><com><loc xmlns:xlink="http://www.w3.org/1999/xlink" href="#ws-explicit" xlink:type="simple" xlink:show="replace" xlink:actuate="onRequest">ws: explicit</loc></com></prod><prod id="prod-xslt40-DoubleLiteral"><lhs>DoubleLiteral</lhs><rhs>(("."  <nt xmlns:xlink="http://www.w3.org/1999/xlink" def="prod-xslt40-Digits" xlink:type="simple">Digits</nt>)  |  (<nt xmlns:xlink="http://www.w3.org/1999/xlink" def="prod-xslt40-Digits" xlink:type="simple">Digits</nt>  ("."  <nt xmlns:xlink="http://www.w3.org/1999/xlink" def="prod-xslt40-Digits" xlink:type="simple">Digits</nt>?)?))  [eE]  [+-]?  <nt xmlns:xlink="http://www.w3.org/1999/xlink" def="prod-xslt40-Digits" xlink:type="simple">Digits</nt></rhs><com><loc xmlns:xlink="http://www.w3.org/1999/xlink" href="#ws-explicit" xlink:type="simple" xlink:show="replace" xlink:actuate="onRequest">ws: explicit</loc></com></prod><prod id="prod-xslt40-StringLiteral"><lhs>StringLiteral</lhs><rhs><nt xmlns:xlink="http://www.w3.org/1999/xlink" def="prod-xslt40-AposStringLiteral" xlink:type="simple">AposStringLiteral</nt>  |  <nt xmlns:xlink="http://www.w3.org/1999/xlink" def="prod-xslt40-QuotStringLiteral" xlink:type="simple">QuotStringLiteral</nt></rhs><com><loc xmlns:xlink="http://www.w3.org/1999/xlink" href="#ws-explicit" xlink:type="simple" xlink:show="replace" xlink:actuate="onRequest">ws: explicit</loc></com></prod><prod id="prod-xslt40-AposStringLiteral"><lhs>AposStringLiteral</lhs><rhs>"'"  (<nt xmlns:xlink="http://www.w3.org/1999/xlink" def="prod-xslt40-EscapeApos" xlink:type="simple">EscapeApos</nt>  |  [^'])*  "'"</rhs><com><loc xmlns:xlink="http://www.w3.org/1999/xlink" href="#ws-explicit" xlink:type="simple" xlink:show="replace" xlink:actuate="onRequest">ws: explicit</loc></com></prod><prod id="prod-xslt40-QuotStringLiteral"><lhs>QuotStringLiteral</lhs><rhs>'"'  (<nt xmlns:xlink="http://www.w3.org/1999/xlink" def="prod-xslt40-EscapeQuot" xlink:type="simple">EscapeQuot</nt>  |  [^"])*  '"'</rhs><com><loc xmlns:xlink="http://www.w3.org/1999/xlink" href="#ws-explicit" xlink:type="simple" xlink:show="replace" xlink:actuate="onRequest">ws: explicit</loc></com></prod><prod id="prod-xslt40-URIQualifiedName"><lhs>URIQualifiedName</lhs><rhs><nt xmlns:xlink="http://www.w3.org/1999/xlink" def="prod-xslt40-BracedURILiteral" xlink:type="simple">BracedURILiteral</nt>  (<nt xmlns:xlink="http://www.w3.org/1999/xlink" def="prod-xslt40-NCName" xlink:type="simple">NCName</nt>  ":")?  <nt xmlns:xlink="http://www.w3.org/1999/xlink" def="prod-xslt40-NCName" xlink:type="simple">NCName</nt></rhs><com><loc xmlns:xlink="http://www.w3.org/1999/xlink" href="#ws-explicit" xlink:type="simple" xlink:show="replace" xlink:actuate="onRequest">ws: explicit</loc></com></prod><prod id="prod-xslt40-BracedURILiteral"><lhs>BracedURILiteral</lhs><rhs>"Q"  "{"  [^{}]*  "}"</rhs><com><loc xmlns:xlink="http://www.w3.org/1999/xlink" href="#ws-explicit" xlink:type="simple" xlink:show="replace" xlink:actuate="onRequest">ws: explicit</loc></com></prod><prod id="prod-xslt40-EscapeQuot"><lhs>EscapeQuot</lhs><rhs>'""'</rhs><com><loc xmlns:xlink="http://www.w3.org/1999/xlink" href="#ws-explicit" xlink:type="simple" xlink:show="replace" xlink:actuate="onRequest">ws: explicit</loc></com></prod><prod id="prod-xslt40-EscapeApos"><lhs>EscapeApos</lhs><rhs>"''"</rhs><com><loc xmlns:xlink="http://www.w3.org/1999/xlink" href="#ws-explicit" xlink:type="simple" xlink:show="replace" xlink:actuate="onRequest">ws: explicit</loc></com></prod><prod id="prod-xslt40-Comment"><lhs>Comment</lhs><rhs>"(:"  (<nt xmlns:xlink="http://www.w3.org/1999/xlink" def="prod-xslt40-CommentContents" xlink:type="simple">CommentContents</nt>  |  <nt xmlns:xlink="http://www.w3.org/1999/xlink" def="prod-xslt40-Comment" xlink:type="simple">Comment</nt>)*  ":)"</rhs><com><loc xmlns:xlink="http://www.w3.org/1999/xlink" href="#ws-explicit" xlink:type="simple" xlink:show="replace" xlink:actuate="onRequest">ws: explicit</loc></com><com><loc xmlns:xlink="http://www.w3.org/1999/xlink" href="#parse-note-comments" xlink:type="simple" xlink:show="replace" xlink:actuate="onRequest">gn: comments</loc></com></prod><prod id="prod-xslt40-QName"><lhs>QName</lhs><rhs><xnt xmlns:xlink="http://www.w3.org/1999/xlink" ref="NT-QName" spec="Names" xlink:type="simple">[http://www.w3.org/TR/REC-xml-names/#NT-QName]</xnt></rhs><com><loc xmlns:xlink="http://www.w3.org/1999/xlink" href="#parse-note-xml-version" xlink:type="simple" xlink:show="replace" xlink:actuate="onRequest">xgs: xml-version</loc></com></prod><prod id="prod-xslt40-NCName"><lhs>NCName</lhs><rhs><xnt xmlns:xlink="http://www.w3.org/1999/xlink" ref="NT-NCName" spec="Names" xlink:type="simple">[http://www.w3.org/TR/REC-xml-names/#NT-NCName]</xnt></rhs><com><loc xmlns:xlink="http://www.w3.org/1999/xlink" href="#parse-note-xml-version" xlink:type="simple" xlink:show="replace" xlink:actuate="onRequest">xgs: xml-version</loc></com></prod><prod id="prod-xslt40-Char"><lhs>Char</lhs><rhs><xnt xmlns:xlink="http://www.w3.org/1999/xlink" ref="NT-Char" spec="XML" xlink:type="simple">[http://www.w3.org/TR/REC-xml#NT-Char]</xnt></rhs><com><loc xmlns:xlink="http://www.w3.org/1999/xlink" href="#parse-note-xml-version" xlink:type="simple" xlink:show="replace" xlink:actuate="onRequest">xgs: xml-version</loc></com></prod></scrap><p>The following symbols represent portions of terminal symbols; they are not
              themselves terminal symbols referenced in the grammar.</p><scrap headstyle="show"><head/><prod id="prod-xslt40-Digits"><lhs>Digits</lhs><rhs><nt xmlns:xlink="http://www.w3.org/1999/xlink" def="prod-xslt40-DecDigit" xlink:type="simple">DecDigit</nt>  ((<nt xmlns:xlink="http://www.w3.org/1999/xlink" def="prod-xslt40-DecDigit" xlink:type="simple">DecDigit</nt>  |  "_")*  <nt xmlns:xlink="http://www.w3.org/1999/xlink" def="prod-xslt40-DecDigit" xlink:type="simple">DecDigit</nt>)?</rhs><com><loc xmlns:xlink="http://www.w3.org/1999/xlink" href="#ws-explicit" xlink:type="simple" xlink:show="replace" xlink:actuate="onRequest">ws: explicit</loc></com></prod><prod id="prod-xslt40-DecDigit"><lhs>DecDigit</lhs><rhs>[0-9]</rhs><com><loc xmlns:xlink="http://www.w3.org/1999/xlink" href="#ws-explicit" xlink:type="simple" xlink:show="replace" xlink:actuate="onRequest">ws: explicit</loc></com></prod><prod id="prod-xslt40-HexDigits"><lhs>HexDigits</lhs><rhs><nt xmlns:xlink="http://www.w3.org/1999/xlink" def="prod-xslt40-HexDigit" xlink:type="simple">HexDigit</nt>  ((<nt xmlns:xlink="http://www.w3.org/1999/xlink" def="prod-xslt40-HexDigit" xlink:type="simple">HexDigit</nt>  |  "_")*  <nt xmlns:xlink="http://www.w3.org/1999/xlink" def="prod-xslt40-HexDigit" xlink:type="simple">HexDigit</nt>)?</rhs><com><loc xmlns:xlink="http://www.w3.org/1999/xlink" href="#ws-explicit" xlink:type="simple" xlink:show="replace" xlink:actuate="onRequest">ws: explicit</loc></com></prod><prod id="prod-xslt40-HexDigit"><lhs>HexDigit</lhs><rhs>[0-9a-fA-F]</rhs><com><loc xmlns:xlink="http://www.w3.org/1999/xlink" href="#ws-explicit" xlink:type="simple" xlink:show="replace" xlink:actuate="onRequest">ws: explicit</loc></com></prod><prod id="prod-xslt40-BinaryDigits"><lhs>BinaryDigits</lhs><rhs><nt xmlns:xlink="http://www.w3.org/1999/xlink" def="prod-xslt40-BinaryDigit" xlink:type="simple">BinaryDigit</nt>  ((<nt xmlns:xlink="http://www.w3.org/1999/xlink" def="prod-xslt40-BinaryDigit" xlink:type="simple">BinaryDigit</nt>  |  "_")*  <nt xmlns:xlink="http://www.w3.org/1999/xlink" def="prod-xslt40-BinaryDigit" xlink:type="simple">BinaryDigit</nt>)?</rhs><com><loc xmlns:xlink="http://www.w3.org/1999/xlink" href="#ws-explicit" xlink:type="simple" xlink:show="replace" xlink:actuate="onRequest">ws: explicit</loc></com></prod><prod id="prod-xslt40-BinaryDigit"><lhs>BinaryDigit</lhs><rhs>[01]</rhs><com><loc xmlns:xlink="http://www.w3.org/1999/xlink" href="#ws-explicit" xlink:type="simple" xlink:show="replace" xlink:actuate="onRequest">ws: explicit</loc></com></prod><prod id="prod-xslt40-CommentContents"><lhs>CommentContents</lhs><rhs>(<nt xmlns:xlink="http://www.w3.org/1999/xlink" def="prod-xslt40-Char" xlink:type="simple">Char</nt>+ - (Char* ('(:' | ':)') Char*))</rhs><com><loc xmlns:xlink="http://www.w3.org/1999/xlink" href="#ws-explicit" xlink:type="simple" xlink:show="replace" xlink:actuate="onRequest">ws: explicit</loc></com></prod></scrap></div2></inform-div1><inform-div1 id="implementation-defined-features"><head>Checklist of Implementation-Defined Features</head><p>This appendix provides a summary of XSLT language features whose effect is explicitly
               <termref def="dt-implementation-defined"/>. The conformance rules (see <specref ref="conformance"/>) require vendors to provide documentation that explains how these
            choices have been exercised.</p><p>The implementation-defined features are grouped into categories for convenience.</p><div2 id="imp-def-api"><head>Application Programming Interfaces</head><p>This category covers interfaces for initiating a transformation, setting its
               parameters, initializing the static and dynamic context, and collecting the results.
               In general terms, it is implementation defined how input is passed to the processor
               and how it returns its output. This includes the interpretation of URIs used to refer
               to stylesheet packages and modules, source documents and collections, collations, and
               result documents.</p><p>More specifically:</p><?implementation-defined-features api?></div2><div2 id="imp-def-ext"><head>Vendor and User Extensions</head><p>This category covers extensions and extensibility: mechanisms for providing vendor or
               user extensions to the language without sacrificing interoperability.</p><p>In general terms, it is implementation-defined:</p><ulist><item><p>whether and under what circumstances the implementation recognizes any
                     extension functions, extension instructions, extension attributes, user-defined
                     data elements, additional types, additional serialization methods or
                     serialization parameters, or additional collations, and if so, what effect they
                     have. </p></item><item><p>whether, how, and under what circumstances the implementation allows users to
                     define extension functions, extension instructions, extension attributes,
                     user-defined data elements, additional types, additional serialization methods
                     or serialization parameters, or additional collations. If it does allow users
                     to do so, it must follow the rules given elsewhere in this specification. </p></item><item><p>what information is available to such extensions (for example, whether they
                     have access to the static and dynamic context.) </p></item><item><p>where such extensions are allowed, the extent to which the processor enforces
                     their correct behavior (for example, checking that strings returned by
                     extension functions contain only valid XML characters) </p></item></ulist><p>More specifically:</p><?implementation-defined-features ext?></div2><div2 id="imp-def-feature"><head>Localization</head><p>This specification, and the specifications that it refers to, include facilities for
               adapting the output of a transformation to meet local expectations: examples include
               the formatting of numbers and dates, and the choice of collations for sorted output.
               The general principles are:</p><ulist><item><p>The specification does not mandate any particular localizations that processors
                     must offer: for example, a conformant processor might choose to provide output
                     in Japanese only.</p></item><item><p>The specification provides fallback mechanisms so that if a particular
                     localization is requested and is not available, processing does not fail.</p></item></ulist><p>More specifically:</p><?implementation-defined-features local?></div2><div2 id="imp-def-optional-feature"><head>Optional Features</head><p>As well as the optional conformance features identified in <specref ref="conformance"/>, some specific features of the specification are defined to be optional.</p><?implementation-defined-features feature?></div2><div2 id="imp-def-dependencies"><head>Dependencies</head><p>When this specification refers normatively to other specifications, it generally
               gives implementations freedom to decide (within constraints) which version of the
               referenced specification should be used. Specifically:</p><?implementation-defined-features spec?></div2><div2 id="imp-def-defaults-and-limits"><head>Defaults and Limits</head><p>To accommodate variations in the way that the XSLT language is deployed, and the
               constraints of different processing environments, defaults for some options are
               implementation-defined. In addition, limits on the sizes of ranges of values
               permitted are in general implementation-defined:</p><?implementation-defined-features defaults?></div2><div2 id="imp-def-errors"><head>Detection and Reporting of Errors</head><p>Some aspects of error handling are implementation-defined:</p><?implementation-defined-features err?></div2></inform-div1><inform-div1 id="summary-list-of-functions"><head>Summary of Available Functions</head><div2 id="function-categories"><head>Function Classification</head><p>The functions available for use within an XSLT stylesheet can be classified based firstly,
            on where the function is defined, and secondly, on where it can be used. Specifically, the set
            of functions available is slightly different for :</p><ulist><item><p>Regular XPath expressions within the stylesheet, for example those appearing in
                  <code nobreak="false">select</code> or <code nobreak="false">test</code> attributes, or between braces in a <termref def="dt-text-value-template"/> (<var>R</var>)</p></item><item><p><termref def="dt-static-expression">Static expressions</termref> (<var>S</var>)</p></item><item><p>XPath expressions evaluated dynamically using <elcode>xsl:evaluate</elcode> (<var>D</var>)</p></item></ulist><p>The categories are listed in the following table:</p><table class="data" border="1" cellpadding="5" width="100%"><caption>Categories of Function, and their Availability</caption><thead><tr><th rowspan="1" colspan="1" align="left" valign="top">Category</th><th rowspan="1" colspan="1" align="left" valign="top">Defined where?</th><th rowspan="1" colspan="1" align="left" valign="top">Available where?</th><th rowspan="1" colspan="1" align="left" valign="top">Notes</th></tr></thead><tbody><tr><td rowspan="1" colspan="1" align="left" valign="top">User-defined functions</td><td rowspan="1" colspan="1" align="left" valign="top">Defined using <elcode>xsl:function</elcode> declarations in the stylesheet</td><td rowspan="1" colspan="1" align="left" valign="top"><var>R</var>, <var>D</var></td><td rowspan="1" colspan="1" align="left" valign="top">Functions are private by default; private functions can be referenced only
                     within the package where they are declared (and not in <elcode>xsl:evaluate</elcode>
                     expressions).</td></tr><tr><td rowspan="1" colspan="1" align="left" valign="top">Constructor functions for built-in types</td><td rowspan="1" colspan="1" align="left" valign="top"><xspecref spec="FO40" ref="constructor-functions"/></td><td rowspan="1" colspan="1" align="left" valign="top"><var>R</var>, <var>S</var>, <var>D</var></td><td rowspan="1" colspan="1" align="left" valign="top">These functions are all in the namespace conventionally associated with the
                     prefix <code nobreak="false">xs</code>. The semantics of a constructor function are identical
                     to the semantics of a <code nobreak="false">cast</code> expression.</td></tr><tr><td rowspan="1" colspan="1" align="left" valign="top">Constructor functions for user-defined types</td><td rowspan="1" colspan="1" align="left" valign="top"><xspecref spec="FO40" ref="constructor-functions"/></td><td rowspan="1" colspan="1" align="left" valign="top"><var>R</var>, <var>D</var> (if <code nobreak="false">schema-aware="yes"</code>)</td><td rowspan="1" colspan="1" align="left" valign="top">This category includes a function for every named user-defined simple
                     type in an imported schema; the function allows the conversion of strings
                     and certain other values to instances of the user-defined type.</td></tr><tr><td rowspan="1" colspan="1" align="left" valign="top">Functions defined in XPath 4.0</td><td rowspan="1" colspan="1" diff="add" at="2023-04-18" align="left" valign="top"><bibref ref="xpath-functions-40"/></td><td rowspan="1" colspan="1" align="left" valign="top"><var>R</var>, <var>S</var>, <var>D</var></td><td rowspan="1" colspan="1" align="left" valign="top">Includes functions in the namespaces conventionally
                     referred to be the prefixes <code nobreak="false">fn</code> and <code nobreak="false">math</code>.</td></tr><tr><td rowspan="1" colspan="1" align="left" valign="top">Functions defined in XSLT 4.0</td><td rowspan="1" colspan="1" align="left" valign="top">This specification</td><td rowspan="1" colspan="1" align="left" valign="top"><var>R</var>, <var>S</var> (see note), <var>D</var></td><td rowspan="1" colspan="1" align="left" valign="top">See <specref ref="XSLT-defined-functions"/>. There is an overlap with
                     the set of functions defined in XPath 4.0. The functions available in static expressions are:
                     <function>element-available</function>, <function>function-available</function>,
                     <function>type-available</function>, <function>available-system-properties</function>,
                     and <function>system-property</function>.</td></tr><tr><td rowspan="1" colspan="1" align="left" valign="top">Extension functions</td><td rowspan="1" colspan="1" align="left" valign="top">Implementation-defined: see <specref ref="extension-functions"/>.</td><td rowspan="1" colspan="1" align="left" valign="top"><var>R</var>, <var>S</var>, <var>D</var></td><td rowspan="1" colspan="1" align="left" valign="top">Availability is <termref def="dt-implementation-defined"/></td></tr></tbody></table></div2><div2 id="XSLT-defined-functions"><head>List of XSLT-defined functions</head><p>This appendix acts as an index of functions defined in this specification, to augment
            the set of functions defined in <bibref ref="xpath-functions-40"/>.</p><?xslt-defined-functions?></div2></inform-div1><inform-div1 id="schema-for-xslt"><head>Schemas for XSLT 4.0 Stylesheets</head><p>For convenience, schemas are provided for validation of XSLT 4.0 stylesheets
         using the XSD 1.1 and Relax NG schema languages. These are non-normative. Neither will detect
         every static error that might arise in an XSLT 4.0 stylesheet (for example, there is no attempt
         to check the syntax of XPath expressions); in addition, these schemas may reject some stylesheets
         that are valid, for example because they rely on <code nobreak="false">xsl:use-when</code> to eliminate sections of code
         that would otherwise be invalid.</p><div2 id="xsd11-schema-for-xslt"><head>XSD 1.1 Schema for XSLT Stylesheets</head><p>The following XSD 1.1 schema describes the structure of an XSLT stylesheet module. 
            There are some limitations:</p><ulist><item><p>It
            does not define all the constraints that apply to a stylesheet (for example, it does not
            attempt to define a datatype that precisely represents attributes containing XPath
               <termref def="dt-expression">expressions</termref>).</p></item><item><p>Stylesheets that use <termref def="dt-forwards-compatible-behavior"/> 
                  (an <code nobreak="false">[xsl:]version</code> attribute greater than
                  4.0), or that have sections excluded using <code nobreak="false">[xsl:]use-when</code>
                  attributes, are not required to conform to the schema.</p></item><item><p>The specification allows <elcode>xsl:note</elcode> elements to appear anywhere,
               but this schema is more restrictive.</p></item></ulist><p>A copy of this schema is available at <phrase diff="chg" at="2023-04-18"><loc xmlns:xlink="http://www.w3.org/1999/xlink" href="schema-for-xslt40.xsd" xlink:type="simple" xlink:show="replace" xlink:actuate="onRequest">schema-for-xslt40.xsd</loc></phrase>
         </p><note><p>The schema as written uses a lax wildcard to permit literal result elements to appear
               in a sequence constructor. This assumes that the schema used for validation will not
               contain any global element declaration that matches the element name of a literal
               result element. The content model for an element such as <code nobreak="false">invoice</code>
               appearing within a stylesheet is not the same as the content model for the same
               element appearing within a source document (it is likely to contain XSLT instructions
               rather than other elements from the target vocabulary): therefore, including such
               declarations in the schema used for validating a stylesheet is inappropriate.</p><p>The reason that lax validation rather than skip validation is used is so that XSLT
               instructions appearing as children of the literal result element will themselves be
               validated, using the appropriate global element declaration.</p></note><note><p>The schema uses XSD 1.1 assertions to represent some of the non-grammatical
               constraints appearing in the specification, for example the rule that some elements
               can have either a <code nobreak="false">select</code> attribute or a contained sequence constructor,
               but not both. At this stage, no attempt has been made to represent every such
               constraint, even where it is not difficult to express the rule. There will always be
               some constraints that cannot be expressed at all, for example those that require
               access to multiple stylesheet modules, those that require access to the in-scope
               schema components, and those that involve parsing a non-regular grammar, such as the
               grammar for patterns.</p><p>Apart from assertions, the only other significant use of XSD 1.1 features is that the
               elements <elcode>xsl:param</elcode> and <elcode>xsl:variable</elcode> are in two
               substitution groups: one containing all instructions, and one containing all
               declarations. If the schema needs to be converted to an XSD 1.0 schema, removing all
               assertions is straightforward; the other change needed is to remove
                  <elcode>xsl:param</elcode> and <elcode>xsl:variable</elcode> from the substitution
               group for declarations, and instead permit them explicitly as children of
                  <elcode>xsl:transform</elcode>.</p></note><?schema-for-xslt?></div2><div2 id="relax-ng-schema-for-xslt"><head>Relax-NG Schema for XSLT Stylesheets</head><p>The following Relax-NG schema may be used to validate XSLT 4.0 stylesheet modules. Similar
            caveats apply as for the XSD 1.1 version.</p><p>A copy of this schema is available at <loc xmlns:xlink="http://www.w3.org/1999/xlink" href="schema-for-xslt30.rnc" xlink:type="simple" xlink:show="replace" xlink:actuate="onRequest">schema-for-xslt30.rnc</loc>
            </p><p diff="add" at="2023-04-18">TODO: Needs updating for 4.0.</p><?rng-schema-for-xslt?></div2></inform-div1><inform-div1 id="changes-since-3.0" diff="add" at="2022-01-01"><head>Changes since XSLT 3.0</head><div2 id="xslt-changes-since-3.0"><head>Changes in this specification</head><?change-log?></div2><div2 id="xpath-changes-since-3.1"><head>Changes in Other Related Specifications</head><p>A number of changes affecting XSLT 4.0 have been made in other related
               specifications. Some of the more significant changes are as follows:</p><olist><item><p>A number of new kinds of ItemType are introduced, for example choice item types,
                  record types, and enumeration types.</p></item><item><p>The coercion rules (previously “function conversion rules”) allow atomic items
                  of primitive types to be supplied where a restricted type is required: for example
                  if the required type is <code nobreak="false">xs:positiveInteger</code>, it is now acceptable to supply the
                  value <code nobreak="false">42</code>.</p></item><item><p>XPath 4.0 introduces abbreviated syntax for <phrase diff="del" at="2023-01-17">conditional expressions
                  (<code nobreak="false">condition ?? action1 !! action2</code>) and for</phrase> inline functions
                  (for example <code nobreak="false">fn($x, $y) { $x + $y }</code>).</p></item></olist></div2></inform-div1><inform-div1 id="incompatibilities"><head>Incompatibilities with XSLT 3.0</head><p>This section lists all known incompatibilities with XSLT 3.0, that is, situations
               where a stylesheet that is error-free
            according to the XSLT 3.0 specification and where all elements have an effective version
            of <code nobreak="false">3.0</code> or less, will produce different results depending on whether it is
            run under an XSLT 3.0 processor or an XSLT 4.0 processor.</p><olist><item><p>The rules for comparing values in <elcode>xsl:for-each-group</elcode> now reference
               the rules for <function>distinct-values</function>, which have themselves changed
               <phrase diff="chg" at="2023-01-25">to be compatible with <function>fn:atomic-equal</function></phrase>. This change eliminates the intransitivity
               in the previous specification, which meant that in edge cases involving rounding of numeric values
               of different types, two items in different groups could compare equal. Any change in behavior
               is confined to this edge case.</p></item><item><p>The rules for matching nodes against patterns using the <code nobreak="false">intersect</code>
               and <code nobreak="false">except</code> operators have changed to deliver a more intuitive result.</p></item><item><p>The rules for comparing values in <termref def="dt-key">keys</termref> have changed,
               to align with the rules for maps. The changes affect edge cases involving rounding of numeric values
               of different types, and the comparison of date/time values with and without timezones.</p></item><item><p>In previous versions, a template rule whose match pattern was a union pattern
               and that had no explicity priority was treated as equivalent to a set of template
               rules, one for each alternative in the union, each potentially with different default
               priority. This rule has not been carried forward into XSLT 4.0: instead, the priority
               of the rule is taken as being the highest priority of any of the alternatives.</p></item><item><p>In XSLT 4.0, an <elcode>xsl:apply-imports</elcode> or <elcode>xsl:next-match</elcode>
               instruction automatically passes on the values of any non-tunnel parameters that were
               present in its own invocation. This means that the template rule invoked by 
               <elcode>xsl:apply-imports</elcode> or <elcode>xsl:next-match</elcode>, if it declares
               a default value for such a parameter, will take the implicitly-supplied value in 
               preference to the default value.</p><p>This change in the specification applies only if the <termref def="dt-effective-version"/>
               of the <elcode>xsl:apply-imports</elcode> or <elcode>xsl:next-match</elcode> is 4.0 or greater.
               This means that 3.0 behavior can be retained by adding the attribute <code nobreak="false">version="3.0"</code>
               to the instruction, or to some ancestor element (for example, the <elcode>xsl:stylesheet</elcode>
               or <code nobreak="false">xsl:transform</code> element).</p></item><item><p>A <termref def="dt-simplified-stylesheet-module"/> in XSLT 4.0 defines a template rule
               whose implicit match pattern is <code nobreak="false">match="."</code> (matching any item), whereas in XSLT 3.0
               the implicit match pattern was <code nobreak="false">match="/"</code> (matching document nodes only). This change
               is made to allow such stylesheets to be used to process JSON input, but it also has
               the effect of changing the behavior of the stylesheet if it is applied to other items, such as
               element or text nodes.</p></item><item><p>Non-static <termref def="dt-stylesheet-parameter">stylesheet parameters</termref> wer
               defined in XSLT 3.0 to have public visibility; this changes in 4.0 to private. The effect
               is that a using package cannot directly refer to (or override) parameters declared
               in a library package that it uses.</p></item></olist><p>This specification also corrects a number of errors and omissions in XSLT 3.0, in a way that
         might create incompatibilities for some processors, depending on how they interpreted the XSLT 3.0
         specification:</p><olist><item><p>XSLT 3.0 (and earlier releases) did not fully define the evaluation context for the
            default values of template parameters. For example, if the default value of a parameter of a 
            template rule invoked <elcode>xsl:next-match</elcode>, it was not specified whether the
            current template rule should be the calling template or the called template. This omission has
            been corrected.</p></item><item><p>Where different packages import different schemas, the specification is now more
                  prescriptive about which schema is used for validation. The rules may differ from
                  the conventions adopted by implementations of XSLT 3.0.</p></item><item><p>XSLT 3.0 failed to specify a default value for the serialization parameter <code nobreak="false">indent</code>
               where the serialization method is <code nobreak="false">json</code> or <code nobreak="false">adaptive</code>. XSLT 4.0 specifies
               a default value of <code nobreak="false">no</code>.</p></item></olist><p>See also <bibref ref="xpath-40"/>, <bibref ref="xpath-functions-40"/>, and
            <bibref ref="xslt-xquery-serialization-40"/> for incompatibilities in other related
            specifications that may affect XSLT stylesheets.</p></inform-div1></back></spec><!--XSLT Processor: Saxonica-->