The following associated resources are available: Specification in XML format, XSD 1.1 Schema for XSLT 4.0 Stylesheets (non-normative), Relax-NG Schema for XSLT 4.0 Stylesheets (non-normative), Stylesheet for XML-to-JSON conversion (non-normative)
Copyright © 2026 W3C® (MIT, ERCIM, Keio, Beihang). W3C liability, trademark and document use rules apply.
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.
XSLT 4.0 is a revised version of the XSLT 3.0 Recommendation [XSLT 3.0] published on 8 June 2017. Changes are presented in 1.2 What’s New in XSLT 4.0?.
XSLT 4.0 is designed to be used in conjunction with XPath 4.0, which is defined in [XPath 4.0]. XSLT shares the same data model as XPath 4.0, which is defined in [XDM 4.0], and it uses the library of functions and operators defined in [Functions and Operators 4.0]. XPath 4.0 and the underlying function library introduce a number of enhancements, for example the availability of union and record types.
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.
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.
This section describes the status of this document at the time of its publication. Other documents may supersede this document.
This document is a working draft developed and maintained by a W3C Community Group, the XQuery and XSLT Extensions Community Group 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.
The community group welcomes comments on the specification. Comments are best submitted as issues on the group's GitHub repository.
The community group maintains two extensive test suites, one oriented to XQuery and XPath, the other to XSLT. These can be found at qt4tests and xslt40-test 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.
The publications of this community group are dedicated to our co-chair, Michael Sperberg-McQueen (1954–2024).
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 required.
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 static variables, the evaluation of [xsl:]use-when expressions (see 3.12.3 Conditional Element Inclusion) and shadow attributes (see 3.12.4 Shadow Attributes), and the detection of static errors. Dynamic evaluation consists of tasks which in general cannot be carried out until a source document is available.
Dynamic evaluation is further divided into two activities: priming the stylesheet, and invoking a selected component.
Priming the stylesheet provides the dynamic context for evaluation, and supplies all the information needed to establish the values of global variables.
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.
[Definition: The result of invoking the selected component, after any required conversion to the declared result type of the component, is referred to as the raw result.]
The raw result of the invocation is the immediate result of evaluating the sequence constructor contained in the target template or function, modified by applying the coercion rules to convert the immediate result to the type declared in the as attribute of the xsl:template or xsl:function declaration, if present.
This raw result may optionally be post-processed to construct a result tree, to serialize the result, or both, as described in 2.3.6 Post-processing the Raw Result.
Implementations may 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 may 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.
The language is designed to allow the static analysis of each 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.
[Definition: A stylesheet may be evaluated by supplying a value to be processed, together with an initial mode. The value (which can be any sequence of items) is referred to as the initial match selection. The processing then corresponds to the effect of the xsl:apply-templates instruction.]
The 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 anthe empty sequence, the result of the transformation will be empty, since no template rules are evaluated.
Processing proceeds by finding the template rules that match the items in the initial match selection, and evaluating these template rules with a focus based on the initial match selection. The template rules are evaluated in final output state.
The following information is needed when dynamic evaluation is to start with a template rule:
The initial match selection. An API that chooses to maintain compatibility with previous versions of this specification should 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 initial match selection, and the root node of the containing tree acts as the global context item.
Optionally, an initial mode.
[Definition: The initial mode is the mode used to select template rules for processing items in the initial match selection when apply-templates invocation is used to initiate a transformation.]
In searching for the template rule that best matches the items in the initial match selection, the processor considers only those rules that apply to the initial mode.
If no initial mode is supplied explicitly, then the initial mode is that named in the default-mode attribute of the (explicit or implicit) xsl:package element of the top-level package or in the absence of such an attribute, the unnamed mode.
[ERR XTDE0044] It is a dynamic error if the invocation of the stylesheet specifies an initial mode when no initial match selection is supplied (either explicitly, or defaulted to the global context item).
A (named or unnamed) modeM is eligible as an initial mode if one of the following conditions applies, where P is the top-level package of the stylesheet:
M is explicitly declared in an xsl:mode declaration within P, and has public or finalvisibility (either by virtue of its visibility attribute, or by virtue of an xsl:expose declaration).
M is the unnamed mode.
M is named in the default-mode attribute of the (explicit or implicit) xsl:package element of P.
M is declared in a package used by P, and is given public or finalvisibility in P by means of an xsl:accept declaration.
The effective value of the declared-modes attribute of the explicit or implicit xsl:package element of P is no, and M appears as a mode-name in the mode attribute of a template rule declared within P.
[ERR XTDE0045] It is a dynamic error if the invocation of the stylesheet specifies an initial mode and the specified mode is not eligible as an initial mode (as defined above).
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 tunnel parameters 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 xsl:apply-templates with an xsl:with-param child specifying tunnel="yes" or tunnel="no" as appropriate. If a parameter is supplied that is not declared or used, the value is simply ignored. These parameters are not used to set stylesheet parameters.
A supplied value is converted if necessary to the declared type of the template parameter using the coercion rules.
Details of how the result of the initial template is to be returned. For details, see 2.3.6 Post-processing the Raw Result
The raw result of the invocation is the result of processing the supplied input sequence as if by a call on xsl:apply-templates 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 as attribute of that template using the 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.
Note:
The design of the API for invoking a transformation should provide some means for users to designate the unnamed mode as the initial mode in cases where it is not the default mode.
It is a dynamic error[see ERR XTDE0700] if the template rule selected for processing any item in the initial match selection defines a template parameter that specifies required="yes" and no value is supplied for that parameter.
Note:
A stylesheet can process further source documents in addition to those supplied when the transformation is invoked. These additional documents can be loaded using the functions document (see 20.1 fn:document); or doc, unparsed-text, unparsed-text-lines, or collection (see [Functions and Operators 4.0]); or using the xsl:source-document instruction; alternatively, they can be supplied as stylesheet parameters (see 9.5 Global Variables and Parameters), or returned as the result of an extension function (see 24.2 Extension Functions).
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 xsl:result-document.)
The raw result (a sequence of values) may be returned directly to the calling application.
A result tree may be constructed from the raw result. By default, a result tree is constructed if the build-tree attribute of the unnamed output definition has the effective valueyes. An API for invoking transformations may allow this setting to be overridden by the calling application. If result tree construction is requested, it is performed as described in 2.3.6.1 Result Tree Construction.
Alternatively, the raw result may be serialized as described in 2.3.6.2 Serializing the Result. The decision whether or not to serialize the result is determined by the rules of transformation API provided by the processor, and is not influenced by anything in the stylesheet.
Note:
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.
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 [DOM Level 2]), 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 not 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 is operator. The way in which maps, arrays, and functions are returned requires careful design choices. It is recommended 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.
If a result tree is to be constructed from the raw result, then this is done by applying the rules for the process of sequence normalizationSE as defined in [Serialization 4.0]. This process takes as input the serialization parameters defined in the unnamed output definition of the top-level package; though the only parameter that is actually used by this process is item-separator.
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).
Note:
More specifically, the process raises a serialization error if any item in the raw result is an attribute node, a namespace node, or a function (including a map, but not an array: arrays are flattened).
The tree that is constructed is referred to as a final result tree.
If the raw result is anthe empty sequence, the final result tree will consist of a document node with no children.
The base URI of the document node is set to the base output URI.
Note:
The item-separator 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.
If there is no item-separator, then a single space is inserted between adjacent atomic items; for example if the raw result is the sequence 1 to 5, then sequence normalization produces a tree comprising a document node with a single child, the child being a text node with the string value 1 2 3 4 5.
If there is an item-separator, 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 A and B, and the item-separator is a comma, then the result of sequence normalization will be a document node with three children: a copy of A, a text node whose string value is a single comma, and a copy of B.
See 2.7 Parsing and Serialization.
The raw result may optionally be serialized as described in 26 Serialization. The serialization is controlled by the serialization parameters defined in the unnamed output definition of the top-level package.
Note:
The first phase of serialization, called sequence normalizationSE, takes place for some output methods but not others. For example, if the json output method (defined in [Serialization 4.0]) is selected, then the process of constructing a tree is bypassed.
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 base output URI.
In previous versions of this specification it was stated that when the raw result of the initial template or function is anthe 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 xsl:result-document). 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 anthe 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.
[Definition: The base output URI is a URI to be used as the base URI when resolving a relative URI reference allocated to a final result tree. If the transformation generates more than one final result tree, then typically each one will be allocated a URI relative to this base URI.] The way in which a base output URI is established is implementation-defined. Each invocation of the stylesheet may supply a different base output URI. It is acceptable for the base output URI to be absent, provided no constructs (such as xsl:result-document) are evaluated that depend on the value of the base output URI.
Note:
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.
This section describes the overall structure of a stylesheet as a collection of XML documents.
A stylesheet module is typically written as a namespace well-formed XML document: more formally, as described in 3.5 Stylesheet Modules, a stylesheet module takes the form of an XDM tree rooted at an element node.
The names of elements and attributes in source documents and result documents are namespace-qualified names. In addition, as described in 5.1.1 Qualified Names, 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.
There are two ways namespace bindings can be established in a stylesheet module:
[Definition: The native namespace bindings for any element in an XSLT stylesheet module are the prefix-uri mappings defined by the namespace nodes of that element, according to the rules in [XDM 4.0].]
For example, a namespace declaration of the form xmlns:math="http://www.w3.org/2005/xpath-functions/math establishes a binding of the prefix math to the namespace URI http://www.w3.org/2005/xpath-functions/math, thereby enabling functions in that namespace to be invoked using an expression such as math:sin($theta)
[Definition: The fixed namespace bindings for a stylesheet module are established using the fixed-namespaces attribute on the xsl:stylesheet, xsl:transform, or xsl:package element enclosing the stylesheet module.]
For example, the attribute fixed-namespaces="math map array" establishes bindings for the prefixes math, map, and array to the namespace URIs conventionally associated with these prefixes as described in 5.1.3 Reserved Namespaces.
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, must be bound using native namespace bindings. In particular, the 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 xmlns:xsl="http://www.w3.org/1999/XSL/Transform. (A different prefix can be used: some users prefer xslt, 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, select="math:sin($theta)") can be declared in fixed namespace bindings.
[Definition: The applicable static namespaces for an element in a stylesheet module are the fixed namespace bindings for the module if the root element of the module has a fixed-namespaces attribute, or the native namespace bindings of the element otherwise. ]
The effect of declaring fixed namespace bindings is described in more detail in 3.6.1 The fixed-namespaces Attribute.
Note:
As a general rule:
Prefixes used in the names of elements and attributes in the stylesheet must be declared using native namespace bindings.
Prefixes used in QNames appearing in the content of attribute nodes and text nodes in the stylesheet can usually be declared using fixed namespace bindings. There are a small number of exceptions, notably the standard attributes [xsl:]exclude-result-prefixes and [xsl:]extension-element-prefixes, and the stylesheet-prefix and result-prefix attributes of xsl:namespace-alias.
[Definition: The XSLT namespace has the URI http://www.w3.org/1999/XSL/Transform. It is used to identify elements, attributes, and other names that have a special meaning defined in this specification.]
Note:
The 1999 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 3.6 Stylesheet Element and 3.7 Simplified Stylesheet Modules).
XSLT processorsmust use the XML namespaces mechanism [Namespaces in XML] to recognize elements and attributes from this namespace. Elements from the XSLT namespace are recognized only in the stylesheet and not in the source document. The complete list of XSLT-defined elements is specified in C Element Syntax Summary. Implementationsmust not extend the XSLT namespace with additional elements or attributes. Instead, any extension must be in a separate namespace. Any namespace that is used for additional instruction elements must be identified by means of the extension instruction mechanism specified in 24.3 Extension Instructions.
Except where the rules for forwards compatible behavior dictate otherwise, it is a static error for any element in the stylesheet to be in the XSLT namespace unless it is an element defined in this specification [see ERR XTSE0010].
This specification uses a prefix of xsl: 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.
Note:
Throughout this specification, an element or attribute that is in no namespace, or an expanded QName whose namespace part is anthe empty sequence, is referred to as having a null namespace URI.
Note:
By convention, the names of XSLT elements, 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 current-dateTime.
Changes in 4.0 (next | previous)
Simplified stylesheets no longer require an xsl:version attribute (which means they might not need a declaration of the XSLT namespace). Unless otherwise specified, a 4.0 simplified stylesheet defaults expand-text to true. [Issue 90 PR 599 12 September 2023]
The outermost element of a simplified stylesheet need no longer be a literal result element, it can now be any instruction (including xsl:result-document). This allows a simplified stylesheet to produce JSON output as well as XML or HTML. [Issue 2322 PR 2323 30 November 2025]
A simplified syntax is allowed for a stylesheet module that defines only a single template rule. A simplified stylesheet module consist of a single instruction or literal result element together with its contents. Such a stylesheet module is equivalent to a standard stylesheet module whose xsl:stylesheet element contains a template rule containing the instruction or literal result element; the template rule has a match pattern of match=".", which matches any item.
The following example shows a stylesheet that simply evaluates one XPath expression:
<out>{count(//*)}</out>The output of the stylesheet will be an XML document such as <out>17</out> showing the number of elements found in the supplied source document.
This simplified stylesheet is defined to be equivalent to the following expanded stylesheet:
<xsl:stylesheet xmlns="http://www.w3.org/1999/XSL/Transform"
version="4.0" expand-text="yes">
<xsl:template match=".">
<out>{count(//*)}</out>
</xsl:template>
</xsl:stylesheet>Because the stylesheet contains no elements or attributes in the XSLT namespace, it does not need to contain any namespace declarations.
A simplified stylesheet can contain XSLT instructions, in which case the XSLT namespace needs to be declared. This is illustrated in the next example.
This stylesheet outputs an HTML document containing a table that summarizes the value of transactions according to their rate of tax:
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xsl:version="4.0">
<head>
<title>Expenditure by Tax Rate</title>
</head>
<body>
<table>
<thead>
<tr>
<th>Gross Amount</th>
<th>Tax Rate</th>
</tr>
</thead>
<tbody>
<xsl:for-each-group select="//transaction" group-by="vat-rate">
<tr>
<td>{sum(current-group()/value)}</td>
<td>{current-grouping-key()}</td>
</tr>
</xsl:for-each-group>
</tbody>
</table>
</body>
</html>
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.
<xsl:result-document method="json" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:array>
<xsl:for-each select="?*">
<xsl:record first="?firstName"
last="?surname"
phone="?mobile"/>
</xsl:for-each>
</xsl:array>
</xsl:result-document>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 named templateexpand, with the outermost element as the context node:
<xsl:stylesheet version="4.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template name="expand">
<xsl:element name="xsl:stylesheet">
<xsl:variable name="version"
select="(if (self::xsl:*) then @version else @xsl:version)
otherwise '4.0'"/>
<xsl:attribute name="version" select="$version"/>
<xsl:attribute name="expand-text"
select="not(number($version) le 3.0)"/>
<xsl:element name="xsl:template">
<xsl:attribute name="match" select="'.'"/>
<xsl:copy-of select="."/>
</xsl:element>
</xsl:element>
</xsl:template>
</xsl:stylesheet>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 sequence constructor. Thus, a simplified stylesheet cannot contain declarations. In particular, simplified stylesheets therefore cannot use template rules, global variables, stylesheet parameters, stylesheet functions, keys, attribute-sets, or output definitions. Furthermore, they cannot contain xsl:include, xsl:import, or xsl:use-package declarations.
The only useful way to initiate the transformation is to supply an item as the initial match selection, to be matched by the implicit match="." template rule using the unnamed mode.
Note:
There are several significant changes to simplified stylesheets in XSLT 4.0.
It is no longer required to include an xsl:version attribute; this in turn means it is often no longer necessary to declare the xsl namespace. The xsl:version attribute defaults to the version of the XSLT processor, that is, "4.0" for an XSLT 4.0 processor.
If the xsl:version attribute is omitted, or is set to "4.0" or a larger value, then the expand-text attribute defaults to true, meaning that text value templates are recognized.
The outermost element of a simplified stylesheet can be any instruction (for example, xsl:array, xsl:map, or xsl:result-document), allowing the stylesheet to deliver arrays, maps, or serialized JSON.
The match pattern of the implicit template rule uses match="." rather than match="/", allowing the to be any item, not only a document node.
Note:
It is technically valid for the outermost element to be xsl:variable or xsl:param, because these are defined as instructions; however, this achieves no useful purpose because the result of these instructions is anthe empty sequence.
This specification provides threeseveral features that cause the raw stylesheet to be preprocessed as the first stage of static processing:
Whitespace and commentary are stripped (see 3.12.1 Stripping Whitespace and Commentary from the Stylesheet).
Any xsl:note elements are removed: see 3.12.2 The xsl:note element.
Elements may be conditionally included or excluded by means of an [xsl:]use-when attribute as described in 3.12.3 Conditional Element Inclusion.
Attributes may be conditionally computed as described in 3.12.4 Shadow Attributes.
Note that many of the rules affecting the validity of stylesheet documents apply to a stylesheet after this preprocessing phase has been carried out.
XPath defines the concept of an expression contextXP which contains all the information that can affect the result of evaluating an expression. The expression context has two parts, the static contextXP, and the dynamic contextXP. The components that make up the expression context are defined in the XPath specification (see [XPath 4.0] section 2.2 Expression Context). This section describes the way in which these components are initialized when an XPath expression is contained within an XSLT stylesheet.
This section does not apply to static expressions (whose context is defined in 9.7 Static Expressions), nor to XPath expressions evaluated using xsl:evaluate (whose context is defined in 10.5.2 Dynamic context for the target expression).
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, xsl:next-match and xsl:apply-imports), and also by the functions in the extended function library described in this specification.
The following four sections describe:
5.3.1 Initializing the Static Context
5.3.2 Additional Static Context Components used by XSLT
5.3.3 Initializing the Dynamic Context
5.3.4 Additional Dynamic Context Components used by XSLT
The static contextXP of an XPath expression appearing in an XSLT stylesheet is initialized as follows. In these rules, the term containing element 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 enclosing element means the containing element or any of its ancestors.
XPath 1.0 compatibility mode is set to true if and only if the containing element is processed with XSLT 1.0 behavior (see 3.8 Backwards Compatible Processing).
The statically known namespacesXP are the applicable static namespaces for the containing element.
The default namespace for elements and typesXP is determined as described in 5.1.2.1 Unprefixed Element Names.
The default function namespaceXP is http://www.w3.org/2005/xpath-functions (and cannot be changed).
The in-scope schema definitionsXP for the XPath expression are the same as the in-scope schema components for the stylesheet, and are as specified in 3.13 Built-in Types.
The in-scope variablesXP are defined by the variable binding elements that are in scope for the containing element (see 9 Variables and Parameters).
The statically known function definitionsXP are:
The functions defined in [Functions and Operators 4.0] in namespaces http://www.w3.org/2005/xpath-functions and http://www.w3.org/2005/xpath-functions/math;
The functions defined in this specification in namespaces http://www.w3.org/2005/xpath-functions and http://www.w3.org/2005/xpath-functions/map;
Constructor functions for all the simple types in the in-scope schema definitionsXP, including both built-in types and user-defined types;
The stylesheet functions defined in the containing package;
Stylesheet functions defined in used packages, subject to visibility: see 3.4.2 Dependencies between Packages;
any extension functions bound using implementation-defined mechanisms (see 24 Extensibility and Fallback).
Note:
The term extension function includes both vendor-supplied and user-written extension functions.
Note:
It follows from the above that a conformant XSLT processor must implement the entire library of functions defined in [Functions and Operators 4.0] as well as those defined in this specification.
The statically known collationsXP are implementation-defined, except that they must always include (a) the Unicode codepoint collation, defined in [Functions and Operators 4.0] section 5.3 Comparison of strings, and (b) the family of UCA collations described in [Functions and Operators 4.0] section 5.3.4 The Unicode Collation Algorithm.
Static base URI: 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 [XDM 4.0] section 7.6.2 base-uri Accessor.
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 recommended (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 doc or document functions are called with a relative URI, the required document is by default located relative to the deployed location of the stylesheet.
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 static-base-uri function returns anthe empty sequence, and other operations that depend on the static base URI may fail with a dynamic error.
The set of statically known decimal formatsXP is the set of decimal formats defined by xsl:decimal-format declarations in the stylesheet.
In addition to the values that make up the focus, 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:
The current template rule, which is the template rule most recently invoked by an xsl:apply-templates, xsl:apply-imports, or xsl:next-match instruction: see 6.9 Overriding Template Rules;
The current mode, which is the mode set by the most recent call of xsl:apply-templates (for a full definition see 6.7 Modes);
The current group and current grouping key, which provide information about the collection of items currently being processed by an xsl:for-each-group instruction: see 14.2.1 fn:current-group and 14.2.2 fn:current-grouping-key;
Note:
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 anthe empty sequence.
The current merge group and current merge key, which provide information about the collection of items currently being processed by an xsl:merge instruction.
The current captured groups: this is maintained when a string is matched against a regular expression using the xsl:analyze-string 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 regex-groups and regex-group functions: see 17.2.2 fn:regex-group.
The output state: this is a flag whose two possible values are final output state and temporary output state. The initial setting when the stylesheet is invoked by executing a template is final output state, and it is switched to temporary output state by instructions such as xsl:variable. For more details, see 25.2 Restrictions on the use of xsl:result-document.
The current output URI: 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 base output URI. During the evaluation of an xsl:result-document instruction, the current output URI is set to the absolute URI identified by the href attribute of that instruction.
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.
[Definition: The initial setting of a component of the dynamic context is used when evaluating global variables and stylesheet parameters, when evaluating the use and match attributes of xsl:key, and when evaluating the initial-value of xsl:accumulator and the select expressions or contained sequence constructors of xsl:accumulator-rule].
[Definition: The term non-contextual function call is used to refer to function calls that do not pass the dynamic context to the called function. This includes all calls on stylesheet functions and all dynamic function callsXP, (that is calls to function items). It excludes calls to some functions in the namespace http://www.w3.org/2005/xpath-functions, in particular those that explicitly depend on the context, such as the current-group and regex-group functions. It is implementation-defined whether, and under what circumstances, calls to extension functions are non-contextual.]
Named function references (such as position#0) and calls on function-lookup (for example, function-lookup("position", 0)) 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 regex-group#1) delivers a function item that holds a snapshot of the in its closure, and subsequent evaluation of that function item will return the relevant value from that snapshot.
Template rules define the processing that can be applied to items that match a particular pattern.
[Definition: A mode is a set of template rules; when the xsl:apply-templates 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.] Modes allow a node in a source tree (for example) to be processed multiple times, each time producing a different result. They also allow different sets of template rules to be active when processing different trees, for example when processing documents loaded using the document function (see 20.1 fn:document).
Modes are identified by an expanded QName; in addition to any named modes, there is always one unnamed mode available. Whether a mode is named or unnamed, its properties may be defined in an xsl:mode declaration. If a mode name is used (for example in an xsl:template declaration or an xsl:apply-templates instruction) and no declaration of that mode appears in the stylesheet, the mode is implicitly declared with default properties.
Changes in 4.0 (next | previous)
The xsl:mode declaration acquires an attribute as="sequence-type" which declares the return type of all template rules in that mode. [Issue 750 PR 751 16 October 2023]
The xsl:mode declaration acquires an attribute copy-namespaces which determines whether or not the built-in template rule copies unused namespace bindings. [Issue 1724 PR 1929 13 April 2025]
<!-- Category: declaration -->
<xsl:mode
name? = eqname
as? = sequence-type〔'item()*'〕
streamable? = boolean〔'no'〕
use-accumulators? = tokens〔''〕
on-no-match? = "deep-copy" | "shallow-copy" | "shallow-copy-all" | "deep-skip" | "shallow-skip" | "text-only-copy" | "fail"〔'text-only-copy'〕
on-multiple-match? = "use-last" | "fail"〔'use-last'〕
warning-on-no-match? = boolean
warning-on-multiple-match? = boolean
typed? = string〔'unspecified'〕
copy-namespaces? = boolean〔'yes'〕
visibility? = "public" | "private" | "final"〔'private'〕 >
<!-- Content: (xsl:template*) -->
</xsl:mode>
[Definition: The unnamed mode is the default mode used when no mode attribute is specified on an xsl:apply-templates instruction or xsl:template declaration, unless a different default mode has been specified using the [xsl:]default-mode attribute of a containing element.]
Every mode other than the unnamed mode is identified by an expanded QName.
A stylesheet may contain multiple xsl:mode declarations and may include or import stylesheet modules that also contain xsl:mode declarations. The name of an xsl:mode declaration is the value of its name attribute, if any.
[Definition: All the xsl:mode declarations in a package that share the same name are grouped into a named mode definition; those that have no name are grouped into a single unnamed mode definition.]
The declared-modes attribute of the xsl:package element determines whether implicit mode declarations are allowed, as described in 3.4.5.1 Requiring Explicit Mode Declarations. If the package allows implicit mode declarations, then if a stylesheet does not contain a declaration of the unnamed mode, a declaration is implied equivalent to an xsl:mode element with no attributes. Similarly, if there is a mode that is named in an xsl:template or xsl:apply-templates element, or in the [xsl:]default-mode attribute of a containing element, and the stylesheet does not contain a declaration of that mode, then a declaration is implied comprising an xsl:mode element with a name attribute equal to that mode name, plus the attribute visibility="private".
The attributes of the xsl:mode 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.
| Attribute | Values | Meaning | ||||
|---|---|---|---|---|---|---|
| name | An EQName | Specifies the name of the mode. If omitted, this xsl:mode declaration provides properties of the unnamed mode | ||||
| as | A SequenceType | 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 as attribute on xsl:template, the values must be consistent. | ||||
| streamable | yes or no (default no) | Determines whether template rules in this mode are to be capable of being processed using streaming. If the value yes is specified, then the body of any template rule that uses this mode must conform to the rules for streamable templates given in 5 Streamable TemplatesSG. | ||||
| use-accumulators | List of accumulator names, or #all (default is anthe empty list) | Relevant only when this mode is the initial mode of the transformation, determines which accumulators are applicable to documents containing nodes in the initial match selection. For further details see 19.2 Applicability of Accumulators. | ||||
| on-no-match | One of deep-copy, shallow-copy, deep-skip, shallow-skip, text-only-copy or fail (default text-only-copy) | Determines selection of the built-in template rules that are used to process an item when an xsl:apply-templates instruction selects an item that does not match any user-written template rule in the stylesheet. For details, see 6.8 Built-in Template Rules. | ||||
| on-multiple-match | One of fail or use-last (default use-last) | Defines the action to be taken when xsl:apply-templates is used in this mode and more than one user-written template rule is available to process an item, each having the same import precedence and priority. The value fail indicates that it is a dynamic error if more than one template rule matches an item. The value use-last indicates that the situation is not to be treated as an error (the last template in declaration order is the one that is used). | ||||
| warning-on-no-match | One of yes or no. The default is implementation-defined | Requests the processor to output (or not to output) a warning message in the case where an xsl:apply-templates instruction selects an item that matches no user-written template rule. The form and destination of such warnings is implementation-defined. The processor may ignore this attribute, for example if the environment provides no suitable means of communicating with the user. | ||||
| warning-on-multiple-match | One of yes or no. The default is implementation-defined | Requests the processor to output a warning message in the case where an xsl:apply-templates instruction selects an item that matches multiple template rules having the same import precedence and priority. The form and destination of such warnings is implementation-defined. The processor may ignore this attribute, for example if the environment provides no suitable means of communicating with the user. | ||||
| typed | One of yes, no, strict, lax, or unspecified. The default is unspecified. | See 6.7.4 Declaring the Type of Values Processed by a Mode. | ||||
| copy-namespaces | One of yes or no. The default is yes. | If on-no-match is shallow-copy, shallow-copy-all, or deep-copy, this attribute determines the effective value of the copy-namespaces attribute on the implicit xsl:copy or xsl:copy-of instruction in the built-in template rule (see 6.8 Built-in Template Rules). In other cases it is ignored, apart from checking that its value is valid. | ||||
| visibility | One of public, private, or final. The default is private. | See 3.4.4.1 Visibility of Components. If the mode is unnamed, that is, if the name attribute is absent, then the visibility attribute if present must have the value private.
| ||||
[Definition: A streamable mode is a mode that is declared in an xsl:mode declaration with the attribute streamable="yes".]
For any named mode, the effective value of each attribute is taken from an xsl:mode declaration that has a matching name in its name 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 import precedence is used.
For the unnamed mode, the effective value of each attribute is taken from an xsl:mode declaration that has no name 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 import precedence is used.
[ERR XTSE0545] It is a static error if for any named or unnamed mode, a package explicitly specifies two conflicting values for the same attribute in different xsl:mode declarations having the same import precedence, unless there is another definition of the same attribute with higher import precedence. The attributes in question are the attributes other than name on the xsl:mode element.
Traditionally, template rules have most commonly been used to construct XDM nodes, and the xsl:apply-templates 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 xsl:apply-templates 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.
XSLT 4.0 therefore allows the result type of the template rules in a mode to be declared using the as attribute on the xsl:mode declaration. If this is absent, it defaults to item()*. The presence of an as attribute on a mode provides useful documentation and consistency checking, and enables the XSLT processor to infer a static type for an xsl:apply-templates instruction, which can be useful for optimization.
If a template rule R is applicable to a mode M, and M is declared with an as attribute whose value is the SequenceTypeT, then:
If R has an as attribute, the SequenceTypeS declared by R must be a subtype of T.
[ERR XTSE4040] It is a static error if a template ruleR has an as attribute S, and the template rule is applicable to a modeM that is declared with an as attribute T, and the sequence type S is not a subtype of the sequence type T as defined by the relationship subtype(S, T) in [XPath 4.0] section 3.3.1 Subtypes of Sequence Types.
If R has no as attribute, then it is treated as if it had an as attribute set to T. This means that a type error[see ERR XTTE0505] is raised if the result of the template rule cannot be coerced to a value of type T.
If R 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 as="node()" and another specifies as="map(*)", 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 implausibilityXPmay be reported if the only value that would satisfy both types is anthe empty sequence, map, or array.
Note:
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 mode="#all"), 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.
The requirement to return values of the correct type extends also to the built-in template rule for the mode (see 6.8 Built-in Template Rules). 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 must be raised dynamically [see ERR XTTE0505].
When an item is selected by xsl:apply-templates and there is no user-specified template rule in the stylesheet that can be used to process that item, then a built-in template rule is evaluated instead.
The built-in template rules have lower import precedence than all other template rules. Thus, the stylesheet author can override a built-in template rule by including an explicit template rule.
There are seven sets of built-in template rules available. The set that is chosen is a property of the mode selected by the xsl:apply-templates instruction. This property is set using the on-no-match attribute of the xsl:mode declaration, which takes one of the values deep-copy, shallow-copy, shallow-copy-all,deep-skip, shallow-skip, text-only-copy, or fail, the default being text-only-copy. The effect of these seven sets of built-in template rules is explained in the following subsections.
This processing mode is introduced in XSLT 4.0 as a variant of shallow-copy to enable recursive descent processing of trees involving maps and arrays, such as might result from parsing JSON input.
For all items other than maps and arrays, the effect of shallow-copy-all is exactly the same as shallow-copy.
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 value records using the function array:members. Each of these value records is processed by a call on xsl:apply-templates (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.
That is, the template rule is equivalent to the following, except that this does not show the propagation of template parameters:
<xsl:array use="?value"> <xsl:apply-templates select="array:members(.)" mode="#current"/> </xsl:array>
| Editorial note | |
| TODO: the use attribute is no more. Example need reworking. | |
Note:
A value record is a single-entry map: it has a single key-value pair with the key "value", 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.
For maps, the processing is as follows:
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 map:entries 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.
If the map contains a single entry { K : V0 }, then a new single entry map { K: V1 } is constructed in which V1 is the result of applying templates to V0 (using the current mode, and passing on the values of all template parameters).
Note:
This rule has the effect that if the input is a value record, the output will also be a value record.
If the map is empty, the result is anthe empty map.
In the first case, the template rule is equivalent to the following, except that this does not show the propagation of template parameters:
<xsl:map> <xsl:apply-templates select="map:entries(.)" mode="#current"/> </xsl:map>
In the second case, the template rule is equivalent to the following, except that this does not show the propagation of template parameters:
<xsl:map-entry key="map:keys(.)"> <xsl:apply-templates select="map:items(.)" mode="#current"/> </xsl:map-entry>
The reason there is a special rule for maps with one entry is to ensure that the process terminates.
The overall effect is best understood with an example.
The following stylesheet transforms a supplied JSON document by deleting all properties named "Note", appearing at any level:
<xsl:stylesheet version="3.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:mode on-no-match="shallow-copy-all"/>
<xsl:template match="record(Note)">
<!-- no action -->
</xsl:template>
</xsl:stylesheet>Consider the following JSON input, converted to an array of maps by calling the function parse-json:
[
{ "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
}
]The logic proceeds as follows:
The outermost array is processed by applying templates to a sequence of value records, the first being in the form:
{ "value": map: { "Title": ..., "Author": ..., ... }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.
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 map: { "Title": ..., "Author": ..., ... } representing a book.
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 {"Title": "Steppenwolf"}.
The default processing for a single-entry map of the form { "Title": "Steppenwolf" } is to return the value unchanged. This is achieved by applying templates to the string "Steppenwolf"; the default template rule for strings returns the string unchanged.
When a single-entry map in the form { "Note": "out of print" } 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 match="record(Note)" that matches such single-entry maps.
When a single-entry map in the form "Authors": [ "Bruce Betts", "Erica Colon" ] is encountered, a new single-entry map is produced; it has the same key ("Authors"), and a value obtained by applying templates to the array [ "Bruce Betts", "Erica Colon" ]. 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.
When the single-entry map "Authors": [ "Enid Blyton", { "Note": "possibly misattributed" } ] is encountered, the recursive processing results in templates being applied to the map { "Note": "possibly misattributed" }. This matches the template rule having match="record(Note)", which returns no output, so the entry is effectively deleted.
Note:
The map entry is deleted, but the map itself remains, so the value becomes "Authors": [ "Enid Blyton", map: {} ].
The effect of processing a tree using a mode that specifies on-no-match="deep-skip" 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.
The effect of choosing on-no-match="deep-skip" is as follows:
The built-in rule for document nodes is equivalent to calling xsl:apply-templates with no select attribute, and with the mode attribute set to #current. If the built-in rule was invoked with parameters, those parameters are passed on in the implicit xsl:apply-templates instruction.
In the case where there are no parameters, this is equivalent to the following rule:
<xsl:template match="document-node()" mode="M"> <xsl:apply-templates mode="#current"/> </xsl:template>
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 anthe empty sequence (without applying templates to any children or ancestors).
This is equivalent to the following rule:
<xsl:template match="." mode="M"/>
The effect of processing a tree using a mode that specifies on-no-match="shallow-skip" is to drop both the textual content and the markup from the result document, except where there is an explicit user-written template rule that dictates otherwise.
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 xsl:apply-templates instructions.
In the case where there are no parameters, this is equivalent to the following rule:
<xsl:template match="document-node()|element()" mode="M"> <xsl:apply-templates select="@*" mode="#current"/> <xsl:apply-templates mode="#current"/> </xsl:template>
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 anthe empty sequence.
This is equivalent to the following rule:
<xsl:template match="." mode="M"/>
The built-in template rule for arrays (see 22 Arrays) is to apply templates to the members of the array. It is equivalent to invoking xsl:apply-templates with the select attribute set to ?* (which selects the members of the array), and with the mode attribute set to #current. If the built-in rule was invoked with parameters, those parameters are passed on in the implicit xsl:apply-templates instruction.
This is equivalent to the following in the case where there are no parameters:
<xsl:template match=".[. instance of array(*)]" mode="M"> <xsl:apply-templates mode="#current" select="?*"/> </xsl:template>
XSLT offers two constructs for processing each entry in a collection: xsl:for-each and xsl:iterate.
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 item and sequence are used generically.
The main difference between the two constructs is that with xsl:for-each, 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 xsl:iterate, 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 xsl:iterate suitable for tasks such as creating a running total over a sequence of financial transactions.
A further difference is that xsl:for-each permits sorting of the input sequence, while xsl:iterate does not.
xsl:for-each instructionChanges in 4.0 (next | previous)
The xsl:for-each and xsl:apply-templates instructions acquire an attribute separator 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.] [ 1 January 2022]
<!-- Category: instruction -->
<xsl:for-each
select = expression
separator? = { string } >
<!-- Content: (xsl:sort*, sequence-constructor) -->
</xsl:for-each>
The xsl:for-each instruction processes each in a sequence of items, evaluating the sequence constructor within the xsl:for-each instruction once for each item in that sequence.
The select attribute is required; it contains an expression which is evaluated to produce a sequence, called the input sequence. If there is an xsl:sort element present (see 13 Sorting) the input sequence is sorted to produce a sorted sequence. Otherwise, the sorted sequence is the same as the input sequence.
The xsl:for-each instruction contains a sequence constructor. The sequence constructor is evaluated once for each item in the sorted sequence, with the focus set as follows:
The context item is the item being processed.
The context position is the position of this item in the sorted sequence.
The context size is the size of the sorted sequence (which is the same as the size of the input sequence).
For each item in the input sequence, evaluating the sequence constructor produces a sequence of items (see 5.7 Sequence Constructors). These output sequences are concatenated; if item Q follows item P in the sorted sequence, then the result of evaluating the sequence constructor with Q as the context item is concatenated after the result of evaluating the sequence constructor with P as the context item. The result of the xsl:for-each instruction is the concatenated sequence of items.
For example, given an XML document with this structure
<customers>
<customer>
<name>...</name>
<order>...</order>
<order>...</order>
</customer>
<customer>
<name>...</name>
<order>...</order>
<order>...</order>
</customer>
</customers>the following would create an HTML document containing a table with a row for each customer element
<xsl:template match="/">
<html>
<head>
<title>Customers</title>
</head>
<body>
<table>
<tbody>
<xsl:for-each select="customers/customer">
<tr>
<th>
<xsl:apply-templates select="name"/>
</th>
<xsl:for-each select="order">
<td>
<xsl:apply-templates/>
</td>
</xsl:for-each>
</tr>
</xsl:for-each>
</tbody>
</table>
</body>
</html>
</xsl:template>
Consider a JSON document of the form:
[
{ "city": "London", "latitude": 51.5099, "longitude": -0.1181 },
{ "city": "Paris", "latitude": 48.8647, "longitude": 2.3488 },
{ "city": "Berlin", "latitude": 52.5200, "longitude": 13.4049 }
]The following code processes this array to produce an XML representation of the same information. The cities are sorted by name:
<xsl:for-each select="json-doc('input.json')?*">
<xsl:sort select="?city"/>
<city number="{position()}"
name="{?city}"
latitude="{?latitude}"
longitude="{?longitude}"/>
</xsl:for-each>In this example it is possible to use the expression $array?* 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 anthe empty sequence, corresponding to the JSON value null, or it might be a sequence containing several items), the function array:members can be used to deliver the contents of the array as a sequence of value records. This is illustrated in the next example.
xsl:for-each to process an array containing nullsExample: Using xsl:for-each to process an array containing nullsConsider a JSON document of the form:
[
{ "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] }
]The requirement is to convert this to the following XML:
<cities> <city name="London" Q1="12.3" Q2="15.6" Q3="" Q4="18.2"/> <city name="Paris" Q1="7.9" Q2="19.1" Q3="23.0" Q4=""/> <city name="Berlin" Q1="5.6" Q2="" Q3="14.6" Q4="9.5"/> </cities>
The following code achieves this transformation:
<xsl:for-each select="json-doc('input.json')?*">
<city name="{?city}">
<xsl:for-each select="array:members(?data)">
<xsl:attribute name="Q{position()}" select="?value"/>
</xsl:for-each>
</city>
</xsl:for-each>In this example the expression $array?* cannot be used on the inner arrays because JSON nulls (which translate to anthe empty sequence in XDM) would be lost. Instead the function array:members is used to create a sequence of value records: a non-null entry is represented by a value such as { 'value': 12.3 }, while a null entry would be { 'value': () }.
Consider a JSON document of the form:
{
"London": { "latitude": 51.5099, "longitude": -0.1181 },
"Paris": { "latitude": 48.8647, "longitude": 2.3488 },
"Berlin": { "latitude": 52.5200, "longitude": 13.4049 }
}The following code processes this map to produce an XML representation of the same information. The cities are sorted by name:
<xsl:for-each select="map:pairs(json-doc('input.json'))">
<xsl:sort select="?key"/>
<city number="{position()}"
name="{?key}"
latitude="{?value?latitude}"
longitude="{?value?longitude}"/>
</xsl:for-each>In this example the map is decomposed to a sequence of key-value pairs, each represented as a map with two entries, "key" and "value", which can be accessed using the lookup expressions ?key and ?value.
xsl:iterate InstructionThe xsl:iterate instruction processes the items in a sequence in order; unlike xsl:for-each, the result of processing one item can affect the way that subsequent items are processed.
<!-- Category: instruction -->
<xsl:iterate
select = expression >
<!-- Content: (xsl:param*, xsl:on-completion?, sequence-constructor) -->
</xsl:iterate>
<!-- Category: instruction -->
<xsl:next-iteration>
<!-- Content: (xsl:with-param*) -->
</xsl:next-iteration>
<!-- Category: instruction -->
<xsl:break
select? = expression >
<!-- Content: sequence-constructor -->
</xsl:break>
<xsl:on-completion
select? = expression >
<!-- Content: sequence-constructor -->
</xsl:on-completion>
Consider the following JSON document representing transactions in a bank account:
[
{ "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 }
]The following code converts this to an XML representation that includes a running balance:
<xsl:iterate select="json-doc('account.json') => array:members()">
<xsl:param name="balance" as="xs:decimal" select="0"/>
<xsl:variable name="delta" select="?value?credit otherwise -?value?debit"/>
<entry date="{ ?value?date }"
amount="{ $delta }"
balance="{ $balance + $delta }"/>
<xsl:next-iteration>
<xsl:with-param name="balance" select="$balance + $delta"/>
</xsl:next-iteration>
</xsl:iterate>Using array:members() 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 null entries, or if any null entries are to be ignored, it becomes possible to simplify the code as follows:
<xsl:iterate select="json-doc('account.json')?*">
<xsl:param name="balance" as="xs:decimal" select="0"/>
<xsl:variable name="delta" select="?credit otherwise -?debit"/>
<entry date="{ ?date }"
amount="{ $delta }"
balance="{ $balance + $delta }"/>
<xsl:next-iteration>
<xsl:with-param name="balance" select="$balance + $delta"/>
</xsl:next-iteration>
</xsl:iterate>The select attribute contains an expression which is evaluated to produce a sequence, called the input sequence.
The sequence constructor contained in the xsl:iterate instruction is evaluated once for each item in the input sequence, in order, or until the loop exits by evaluating an xsl:break instruction, whichever is earlier. Within the sequence constructor that forms the body of the xsl:iterate instruction, the context item is set to each item from the value of the select expression in turn; the context position reflects the position of this item in the input sequence, and the context size is the number of items in the input sequence (which may be greater than the number of iterations, if the loop exits prematurely using xsl:break).
Note:
If xsl:iterate is used in conjunction with xsl:source-document to achieve streaming, calls on the function last will be disallowed.
The xsl:break and xsl:on-completion elements may have either a select attribute or a non-empty contained sequence constructor but not both. The effect of the element in both cases is obtained by evaluating the select expression if present or the contained sequence constructor otherwise; if neither is present, the value is anthe empty sequence.
Note:
The xsl:on-completion element appears before other children of xsl:iterate to ensure that variables declared in the sequence constructor are not in scope within xsl:on-completion, since such variables do not have a defined value within xsl:on-completion especially in the case where the value of the select attribute is anthe empty sequence.
The effect of xsl:next-iteration 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 xsl:break 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 xsl:iterate element.
The instructions xsl:next-iteration and xsl:break are allowed only as descendants of an xsl:iterate instruction, and only in a tail position within the sequence constructor forming the body of the xsl:iterate instruction.
[Definition: An instructionJ is in a tail position within a sequence constructorSC if it satisfies one of the following conditions:
J is the last instruction in SC, ignoring any xsl:fallback instructions.
J is in a tail position within the sequence constructor that forms the body of an xsl:if instruction that is itself in a tail position within SC.
J is in a tail position within the sequence constructor that forms the body of an xsl:when or xsl:otherwise branch of an xsl:chooseor xsl:switch instruction that is itself in a tail position within SC.
J is in a tail position within the sequence constructor that forms the body of an xsl:try instruction that is itself in a tail position within SC (that is, it is immediately followed by an xsl:catch element, ignoring any xsl:fallback elements).
J is in a tail position within the sequence constructor that forms the body of an xsl:catch element within an xsl:try instruction that is itself in a tail position within SC.
]
[ERR XTSE3120] It is a static error if an xsl:break or xsl:next-iteration element appears other than in a tail position within the sequence constructor forming the body of an xsl:iterate instruction.
[ERR XTSE3125] It is a static error if the select attribute of xsl:break or xsl:on-completion is present and the instruction has children.
[ERR XTSE3130] It is a static error if the name attribute of an xsl:with-param child of an xsl:next-iteration element does not match the name attribute of an xsl:param child of the innermost containing xsl:iterate instruction.
Parameter names in xsl:with-param must be unique: [see ERR XTSE0670].
The result of the xsl:iterate instruction is the concatenation of the sequences that result from the repeated evaluation of the contained sequence constructor, followed by the sequence that results from evaluating the xsl:break or xsl:on-completion element if any.
Any xsl:param element that appears as a child of xsl:iterate 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 9.3 Values of Variables and Parameters. The dynamic context for evaluating the initial value of an xsl:param element is the same as the dynamic context for evaluating the select expression of the xsl:iterate instruction (the context item is thus not the first item in the input sequence).
On the first iteration a parameter always takes its initial value (which may depend on variables or other aspects of the dynamic context). Subsequently:
If an xsl:next-iteration instruction is evaluated, then parameter values for processing the next item in the input sequence can be set in the xsl:with-param children of that instruction; in the absence of an xsl:with-param element that names a particular parameter, that parameter will retain its value from the previous iteration.
If an xsl:break instruction is evaluated, no further items in the input sequence are processed.
If neither an xsl:next-iteration nor an xsl:break instruction is evaluated, then the next item in the input sequence is processed using parameter values that are unchanged from the previous iteration.
The xsl:next-iteration instruction contributes nothing to the result sequence (technically, it returns anthe empty sequence). The instruction supplies parameter values for the next iteration, which are evaluated according to the rules given in 9.10 Setting Parameter Values; if there are no further items in the input sequence then it supplies parameter values for use while evaluating the body of the xsl:on-completion element if any.
The xsl:break instruction indicates that the iteration should terminate without processing any remaining items from the input sequence. The select expression or contained sequence constructor is evaluated using the same context item, position, and size as the xsl:break instruction itself, and the result is appended to the result of the xsl:iterate instruction as a whole.
If neither an xsl:next-iteration nor an xsl:break 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.
The optional xsl:on-completion element (which is not technically an instruction and is not technically part of the sequence constructor) is evaluated when the input sequence is exhausted. It is not evaluated if the evaluation is terminated using xsl:break. During evaluation of its select expression or sequence constructor the context item, position, and size are absent (that is, any reference to these values is an error). However, the values of the parameters to xsl:iterate are available, and take the values supplied by the xsl:next-iteration instruction evaluated while processing the last item in the sequence.
If the input sequence is empty, then the result of the xsl:iterate instruction is the result of evaluating the select attribute or sequence constructor forming the body of the xsl:on-completion element, using the initial values of the xsl:param elements. If there is no xsl:on-completion element, the result is anthe empty sequence.
Note:
Conceptually, xsl:iterate behaves like a tail-recursive function. The xsl:next-iteration 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 xsl:iterate 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 xsl:iterate 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 xsl:source-document, 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.
Note:
One of the motivations for introducing the xsl:iterate instruction was to enable information to be retained while processing a streamed sequence of sibling nodes. For examples illustrating this, see 6 Streaming withSG.
There are several instructions in XSLT that support conditional processing: xsl:if, xsl:choose, and xsl:switch. The xsl:if instruction provides simple if-then-else conditionality; the xsl:choose instruction supports selection of one choice when there are several possibilities, and xsl:switch allows a branch to be selected based on the value of a given expression.
XSLT 3.0 also supports xsl:try and xsl:catch which define conditional processing to handle dynamic errors.
Note:
XSLT offers a number of ways of expressing conditional logic.
XSLT 1.0 offered the xsl:if instruction for cases where output was to be produced only if a condition was true, with xsl:choose 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.
XSLT 2.0 added the XPath conditional expression providing two-way branches for use at a finer-grained level where xsl:choose could be excessively verbose: it allowed constructs such as <xsl:value-of select="if ($x) then 'red' else 'green'/> to be reduced from eight lines of code to one.
XSLT 4.0 introduces the then and else attributes for xsl:if, which are particularly useful in contexts such as the body of an xsl:function 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 <xsl:if test="empty($seq)" then="1" else="head($seq) * my:f(tail($seq))"/>. The select attribute of xsl:when and xsl:otherwise 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.
The xsl:switch instruction is introduced in XSLT 4.0 as an alternative to xsl:choose 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.
xsl:if<!-- Category: instruction -->
<xsl:if
test = expression
then? = expression
else? = expression〔()〕 >
<!-- Content: sequence-constructor -->
</xsl:if>
The xsl:if element has a mandatory test attribute, whose value is an expression. The content is a sequence constructor.
If the xsl:if element has a then attribute, then it must have no children. That is, the then attribute and the contained sequence constructor are mutually exclusive.
The result of the xsl:if instruction depends on the effective boolean valueXP of the expression in the test attribute. The rules for determining the effective boolean value of an expression are given in [XPath 4.0]: they are the same as the rules used for XPath conditional expressions.
If the effective boolean value of the expression is true, then:
If there is a then attribute, the expression in the then attribute is evaluated, and the resulting value is returned as the result of the xsl:if instruction.
If there is a non-empty sequence constructor, it is evaluated and the resulting value is returned as the result of the xsl:if instruction.
Otherwise, the result of the xsl:if instruction is anthe empty sequence.
If the effective boolean value of the testexpression is false, then:
If there is an else attribute, the expression in the else attribute is evaluated, and the resulting value is returned as the result of the xsl:if instruction.
Otherwise, the result of the xsl:if instruction is anthe empty sequence.
If the test expression has no effective boolean value (for example, if it is a sequence of several integers, or a map), then a dynamic error occurs. (See [ERR FORG0006] FO.)
Note:
The semantics of the xsl:if instruction are essentially equivalent to the semantics of the conditional expression in XPath: the construct <xsl:if test="C" then="X" else="Y"/> can equivalently be written <xsl:sequence select="if (C) then X else Y"/>. The same effect can also be achieved by writing <xsl:choose><xsl:when test="C" select="X"/><xsl:otherwise select="Y"/></xsl:choose>. The choice of which of these constructs to use is a largely matter of personal style.
In the following example, the names in a group of names are formatted as a comma separated list:
<xsl:template match="namelist/name"> <xsl:apply-templates/> <xsl:if test="not(position()=last())">, </xsl:if> </xsl:template>
This adds a comma after every item except the last. This can also be expressed as:
<xsl:template match="namelist/name"> <xsl:if test="not(position()=1)">, </xsl:if> <xsl:apply-templates/> </xsl:template>
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.)
The following example shows the use of xsl:if to deliver the result of a recursive function:
<xsl:function name="f:product" as="xs:double"> <xsl:param name="in" as="xs:double*"/> <xsl:if test="empty($in)" then="1e0" else="head($in) * f:product(tail($in))"/> </xsl:function>
xsl:chooseChanges in 4.0 (next | previous)
In xsl:choose, the xsl:when and xsl:otherwise elements can take a select attribute in place of a sequence constructor. [Issue 167 PR 237 25 November 2022]
<!-- Category: instruction -->
<xsl:choose>
<!-- Content: (xsl:when+, xsl:otherwise?) -->
</xsl:choose>
<xsl:when
test = expression
select? = expression >
<!-- Content: sequence-constructor -->
</xsl:when>
<xsl:otherwise
select? = expression >
<!-- Content: sequence-constructor -->
</xsl:otherwise>
The xsl:choose element selects one among a number of possible alternatives. It consists of a sequence of one or more xsl:when elements followed by an optional xsl:otherwise element. Each xsl:when element has an attribute, test, which specifies an expression used as a condition.
The effective value of an xsl:when or xsl:otherwise branch may be supplied using either a select attribute or a contained sequence constructor. These are mutually exclusive: if the select attribute is present then the sequence constructor must be empty, and if the sequence constructor is non-empty then the select attribute must be absent [see ERR XTSE3185]. If the select attribute is absent and the sequence constructor is empty, then the effective value is anthe empty sequence.
When an xsl:choose element is processed, each of the xsl:when elements is tested in turn (that is, in the order that the elements appear in the stylesheet), until one of the xsl:when elements is satisfied. If none of the xsl:when elements is satisfied, then the xsl:otherwise element is considered, as described below.
An xsl:when element is satisfied if the effective boolean valueXP of the expression in its test attribute is true. The rules for determining the effective boolean value of an expression are given in [XPath 4.0]: they are the same as the rules used for XPath conditional expressions.
The first, and only the first, xsl:when element that is satisfied is evaluated, and the resulting sequence (that is, the result of evaluating its select attribute or contained sequence constructor as appropriate) is returned as the result of the xsl:choose instruction. If no xsl:when element is satisfied, the content of the xsl:otherwise element is evaluated, and the resulting sequence is returned as the result of the xsl:choose instruction. If no xsl:when element is satisfied, and no xsl:otherwise element is present, the result of the xsl:choose instruction is anthe empty sequence.
The select expressions and sequence constructors of xsl:when and xsl:otherwise instructions after the selected one are not evaluated. The test expressions for xsl:when instructions after the selected one are not evaluated.
xsl:choose for formatting a numbered list Example: Using xsl:choose for formatting a numbered list 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.
<xsl:template match="orderedlist/listitem">
<fo:list-item indent-start='2pi'>
<fo:list-item-label>
<xsl:variable name="level"
select="count(ancestor::orderedlist) mod 3"/>
<xsl:choose>
<xsl:when test='$level=1'>
<xsl:number format="i"/>
</xsl:when>
<xsl:when test='$level=2'>
<xsl:number format="a"/>
</xsl:when>
<xsl:otherwise>
<xsl:number format="1"/>
</xsl:otherwise>
</xsl:choose>
<xsl:text>. </xsl:text>
</fo:list-item-label>
<fo:list-item-body>
<xsl:apply-templates/>
</fo:list-item-body>
</fo:list-item>
</xsl:template>
select attribute of xsl:when and xsl:otherwiseExample: Using the select attribute of xsl:when and xsl:otherwiseThe following example is equivalent to the one above:
<xsl:template match="orderedlist/listitem">
<fo:list-item indent-start='2pi'>
<fo:list-item-label>
<xsl:variable name="level"
select="count(ancestor::orderedlist) mod 3"/>
<xsl:variable name="format" as="xs:string">
<xsl:choose>
<xsl:when test='$level=1' select="'i'"/>
<xsl:when test='$level=2' select="'a'"/>
<xsl:otherwise select="'1'"/>
</xsl:choose>
</xsl:variable>
<xsl:number format="{ $format }"/>
<xsl:text>. </xsl:text>
</fo:list-item-label>
<fo:list-item-body>
<xsl:apply-templates/>
</fo:list-item-body>
</fo:list-item>
</xsl:template>xsl:switchChanges in 4.0 (next | previous)
A new xsl:switch instruction is introduced. [Issue 167 PR 237 25 November 2022]
<!-- Category: instruction -->
<xsl:switch
select = expression >
<!-- Content: (xsl:when+, xsl:otherwise?, xsl:fallback*) -->
</xsl:switch>
<xsl:when
test = expression
select? = expression >
<!-- Content: sequence-constructor -->
</xsl:when>
<xsl:otherwise
select? = expression >
<!-- Content: sequence-constructor -->
</xsl:otherwise>
The xsl:switch element selects one among a number of possible alternatives. The select attribute of the xsl:switch element is evaluated to obtain an atomic item, which is compared with the values given by the test attributes of the xsl:when elements, in turn.
The content of the xsl:switch element consists of a sequence of one or more xsl:when elements followed by an optional xsl:otherwise element. Each xsl:when element has an attribute, test, which contains an expression.
The result of an xsl:when or xsl:otherwise branch may be supplied using either a select attribute or a contained sequence constructor. These are mutually exclusive: if the select attribute is present then the sequence constructor must be empty, and if the sequence constructor is non-empty then the select attribute must be absent. If the select attribute is absent and the sequence constructor is empty, then the result is anthe empty sequence.
Any xsl:fallback 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 forwards compatible behavior.
An xsl:switch element is processed as follows:
The select expression of the xsl:switch element is evaluated.
The result of the evaluation is converted to a single atomic item by applying the coercion rules; a type error occurs if this conversion is not possible. This value is referred to below as the selector.
Each of the xsl:when elements is tested in turn (that is, in the order that the elements appear in the stylesheet), until one of the xsl:when elements is satisfied. If none of the xsl:when elements is satisfied, then the xsl:otherwise element is considered, as described below.
An xsl:when element is tested by first evaluating its test expression and converting the result to a sequence of atomic items by applying the coercion rules, and then comparing this sequence of atomic items with the selector value. The comparison is performed using the rules of the XPath = operator, using the default collation that is in scope for the xsl:switch instruction.
An xsl:when element is satisfied if the result of this comparison is true.
The first, and only the first, xsl:when element that is satisfied is evaluated, and the resulting sequence (that is, the result of evaluating its select attribute or contained sequence constructor as appropriate) is returned as the result of the xsl:switch instruction. If no xsl:when element is satisfied, the content of the xsl:otherwise element is evaluated, and the resulting sequence is returned as the result of the xsl:switch instruction. If no xsl:when element is satisfied, and no xsl:otherwise element is present, the result of the xsl:switch instruction is anthe empty sequence.
The select expressions and sequence constructors of xsl:when and xsl:otherwise instructions after the selected one are not evaluated. The test expressions for xsl:when instructions after the selected one are not evaluated.
Note:
There is no requirement that the values of select expressions should be literals, nor that the values should be distinct.
The following example shows a simple function to convert a month number to a month name:
<xsl:function name="f:month-name" as="xs:string">
<xsl:param name="month-number" as="xs:integer"/>
<xsl:switch select="$month-number">
<xsl:when test="1" select="'January'"/>
<xsl:when test="2" select="'February'"/>
<xsl:when test="3" select="'March'"/>
<xsl:when test="4" select="'April'"/>
<xsl:when test="5" select="'May'"/>
<xsl:when test="6" select="'June'"/>
<xsl:when test="7" select="'July'"/>
<xsl:when test="8" select="'August'"/>
<xsl:when test="9" select="'September'"/>
<xsl:when test="10" select="'October'"/>
<xsl:when test="11" select="'November'"/>
<xsl:when test="12" select="'December'"/>
<xsl:otherwise select="error('Unknown month')"/>
</xsl:switch>
</xsl:function>
xsl:switch to return the number of days in the monthExample: Using xsl:switch to return the number of days in the monthThis function returns the number of days in a month, returning anthe empty sequence if the supplied month is invalid.
<xsl:function name="f:days-in-month" as="xs:integer?">
<xsl:param name="month-number" as="xs:integer"/>
<xsl:param name="leap-year" as="xs:boolean"/>
<xsl:switch select="$month-number">
<xsl:when test="1, 3, 5, 7, 8, 10, 12" select="31"/>
<xsl:when test="4, 6, 9, 11" select="30"/>
<xsl:when test="2">
<xsl:if test="$leap-year" then="29" else="28"/>
</xsl:when>
</xsl:switch>
</xsl:function>The xsl:try 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 xsl:catch element.
<!-- Category: instruction -->
<xsl:try
select? = expression
rollback-output? = boolean〔'yes'〕 >
<!-- Content: (sequence-constructor, xsl:catch, (xsl:catch | xsl:fallback)*) -->
</xsl:try>
Note:
Because a sequence constructor may contain an xsl:fallback element, the effect of this content model is that an xsl:fallback instruction may appear as a child of xsl:try in any position.
<xsl:catch
errors? = tokens〔'*'〕
select? = expression >
<!-- Content: sequence-constructor -->
</xsl:catch>
An xsl:try instruction evaluates either the expression contained in its select attribute, or its contained sequence constructor, and returns the result of that evaluation if it succeeds without error. If a dynamic error occurs during the evaluation, the processor evaluates the first xsl:catch child element applicable to the error, and returns that result instead.
If the xsl:try element has a select attribute, then it must have no children other than xsl:catch and xsl:fallback. That is, the select attribute and the contained sequence constructor are mutually exclusive. If neither is present, the result of the xsl:try is anthe empty sequence (no dynamic error can occur in this case).
The rollback-output attribute is described in 8.4.1 Recovery of Result Trees. The default value is yes.
[ERR XTSE3140] It is a static error if the select attribute of the xsl:try element is present and the element has children other than xsl:catch and xsl:fallback elements.
Any xsl:fallback children of the xsl:try 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 forwards compatible behavior.
The xsl:catch element has an optional errors attribute, which lists the error conditions that the xsl:catch element is designed to intercept. The default value is errors="*", which catches all errors. The value is a whitespace-separated list of NameTestsXP; an xsl:catch element catches an error condition if this list includes a NameTest that matches the error code associated with that error condition.
Note:
Error codes are QNames. Those defined in this specification and in related specifications are all in the standard error namespace, and may therefore be caught using an xsl:catch element such as <xsl:catch errors="err:FODC0001 err:FODC0005"> where the namespace prefix err is bound to this namespace. Errors defined by implementers, and errors raised by an explicit call of the error function or by use of the xsl:message or xsl:assert instruction, may use error codes in other namespaces.
If more than one xsl:catch element matches an error, the error is processed using the first one that matches, in document order. If no xsl:catch matches the error, then the error is not caught (that is, evaluation of the xsl:try element fails with the dynamic error).
An xsl:catch element may have either a select attribute, or a contained sequence constructor.
[ERR XTSE3150] It is a static error if the select attribute of the xsl:catch element is present unless the element has empty content.
The result of evaluating the xsl:catch element is the result of evaluating the XPath expression in its select attribute or the result of evaluating the contained sequence constructor; if neither is present, the result is anthe empty sequence. This result is delivered as the result of the xsl:try instruction.
If a dynamic error occurs during the evaluation of xsl:catch, it causes the containing xsl:try to fail with this error. The error is not caught by other sibling xsl:catch elements within the same xsl:try instruction, but it may be caught by an xsl:try instruction at an outer level, or by an xsl:try instruction nested within the xsl:catch.
Within the select expression, or within the sequence constructor contained by the xsl:catch element, a number of variables are implicitly declared, giving information about the error that occurred. These are lexically scoped to the xsl:catch element. These variables are all in the standard error namespace, and they are initialized as described in the following table:
| Variable | Type | Value |
|---|---|---|
| err:code | xs:QName | The error code |
| err:description | xs:string? | A description of the error condition; anthe empty sequence if no description is available (for example, if the error function was called with one argument). |
| err:value | item()* | Value associated with the error. For an error raised by calling the error function, this is the value of the third argument (if supplied). For an error raised by evaluating xsl:message with terminate="yes", or a failing xsl:assert, this is the document node at the root of the tree containing the XML message body. |
| err:module | xs:string? | The URI (or system ID) of the stylesheet module containing the instruction where the error occurred; anthe empty sequence if the information is not available. |
| err:line-number | xs:integer? | The line number within the stylesheet module of the instruction where the error occurred; anthe empty sequence if the information is not available. The value may be approximate. |
| err:column-number | xs:integer? | The column number within the stylesheet module of the instruction where the error occurred; anthe empty sequence if the information is not available. The value may be approximate. |
| err:stack-trace | xs:string? | An implementation-dependent string containing diagnostic information about the state of execution at the point where the error occured, or anthe empty sequence if no stack trace is available. |
| err:additional | item()* | Additional implementation-defined information about the error. |
| err:map | map(xs:string, item()*) | 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. |
Variables declared within the sequence constructor of the xsl:try element (and not within an xsl:catch) are not visible within the xsl:catch element.
Note:
Within an xsl:catch it is possible to re-raise the error using the function call error($err:code, $err:description, $err:value).
The following additional rules apply to the catching of errors:
All dynamic errors occurring during the evaluation of the xsl:try sequence constructor or select expression are caught (provided they match one of the xsl:catch elements).
Note:
This includes errors occurring in functions or templates invoked in the course of this evaluation, unless already caught by a nested xsl:try.
It also includes (for example) errors caused by calling the error function, or the xsl:message instruction with terminate="yes", or the xsl:assert instruction, or the xs:error constructor function.
It does not include errors that occur while evaluating references to variables whose declaration and initialization is outside the xsl:try.
The existence of an xsl:try 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 type errors) statically or dynamically. Static errors are never caught.
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 xsl:try instruction. This is implementation-dependent.
If the sequence constructor or select expression of the xsl:try causes execution of xsl:result-document, xsl:message, or xsl:assert 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 not required to roll back any changes made by these instructions. The same applies to any side effects caused by extension functions or extension instructions.
A serialization error that occurs during the serialization of a secondary result produced using xsl:result-document is treated as a dynamic error in the evaluation of the xsl:result-document instruction, and may be caught (for example by an xsl:try instruction that contains the xsl:result-document instruction). A serialization error that occurs while serializing the principal result is treated as occurring after the transformation has finished, and cannot be caught.
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 validation="strict" on the instruction that creates the outermost html element, then a validation failure can be caught only at that level. Although the validation error might be detected, for example, while writing a p element at a location where no p element is allowed, it is not treated as an error in the instruction that writes the p element and cannot be caught at that level.
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.
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 C place requirements on the type of some subexpression, a type error is an error in the evaluation of C, not in the evaluation of the subexpression.
For example, consider the following construct:
<xsl:variable name="v" as="xs:integer"> <xsl:sequence select="$foo"/> </xsl:variable>
The expected type of the result of the sequence constructor is xs:integer; if the value of variable $foo turns out to be a string, then a type error will occur. It is not possible to catch this by writing:
<xsl:variable name="v" as="xs:integer">
<xsl:try>
<xsl:sequence select="$foo"/>
<xsl:catch>...</xsl:catch>
</xsl:try>
</xsl:variable>This fails to catch the error because the xsl:sequence instruction is deemed to evaluate successfully; the failure only occurs when the result of this instruction is bound to the variable.
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.
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.
Note:
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 $p + 1 where $p is a parameter of unknown type, and then catching the type error that occurs if $p is not numeric, it is better first to test whether $p is numeric, perhaps by means of an expression such as $p instance of my:numeric, where my:numeric is a union type with xs:double, xs:float, and xs:decimal as its member types.
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 exists(//a[10 div . gt 5]) 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.
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.
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.
The facilities are introduced first by example:
The following example generates an events element if and only if there are one or more event elements. The code could be written like this:
<xsl:if test="exists(event)">
<events>
<xsl:copy-of select="event"/>
</events>
</xsl:if>However, the above code would not be guaranteed-streamableSG, because it processes the child event elements more than once. To make it streamable, it can be rewritten as:
<xsl:where-populated>
<events>
<xsl:copy-of select="event"/>
</events>
</xsl:where-populated>The effect of the xsl:where-populated instruction, as explained later, is to avoid outputting the events element if it would have no children. A streaming implementation will typically hold the start tag of the events element in a buffer, to be sent to the output destination only if and when a child node is generated.
The following example generates an h3 element and a summary paragraph only if a list of items is non-empty. The code could be written like this:
<xsl:if test="exists(item-for-sale)">
<h1>Items for Sale</h1>
</xsl:if>
<xsl:apply-templates select="item-for-sale"/>
<xsl:if test="exists(item-for-sale)">
<p>Total value: {accumulator-before('total-value')}</p>
</xsl:if>However, the above code would not be guaranteed-streamableSG, because it processes the child item-for-sale elements more than once. To make it streamable, it can be rewritten as:
<xsl:sequence>
<xsl:on-non-empty>
<h1>Items for Sale</h1>
</xsl:on-non-empty>
<xsl:apply-templates select="item-for-sale"/>
<xsl:on-non-empty>
<p>Total value: {accumulator-before('total-value')}</p>
</xsl:on-non-empty>
</xsl:sequence>The effect of the xsl:on-non-empty 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 xsl:on-empty and xsl:on-non-empty instructions.
The following example generates a summary paragraph only if a list of items is empty. The code could be written like this:
<xsl:apply-templates select="item-for-sale"/> <xsl:if test="empty(item-for-sale)"> <p>There are no items for sale.</p> </xsl:if>
However, the above code would not be guaranteed-streamableSG, because it processes the child item-for-sale 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:
<xsl:sequence>
<xsl:apply-templates select="item-for-sale"/>
<xsl:on-empty>
<p>There are no items for sale.</p>
</xsl:on-empty>
</xsl:sequence>The effect of the xsl:on-empty 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 xsl:on-empty and xsl:on-non-empty instructions.
For further examples showing the use of these instructions when streaming, see 7 Handling Empty InputSG.
xsl:where-populated instruction<!-- Category: instruction -->
<xsl:where-populated>
<!-- Content: sequence-constructor -->
</xsl:where-populated>
The xsl:where-populated instruction encloses a sequence constructor. The result of the instruction is established as follows:
The sequence constructor is evaluated in the usual way (taking into account any xsl:on-empty and xsl:on-non-empty instructions) to produce a result $R.
The result of the instruction is the value of the expression $R[not(deemed-empty(.))] where the function deemed-empty($item as item()) returns true if and only if $item is one of the following:
A document or element node that has no children.
Note:
If an element has attributes or namespaces, these do not prevent the element being deemed empty.
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 xsl:variable instruction in the form <xsl:variable name="temp"><a/></xsl:variable> is not deemed empty, even though the contained <a/> element is empty.
A node, other than a document or element node, whose string value is zero-length.
Note:
A whitespace-only text node is not deemed empty.
An atomic item such that the result of casting the atomic item to a string is zero-length.
Note:
This can happen only when the atomic item is of type xs:string, xs:anyURI, xs:untypedAtomic, xs:hexBinary, or xs:base64Binary.
A map whose size (number of key/value pairs) is zero.
An array (see 22 Arrays) where the result of flattening the array using the array:flatten function is either anthe empty sequence, or a sequence in which every item is deemed empty (applying these rules recursively).
The following example generates an HTML unnumbered list, if and only if the list is non-empty. Note that the presence of the class attribute does not make the list non-empty. The code is written to be streamable.
<xsl:where-populated expand-text="yes">
<ul class="my-list">
<xsl:for-each select="source-item">
<li>{.}</li>
</xsl:for-each>
</ul>
</xsl:where-populated>xsl:on-empty instruction<!-- Category: instruction -->
<xsl:on-empty
select? = expression >
<!-- Content: sequence-constructor -->
</xsl:on-empty>
The xsl:on-empty instruction has the same content model as xsl:sequence, and when it is evaluated, the same rules apply. In particular, the select attribute and the contained sequence constructor are mutually exclusive [see ERR XTSE3185].
When an xsl:on-empty instruction appears in a sequence constructor, then:
It must be the only xsl:on-empty instruction in the sequence constructor, and
It must not be followed in the sequence constructor by any other instruction, other than xsl:fallback, or by a significant text node (that is, a text node that has not been discarded under the provisions of 3.12.1 Stripping Whitespace and Commentary from the Stylesheet), or by a literal result element. It may, however, be followed by non-instructions such as xsl:catch where appropriate.
[Definition: An item is vacuous 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 xs:string, produces a zero-length string; or an array which on flattening using the array:flatten function produces either anthe empty sequence or a sequence consisting entirely of vacuous items.]
An xsl:on-empty instruction is triggered only if every preceding sibling instruction, text node, and literal result element in the same sequence constructor returns either anthe empty sequence, or a sequence consisting entirely of vacuous items.
If an xsl:on-empty instruction is triggered, then the result of the containing sequence constructor is the result of the xsl:on-empty instruction.
Note:
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.
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.
Note:
In nearly all cases, the rules for xsl:on-empty are aligned with the rules for constructing complex content. If the sequence constructor within a literal result element or an xsl:element instruction includes an xsl:on-empty instruction, then the content of the element will be the value delivered by the xsl:on-empty instruction if and only if the content would otherwise be empty.
There is one minor exception to this rule: if the sequence constructor delivers multiple zero-length strings, then in the absence of the xsl:on-empty instruction the new element would contain whitespace, made up of the separators between these zero-length strings; but xsl:on-empty takes no account of these separators.
Note:
Attribute and namespace nodes created by the sequence constructor are significant; the xsl:on-empty 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 xsl:on-empty, for example:
<ol>
<xsl:attribute name="class" select="numbered-list"/>
<xsl:sequence>
<xsl:value-of select="xyz"/>
<xsl:on-empty select="'The list is empty'"/>
</xsl:sequence>
</ol>Note:
Where the sequence constructor is a child of an instruction with an [xsl:]use-attribute-sets 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 xsl:on-empty or xsl:on-non-empty instruction is triggered. Equally, when the sequence constructor is a child of a literal result element, attribute nodes generated by expanding the attributes of the literal result element are not taken into account.
Note:
If xsl:on-empty is the only instruction in a sequence constructor then it is always evaluated.
If xsl:on-empty and xsl:on-non-empty appear in the same sequence constructor, then the rules ensure that only one of them will be evaluated.
[Definition: The two elements xsl:variable and xsl:param are referred to as variable-binding elements.]
[Definition: The xsl:variable element declares a variable, which may be a global variable or a local variable.]
[Definition: The xsl:param element declares a parameter, which may be a stylesheet parameter, a template parameter, a function parameter, or an xsl:iterate parameter. A parameter is a variable with the additional property that its value can be set by the caller.]
[Definition: A variable is a binding between a name and a value. The value of a variable is any sequence (of nodes, atomic items, and/or function items), as defined in [XDM 4.0].]
<!-- Category: declaration -->
<xsl:param
name = eqname
select? = expression
as? = sequence-type
required? = boolean
tunnel? = boolean〔'no'〕
static? = boolean〔'no'〕 >
<!-- Content: sequence-constructor -->
</xsl:param>
The xsl:param element may be used:
As a child of xsl:stylesheet or xsl:package, to define a parameter to the transformation. Stylesheet parameters are set by the calling application: see 2.3.2 Priming a Stylesheet.
As a child of xsl:template to define a parameter to a template, which may be supplied when the template is invoked using xsl:call-template, xsl:apply-templates, xsl:apply-imports or xsl:next-match. Template parameters are set by means of an xsl:with-param child element of the invoking instruction, as described in 9.10 Setting Parameter Values.
As a child of xsl:function to define a parameter to a stylesheet function, which may be supplied when the function is called from an XPath expression. Function parameters are set either positionally or by keyword by means of the argument list in an XPath function call.
As a child of xsl:iterate 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 xsl:with-param child of the xsl:next-iteration instruction.
The attributes applicable to xsl:param depend on its parent element in the stylesheet, as defined by the following table:
| Parent Element | name | select | as | required | tunnel | static |
|---|---|---|---|---|---|---|
xsl:package | mandatory | optional | optional | yes|no | no | yes|no |
xsl:stylesheet | mandatory | optional | optional | yes|no | no | yes|no |
xsl:template | mandatory | optional | optional | yes|no | yes|no | no |
xsl:function | mandatory | optional | optional | yes|no | no | no |
xsl:iterate | mandatory | mandatory | optional | no | no | no |
In the table, the entries for the name, select, and as attributes indicate whether the attribute must appear, is optional, or must be absent; the entries for the required, tunnel, and static attributes indicate the values that are permitted if the attribute is present, with the default value shown in bold. (The value yes can also be written true or 1, while no can also be written false or 0.)
The name attribute is mandatory: it specifies the name of the parameter. The value of the name attribute is an EQName, which is expanded as described in 5.1.1 Qualified Names.
[ERR XTSE0580] It is a static error if the values of the name attribute of two sibling xsl:param elements represent the same expanded QName.
If the xsl:param element has a select attribute, then the sequence constructor must be empty.
The static attribute can take the value yes only on stylesheet parameters, and is explained in 9.5 Global Variables and Parameters.
Note:
Local variables may shadow template parameters and function parameters: see 9.9 Scope of Variables.
The optional tunnel attribute may be used to indicate that a parameter is a tunnel parameter. The default is no; the value yes may be specified only for template parameters. Tunnel parameters are described in 10.1.6 Tunnel Parameters
The xsl:param element has an optional as attribute, which specifies the required type of the parameter. The value of the as attribute is a SequenceType. If the as attribute is omitted, then the required type is item()*.
The supplied value 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 9.2.2 Default Values of Parameters.
The supplied value of the parameter is converted to the required type using the coercion rules.
[ERR XTTE0590] It is a type error if the conversion of the supplied value of a parameter, or of the context item, does not match the required type, after applying any permitted conversions.
For example, the following declares a parameter that requires the supplied value (after atomization) to be either a QName, or the string "*", or anthe empty sequence:
<xsl:param name="n" as="(xs:QName | enum('*'))?"/>Changes in 4.0 (next | previous)
A variable-binding with no as or select attribute no longer attempts to create an implicit document node if the sequence constructor contains certain instructions (such as xsl:map, xsl:array, xsl:record, and xsl:select). [Issues 2009 2288 PRs 2015 2296 20 May 2025]
A variable-binding element may specify the supplied value of a variable or the default value of a parameter in four different ways.
If the variable-binding element has a select attribute, then the value of the attribute must be an expression and the supplied value of the variable is the value that results from evaluating the expression. In this case, the content of the variable-binding element must be empty.
If the variable-binding element has empty content and has neither a select attribute nor an as attribute, then the supplied value of the variable is a zero-length string. Thus
<xsl:variable name="x"/>
is equivalent to
<xsl:variable name="x" select="''"/>
If a variable-binding element satisfies all the following conditions:
The element has no select attribute
The element has no as attribute
The element has non-empty content (that is, the variable-binding element has one or more child nodes)
There is no disqualifying element among the element's children.
then the content of the variable-binding element specifies the supplied value. The content of the variable-binding element is a sequence constructor; 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 5.7.1 Constructing Complex Content. The value of the variable is then a singleton sequence containing this document node. For further details, see 9.4 Creating Implicit Document Nodes.
Otherwise, the supplied value is the sequence that results from evaluating the (possibly empty) sequence constructor contained within the variable-binding element (see 5.7 Sequence Constructors).
These combinations are summarized in the table below.
| select attribute | as attribute | content | Effect |
|---|---|---|---|
| present | absent | empty | Value is obtained by evaluating the select attribute |
| present | present | empty | Value is obtained by evaluating the select attribute, coerced to the type required by the as attribute |
| present | absent | present | Static error |
| present | present | present | Static error |
| absent | absent | empty | Value is a zero-length string |
| absent | present | empty | Value is anthe empty sequence, provided the as attribute permits anthe empty sequence |
| absent | absent | includes a disqualifying element | Value is obtained by evaluating the sequence constructor |
| absent | absent | present and does not include a disqualifying element | Value is a document node whose content is obtained by evaluating the sequence constructor |
| absent | present | present | Value is obtained by evaluating the sequence constructor, coerced to the type required by the as attribute |
[ERR XTSE0620] It is a static error if a variable-binding element has a select attribute and has non-empty content.
The value of the following variable is the sequence of integers (1, 2, 3):
<xsl:variable name="i" as="xs:integer*" select="1 to 3"/>
The value of the following variable is an integer, assuming that the attribute @size exists, and is annotated either as an integer, or as xs:untypedAtomic:
<xsl:variable name="i" as="xs:integer" select="@size"/>
The value of the following variable is a zero-length string:
<xsl:variable name="z"/>
The value of the following variable is a document node containing an empty element as a child:
<xsl:variable name="doc"><c/></xsl:variable>
The value of the following variable is a sequence of integers (2, 4, 6):
<xsl:variable name="seq" as="xs:integer*">
<xsl:for-each select="1 to 3">
<xsl:sequence select=".*2"/>
</xsl:for-each>
</xsl:variable>The value of the following variable is a sequence of parentless attribute nodes:
<xsl:variable name="attset" as="attribute()+"> <xsl:attribute name="x">2</xsl:attribute> <xsl:attribute name="y">3</xsl:attribute> <xsl:attribute name="z">4</xsl:attribute> </xsl:variable>
The value of the following variable is anthe empty sequence:
<xsl:variable name="empty" as="empty-sequence()"/>
The actual value of the variable depends on the supplied value, as described above, and the required type, which is determined by the value of the as attribute.
When a variable is used to select nodes by position, be careful not to do:
<xsl:variable name="n">2</xsl:variable> ... <xsl:value-of select="td[$n]"/>
This will output the values of all the td elements, space-separated (or with XSLT 1.0 behavior, the value of the first td element), because the variable n will be bound to a node, not a number. Instead, do one of the following:
<xsl:variable name="n" select="2"/> ... <xsl:value-of select="td[$n]"/>
or
<xsl:variable name="n">2</xsl:variable> ... <xsl:value-of select="td[position()=$n]"/>
or
<xsl:variable name="n" as="xs:integer">2</xsl:variable> ... <xsl:value-of select="td[$n]"/>
[Definition: As well as being allowed as a declaration, the xsl:variable element is also allowed in sequence constructors. Such a variable is known as a local variable.]
An xsl:param element may also be used to create a variable binding with local scope:
[Definition: An xsl:param element may appear as a child of an xsl:template element, before any non-xsl:param children of that element. Such a parameter is known as a template parameter. A template parameter is a local variable with the additional property that its value can be set when the template is called, using any of the instructions xsl:call-template, xsl:apply-templates, xsl:apply-imports, or xsl:next-match.]
[Definition: An xsl:param element may appear as a child of an xsl:function element, before any non-xsl:param children of that element. Such a parameter is known as a function parameter. A function parameter is a local variable with the additional property that its value can be set when the function is called, using a function call in an XPath expression.]
An xsl:param element may appear as a child of an xsl:iterate instruction, before any non-xsl:param 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 xsl:with-param element in the xsl:next-iteration instruction.
The result of evaluating a local xsl:variable or xsl:param element (that is, the contribution it makes to the result of the sequence constructor it is part of) is anthe empty sequence.
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 10.1 Named Templates), named attribute sets (see 10.2 Named Attribute Sets), and stylesheet functions (see 10.3 Stylesheet Functions).
[Definition: The following constructs are classified as invocation constructs: the instructions xsl:call-template, xsl:apply-templates, xsl:apply-imports, and xsl:next-match; XPath function calls that bind to stylesheet functions; XPath dynamic function calls; the functions accumulator-before and accumulator-after; the [xsl:]use-attribute-sets attribute. These all have the characteristic that they can cause evaluation of constructs that are not lexically contained within the calling construct.]
Changes in 4.0 (next | previous)
Parameters on functions declared using xsl:function can now be defined as optional, with a default value supplied. [Issue 155 PR 159 30 September 2022]
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 fn namespace. [Issue 657 PR 2200 23 September 2025]
[Definition: An xsl:function declaration declares the name, parameters, and implementation of a family of stylesheet functions that can be called from any XPath expression within the stylesheet (subject to visibility rules).]
<!-- Category: declaration -->
<xsl:function
name = eqname
as? = sequence-type〔'item()*'〕
visibility? = "public" | "private" | "final" | "abstract"〔'private'〕
streamability? = "unclassified" | "absorbing" | "inspection" | "filter" | "shallow-descent" | "deep-descent" | "ascent" | eqname〔'unclassified'〕
override-extension-function? = boolean〔'yes'〕
[override]? = boolean〔'yes'〕
new-each-time? = "yes" | "true" | "1" | "no" | "false" | "0" | "maybe"
cache? = boolean〔'no'〕 >
<!-- Content: (xsl:param*, sequence-constructor) -->
</xsl:function>
The effect of an xsl:function declaration is to add a function definition to the static context for all XPath expressions used in the stylesheet (including an XPath expression used within a predicate in a pattern).
The content of the xsl:function element consists of zero or more xsl:param elements that specify the formal parameters of the function, followed by a sequence constructor that defines the value to be returned by the function.
The children and attributes of the xsl:function declaration translate directly into properties of the function definition:
The xsl:function/@name attribute defines the function’s name.
The xsl:param children define the function’s parameters:
The xsl:param/@name attribute defines the name of the parameter.
The xsl:param/@required attribute determines whether the parameter is mandatory or optional.
The xsl:param/@as attribute determines the required type of the parameter.
The xsl:param/@select attribute determines a default value for an optional parameter.
The xsl:function/@as attribute defines the return type of the function.
The implementation of the function is defined by the sequence constructor content of the xsl:function element.
An xsl:function declaration can only appear as a top-level element in a stylesheet module.
The name of the function is given by the name attribute.
[ERR XTSE0740] It is a static error if a stylesheet function has a name that is in no namespace, unless the visibility of the function is private.
Note:
XSLT 4.0 allows the function name to be unprefixed, provided that its visibility is private. 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 fn namespace.
Note:
To prevent the namespace URI used for the function name appearing in the result document, use the exclude-result-prefixes attribute on the xsl:stylesheet element: see 11.1.3 Namespace Nodes for Literal Result Elements.
The name of the function must not be in a reserved namespace: [see ERR XTSE0080]
The function parameters are defined by child xsl:param 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 required="no"; otherwise, it is required.
The default value for an optional parameter can be defined using the select attribute or the contained sequence constructor of the xsl:param element. These must be absent for a required parameter. If an optional parameter has no select attribute and the contained sequence constructor is empty, then the default value will be anthe empty sequence. This will lead to a type error if the required type of the parameter does not permit anthe empty sequence.
Note:
When considering function overriding, dynamic function calls, and details such as the function-lookup function, it is useful to think of an xsl:function declaration with optional parameters as a syntactic short-cut for a set of xsl:function 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.
This is not an exact equivalence, however, because of the rules allowing default values of function parameters to be context-dependent.
The function definition derived from the xsl:function declaration has an arity range from M to M+N, where M is the number of required parameters and N is the number of optional parameters. The arity range constrains the number of arguments that may appear in a call to this function.
For example, the following xsl:function declaration declares a function, named f:compare, with an arity range of (2 to 3). The effect of calling f:compare($a, $b) is the same as the effect of calling f:compare($a, $b, { "order": "ascending" }).
<xsl:function name="f:compare" as="xs:boolean">
<xsl:param name="arg1" as="xs:double"/>
<xsl:param name="arg2" as="xs:double"/>
<xsl:param name="options" as="map(*)"
required="no"
select="{ 'order': 'ascending' }"/>
<xsl:if test="$options?order = 'descending'"
then="$arg1 gt $arg2"
else="$arg2 gt $arg1"/>
</xsl:function>Note:
Functions are not polymorphic. Although the XPath function call mechanism allows two functions to have the same name and non-overlapping arity ranges, it does not allow them to be distinguished by the types of their arguments.
The two instructions described in this section, xsl:sequence and xsl:select, 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 xsl:sequence instruction can also be used to evaluate a sequence constructor.
xsl:sequence InstructionChanges in 4.0 (next | previous)
An as attribute is available on the xsl:sequence instruction. [Issue 46 PR 1306 27 June 2024]
<!-- Category: instruction -->
<xsl:sequence
select? = expression
as? = sequence-type〔'item()*'〕 >
<!-- Content: sequence-constructor -->
</xsl:sequence>
The xsl:sequence instruction may be used within a sequence constructor 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, xsl:sequence can return a sequence containing existing nodes, rather than constructing new nodes. When xsl:sequence is used to select atomic items or function items, the effect is very similar to the xsl:copy-of instruction.
The select attribute and the contained sequence constructor are mutually exclusive; if the instruction has a select attribute, then it must have no children other than xsl:fallback instructions. If there is no select attribute and no contained sequence constructor, the result is anthe empty sequence.
The effect of the instruction is as follows:
Evaluate the expression in the select attribute if present, or the contained sequence constructor otherwise. Call the result T.
Use the coercion rules to convert T to the sequence type appearing in the as attribute, defaulting to item()*. The converted result is the value returned by the xsl:sequence instruction.
[ERR XTSE3185] For the elements xsl:sequence, xsl:on-empty, xsl:on-non-empty, xsl:when, xsl:otherwise, xsl:matching-substring, xsl:non-matching-substring, xsl:map, xsl:map-entry, xsl:array, xsl:array-member, and xsl:result-document, it is a static error if the select attribute is present and the instruction has children other than xsl:fallback.
Note:
The xsl:sequence instruction was first introduced in XSLT 2.0, so the xsl:fallback instruction is relevant only to an XSLT 1.0 processor operating in forwards compatibility mode.
An XSLT 2.0 or 3.0 processor operating in forwards compatibility mode will ignore the @as attribute.
Note:
The xsl:sequence instruction is most commonly used as the final instruction in the body of xsl:function, to compute the result of the function. If the result is a single item, consider writing <xsl:sequence select="..." as="item()"/> to make this clear to the reader.
Note:
The main use case for allowing xsl:sequence to contain a sequence constructor is to allow the instructions within an xsl:fork element to be divided into groups.
It can also be used to limit the scope of local variables or of standard attributes such as [xsl:]default-collation.
The following code:
<xsl:variable name="values" as="xs:integer*">
<xsl:sequence select="(1,2,3,4)"/>
<xsl:sequence select="(8,9,10)"/>
</xsl:variable>
<xsl:value-of select="sum($values)"/>produces the output: 37
xsl:for-each to Construct a SequenceExample: Using xsl:for-each to Construct a SequenceThe following code constructs a sequence containing the value of the @price attribute for selected elements, or a computed price for those elements that have no @price attribute:
<xsl:variable name="prices" as="xs:decimal*">
<xsl:for-each select="//product">
<xsl:sequence select="@price otherwise @cost * 1.5" as="xs:decimal"/>
</xsl:for-each>
</xsl:variable>Note that the existing @price attributes could equally have been added to the $prices sequence using xsl:copy-of or xsl:value-of. However, xsl:copy-of would create a copy of the attribute node, which is not needed in this situation, while xsl:value-of would create a new text node, which then has to be converted to an xs:decimal. Using xsl:sequence, which in this case atomizes the existing attribute node and adds an xs:decimal atomic item to the result sequence, is a more direct way of achieving the same result.
This example could alternatively be solved at the XPath level:
<xsl:sequence select="//product/(+@price otherwise @cost*1.5))"/>
or, in XSLT 4.0:
<xsl:select>//product/(+@price otherwise @cost*1.5))</xsl:select>
The apparently redundant + operator is there to atomize the attribute value: the expression on the right hand side of the / operator must not return a sequence containing both nodes and non-nodes (atomic items or function items).
This section describes instructions that directly create new nodes.
<!-- Category: instruction -->
<xsl:copy
select? = expression
copy-namespaces? = boolean〔'yes'〕
inherit-namespaces? = boolean〔'yes'〕
use-attribute-sets? = eqnames〔''〕
type? = eqname
validation? = "strict" | "lax" | "preserve" | "strip" >
<!-- Content: sequence-constructor -->
</xsl:copy>
The xsl:copy instruction provides a way of copying a selected item. The selected item is the item selected by evaluating the expression in the select attribute if present, or the context item otherwise. If the selected item is a node, evaluating the xsl:copy instruction constructs a copy of the selected node, and the result of the xsl:copy 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.
[ERR XTTE0945] It is a type error to use the xsl:copy instruction with no select attribute when the context item is absent.
If the select expression returns anthe empty sequence, the xsl:copy instruction returns anthe empty sequence, and the contained sequence constructor is not evaluated.
[ERR XTTE3180] It is a type error if the result of evaluating the select expression is a sequence of more than one item.
When the selected item is an atomic item or function item, the xsl:copy instruction returns this value. The sequence constructor is not evaluated.
When the selected item is an attribute node, text node, comment node, processing instruction node, or namespace node, the xsl:copy 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 is-id and is-idrefs properties. The sequence constructor is not evaluated.
When the selected item is a document node or element node, the xsl:copy 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 sequence constructor contained in the xsl:copy instruction. If the select attribute is present then the sequence constructor is evaluated with the selected item as the singleton focus; otherwise it is evaluated using the context of the xsl:copy 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 5.7.1 Constructing Complex Content.
When the selected item is a document node, the unparsed-entities property of the existing document node is copied to the new document node.
When the selected item is an element or attribute node, the values of the is-id, is-idrefs, and nilled properties of the new element or attribute depend on the values of the validation and type attributes, as defined in 25.4 Validation.
The xsl:copy instruction has an optional use-attribute-sets attribute, whose value is a whitespace-separated list of QNames that identify xsl:attribute-set declarations. This attribute is used only when copying element nodes. This list is expanded as described in 10.2 Named Attribute Sets to produce a sequence of attribute nodes. This sequence is prepended to the sequence produced as a result of evaluating the sequence constructor.
The xsl:copy instruction has an optional copy-namespaces attribute, with the value yes or no. The default value is yes. The attribute is used only when copying element nodes. If the value is set to yes, 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 sequence constructor (it is immaterial whether they come before or after any attribute nodes produced by expanding the use-attribute-sets attribute). If the value is set to no, then the namespace nodes are not copied. However, namespace nodes will still be added to the result element as required by the namespace fixup process: see 5.7.3 Namespace Fixup.
The xsl:copy instruction has an optional inherit-namespaces attribute, with the value yes or no. The default value is yes. The attribute is used only when copying element nodes. If the value is set to yes, 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 5.7.1 Constructing Complex Content. If the value is set to no, then these namespace nodes are not automatically copied to the children. This may result in namespace undeclarations (such as xmlns="" or, in the case of XML Namespaces 1.1, xmlns:p="") appearing on the child elements when a final result tree is serialized.
[ERR XTTE0950] It is a type error to use the xsl:copy or xsl:copy-of instruction to copy a node that has namespace-sensitive content if the copy-namespaces attribute has the value no and its explicit or implicit validation attribute has the value preserve. It is also a type error if either of these instructions (with validation="preserve") 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 xs:QName or xs:NOTATION 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.
Note:
When attribute nodes are copied, whether with xsl:copy or with xsl:copy-of, 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 5.7.3 Namespace Fixup) when the attribute is added to an element in the result tree, 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 result tree. This can be achieved by copying the namespace nodes using xsl:copy, or by generating them using xsl:namespace.
The optional attributes type and validation may be used on the xsl:copy 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 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 must be omitted. The permitted values of these attributes and their semantics are described in 25.4 Validation.
Note:
The final type annotation of the node in the result tree also depends on the type and validation attributes of the instructions used to create the ancestors of the node.
When a node is copied, its base URI is copied, except when the result of the xsl:copy instruction is an element node having an xml:base attribute, in which case the base URI of the new node is taken as the value of its xml:base attribute, resolved if it is relative against the base URI of the xsl:copy instruction.
When an xml:id attribute is copied, using either the xsl:copy or xsl:copy-of instruction, it is implementation-defined whether the value of the attribute is subjected to attribute value normalization (that is, effectively applying the normalize-space function).
Note:
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.
[Definition: A sort key specification is a sequence of one or more adjacent xsl:sort elements which together define rules for sorting the items in an input sequence to form a sorted sequence.]
[Definition: Within a sort key specification, each xsl:sort element defines one sort key component.] The first xsl:sort element specifies the primary component of the sort key specification, the second xsl:sort element specifies the secondary component of the sort key specification, and so on.
A sort key specification may occur immediately within an xsl:apply-templates, xsl:for-each, xsl:perform-sort, or xsl:for-each-group element.
Note:
When used within xsl:for-each, xsl:for-each-group, or xsl:perform-sort, xsl:sort elements must occur before any other children.
<!-- Category: instruction -->
<xsl:perform-sort
select? = expression >
<!-- Content: (xsl:sort+, sequence-constructor) -->
</xsl:perform-sort>
The xsl:perform-sort instruction is used to return a sorted sequence.
The initial sequence is obtained either by evaluating the select attribute or by evaluating the contained sequence constructor (but not both). If there is no select attribute and no sequence constructor then the initial sequence (and therefore, the sorted sequence) is anthe empty sequence.
[ERR XTSE1040] It is a static error if an xsl:perform-sort instruction with a select attribute has any content other than xsl:sort and xsl:fallback instructions.
The result of the xsl:perform-sort instruction is the result of sorting its initial sequence using its contained sort key specification.
The following stylesheet function sorts a sequence of atomic items using the value itself as the sort key.
<xsl:function name="local:sort"
as="xs:anyAtomicType*">
<xsl:param name="in" as="xs:anyAtomicType*"/>
<xsl:perform-sort select="$in">
<xsl:sort select="."/>
</xsl:perform-sort>
</xsl:function>
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:
<xsl:function name="bib:books-by-price"
as="schema-element(bib:book)*">
<xsl:param name="in" as="schema-element(bib:book)*"/>
<xsl:perform-sort select="$in">
<xsl:sort select="xs:decimal(bib:price)"/>
</xsl:perform-sort>
</xsl:function>
...
<xsl:copy-of select="bib:books-by-price(//bib:book)
[position() = 1 to 5]"/>Changes in 4.0 (next | previous)
A new attribute xsl:for-each-group/@split-when is available to give applications more complete control over how a sequence is partitioned [Issue 571 PR 740 26 September 2023]
A new attribute xsl:for-each-group/@merge-when is available to give applications control to create groups based on clustering, overlap, and networks. [Issue 2051 PR 2123 30 September 2025]
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 expression. 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.
Note:
Simple elimination of duplicates can also be achieved using the function distinct-values: see [Functions and Operators 4.0].
In addition these facilities allow grouping based on sequential position, for example selecting groups of adjacent para 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.
For each group of items identified, it is possible to evaluate a sequence constructor 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.
It is also possible for one item to participate in more than one group.
Note:
Grouping can also be achieved by constructing a map. For example, the function call map:build(//employee, fn { department }) constructs a map in which employees are grouped by department.
xsl:for-each-group ElementThe xsl:for-each-groupinstruction 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 sequence constructor.
<!-- Category: instruction -->
<xsl:for-each-group
select = expression
group-by? = expression
group-adjacent? = expression
group-starting-with? = pattern
group-ending-with? = pattern
split-when? = expression
merge-when? = expression
composite? = boolean〔'no'〕
collation? = { uri } >
<!-- Content: (xsl:sort*, sequence-constructor) -->
</xsl:for-each-group>
The select attribute contains an expression which is evaluated to produce a sequence, called the population.
[Definition: The xsl:for-each-group instruction allocates the items in an input sequence into groups of items (that is, it establishes a collection of sequences) based either on common values of a grouping key, or on a pattern that the initial or final item in a group must match.] The sequence constructor that forms the content of the xsl:for-each-group instruction is evaluated once for each of these groups.
[Definition: The sequence of items to be grouped, which is referred to as the population, is determined by evaluating the XPath expression contained in the select attribute.]
[Definition: The population is treated as a sequence; the order of items in this sequence is referred to as population order.]
A group is never empty. If the population is empty, the number of groups will be zero.
The assignment of items to groups depends on the group-by, group-adjacent, group-starting-with, group-ending-with, split-when,and merge-when attributes.
[ERR XTSE1080] These six attributes are mutually exclusive: it is a static error if none of these attributes is present or if more than one of them is present.
[ERR XTSE1090] It is a static error to specify the collation attribute or the composite attribute if neither the group-by attribute nor the group-adjacent attribute is specified.
[Definition: If the group-by or group-adjacent attributes is present, then for each item in the population a set of grouping keys is calculated, as follows: the expression contained in the group-by or group-adjacent attribute is evaluated; the result is atomized; and any xs:untypedAtomic items are cast to xs:string. If composite="yes" 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.]
When calculating grouping keys for an item in the population, the expression contained in the group-by or group-adjacent attribute is evaluated with that item as the context item, with its position in population order as the context position, and with the size of the population as the context size.
If the group-by attribute is present, and if the composite attribute is omitted or takes the value no, then an item in the population may have multiple grouping keys: that is, the group-by 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).
If the group-adjacent attribute is used, and if the composite attribute is omitted or takes the value no, then each item in the population must have exactly one grouping key value.
[ERR XTTE1100] It is a type error if the result of evaluating the group-adjacent expression is anthe empty sequence or a sequence containing more than one item, unless composite="yes" is specified.
Atomic grouping keys are compared using the rules of the distinct-values function, using the relevant collation. The relevant collation is the collation specified as the effective value of the collation attribute, resolved if relative against the base URI of the xsl:for-each-group element; if there is no collation attribute then the default collation is used. Given this collation, two grouping keys K1 and K2 are considered equal if count(distinct-values(($K1, $K2), $collation)) = 1.
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.
[ERR XTDE1110] It is a dynamic error if the collation URI specified to xsl:for-each-group (after resolving against the base URI) is a collation that is not recognized by the implementation. (For notes, [see ERR XTDE1035].)
For more information on collations, see 13.1.3 Sorting Using Collations.
The way in which an xsl:for-each-group element is evaluated depends on which of the six group-defining attributes is present:
If the group-by attribute is present, the items in the population are examined, in population order. For each item J, the expression in the group-by attribute is evaluated to produce a sequence of zero or more grouping key values. If composite="yes" 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 grouping keys, if there is already a group created to hold items having that grouping key value, J is appended to that group; otherwise a new group is created for items with that grouping key value, and J becomes its first member.
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 item 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.
The number of groups will be the same as the number of distinct grouping key values present in the population.
If the group-adjacent attribute is present, the items in the population are examined, in population order. If an item has the same value for the grouping key as its preceding item within the population (in population order), 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.
If the group-starting-with attribute is present, then its value must be a pattern.
The items in the population are examined in population order. 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.
If the group-ending-with attribute is present, then its value must be a pattern.
The items in the population are examined in population order. 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.
If the split-when attribute is present, then its value must be an expression. This expression is evaluated once for every item in the population except the first. The context item is that item, the context position is its position in the population, and the context size is the size of the population. The expression is supplied with two variables: $group is set to the contents of the current group being constructed, and $next is the next item in the population. If the effective boolean valueXP of the expression is true, then this item forms the start of a new group; if it is false, the item is added to the existing group.
The variable $group is implicitly declared, and shadows any other variable of the same name. Its name is in no namespace. Its scope is the split-when expression, and its type is item()+.
The variable $next is implicitly declared, and shadows any other variable of the same name. Its name is in no namespace. Its scope is the split-when expression, and its type is item().
For example:
split-when="count($group) = 3" 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).
split-when="$next[self::h1]" starts a new group whenever an h1 element is encountered. The effect is the same as specifying group-starting-with="h1"
split-when="foot($group)/@continued='no'" starts a new group immediately after any element having @continued="no". The effect is the same as specifying group-ending-with="*[@continued='no']"
split-when="node-name($group[last()] != node-name($next)" 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 group-adjacent="node-name(.)".
split-when="foot($group)[self::hr] or $next[self::hr]" starts a new group immediately before and immediately after every hr element. (That is, hr elements become singleton groups.)
split-when="$next ne foot($group) + 1" starts a new group whenever the current item is not equal to the previous item plus one. For example 1, 2, 5, 6, 7, 10, 11 is grouped as (1, 2), (5, 6, 7), (10, 11).
split-when="sum($group/string-length()) gt 40" starts a new group when the sum of the string lengths of the items in the current group exceeds 40.
split-when="ends-with(foot($group), '.') and matches($next, '^\p{Lu}')" starts a new group when the last item in the current group ends with "." and the next item starts with a capital letter.
split-when="deep-equal(slice($group, -2 to -1), ('', ''))" starts a new group after two consecutive zero-length strings.
split-when="count($group) gt 1 and head($group)/@name = foot($group)/@name" starts a new group if the last item in the current group has the same value for @name as the first item in that group (provided they are not the same item).
If the merge-when attribute is present, then its value must be an expression that is a sequence comparator. [Definition: A sequence comparator is an expression that evaluates two sequences of items and results in a true or false value. ]
The sequence comparator is supplied with two variables: $group-a and $group-b. Each of these variables is implicitly declared, and shadows any other variable of the same name. Its name is in no namespace. Its scope is the merge-when expression, and its type is item()+.
The sequence comparator is evaluated not item by item (as with split-when) but group by group. The context item is absent, the context position is the position of the first sequence ($group-a) within the sequence of groups being constructed, and the context size is the number of groups at the moment of evaluation.
The process begins by creating singleton groups. For each item in the population a group is created, with that item's position as its grouping key, and the item as its only member.
After the groups are created, they are evaluated pairwise against the sequence comparator. 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.
$group-a is set to the items in the first group in a pair of groups, G1, and $group-b to the second group, G2.
If the effective boolean valueXP of the sequence comparator is true, then all items in G2 are merged with the items in G1, preserving original sequence order, and the grouping keys of G2 are merged with those of G1, sorted in ascending order. The process of merging two groups is identical to the process described in 15 Merging to merge sequences. Pairwise comparison then restarts from the beginning with the first pair of groups, as described above.
The process is repeated until it is the case that there is no pair of groups for which the sequence comparator evaluates to true, or there is only one group.
Every item in the population will be appended to exactly one group.
Unlike other grouping methods, a group created by merge-when 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.
merge-when is most effective for building clusters or networks. For example:
merge-when="$group-a/(@id | is-related-to) = $group-b/(@id | is-related-to)" 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.
Suppose we have elements containing text units where word tokens of significance are wrapped in children tok elements. merge-when="every $a in $group-a, $b in $group-b satisfies count($a/tok[. = $b/tok]) ge 3" creates groups of possibly related texts. In groups of more than one item, any pair of texts has at least three common word-tokens.
merge-when="some $a in $group-a, $b in $group-b satisfies count($a/tok[. = $b/tok]) ge 3" 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.
merge-when="not($group-a = $group-b)" creates maximal groups of distinct values. For example, 4, 1, 5, 1, 9, 4, 1 is grouped as 4, 1, 5, 9 (with grouping keys 1, 2, 3, 5), 1, 4 (with grouping keys 4, 6), and 1 (with grouping key 7). Note, the first group is always the result of the distinct-values function, and the final group always contains the items that appear most frequently in the original population.
In merge-when="count($group-a) le 3 and count(distinct-values(($group-a, $group-b) ! node-name(.))) eq 1" no group has more than three items. Within each group, every item has the same node name. The effect is the same as specifying group-by="node-name(.)" then subgrouping with split-when="count($group) = 3".
merge-when="some $a in $group-a, $b in $group-b satisfies tokenize($a/@class) = tokenize($b/@class)" 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 @class.
merge-when="some $a in $group-a, $b in $group-b satisfies abs($a - $b) le 2" creates groups of numerals. Each numeral has at least one other numeral where the two differ by two or less. For example, 3, 9, 4, 1, 10, 6 is grouped as (3, 4, 1, 6) (with grouping keys 1, 3, 4, 6) and (9, 10) (with grouping keys 2, 5).
merge-when="some $a in $group-a, $b in $group-b satisfies abs($a - $b) le xs:dayTimeDuration('PT2H')" 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, 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") is grouped as (xs:time("11:12:00Z"), xs:time("09:44:10Z"), xs:time("08:16:30Z")) (with grouping keys 1, 3, 5) and (xs:time("13:24:55Z"), xs:time("14:09:22Z")) (with grouping keys 2, 4).
merge-when="every $a in $group-a, $b in $group-b satisfies (string-to-codepoints($a) = string-to-codepoints($b))" creates groups of strings. In groups with more than one member, each member shares at least one codepoint with every other member. For example, ("animal", "bison", "cat", "dog", "zebra") is grouped as ("animal", "bison", "zebra") (linking letters are a, i, n, and b), ("cat") (although it shares letter a with "animal," the group has already been merged with "bison," which has no common letter with "cat"), and ("dog"). The grouping keys are 1, 2, 5, 3, and 4, respectively.
In all cases the order of items within each group is predictable, and reflects the original population order, in that the items are processed in population order and each item is appended at the end of zero or more groups.
Note:
As always, a different algorithm may be used if it achieves the same effect.
[Definition: For each group, the item within the group that is first in population order is known as the initial item of the group.]
The sequence constructor contained in the xsl:for-each-group element is evaluated once for each of the groups, in processing order. The sequences that result are concatenated, in processing order, to form the result of the xsl:for-each-group element. Within the sequence constructor, the context item is the initial item of the relevant group, the context position is the position of this group in the processing order of the groups, and the context size is the number of groups This has the effect that within the sequence constructor, a call on position() takes successive values 1, 2, ... last().
The xsl:merge instruction allows a sorted sequence of items to be constructed by merging several input sequences. Each input sequence must 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 must 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 must 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.
For example, if two log files contain details of events sorted by date and time, then the xsl:merge instruction can be used to combine these into a single sequence that is also sorted by date and time.
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.
The xsl:merge 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, xsl:merge 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 xsl:merge-source element represents a set of input sequences that follow common rules, including the rules for computing the merge key. The xsl:merge operation may take any number of xsl:merge-source elements representing different rules for input sequences, and each xsl:merge-source 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 xsl:merge instruction is evaluated, and may vary from one evaluation to another.
The following examples illustrate some of the possibilities. The detailed explanation of the constructs used follows later in this section.
This example takes as input a homogeneous collection of XML log files each of which contains a sorted sequence of event elements with a timestamp attribute validated as an instance of xs:dateTime. It merges the events from the input files into a single sorted output file.
<xsl:result-document href="merged-events.xml">
<events>
<xsl:merge>
<xsl:merge-source for-each-source="uri-collection('log-files')"
select="events/event">
<xsl:merge-key select="@timestamp"/>
</xsl:merge-source>
<xsl:merge-action>
<xsl:copy-of select="current-merge-group()"/>
</xsl:merge-action>
</xsl:merge>
</events>
</xsl:result-document>The example assumes that there are several input files each of which has a structure similar to the following, in which the timestamp attribute has a typed value that is an instance of xs:dateTime:
<events> <event timestamp="2009-08-20T12:01:01Z">Transaction T1234 started</event> <event timestamp="2009-08-20T12:01:08Z">Transaction T1235 started</event> <event timestamp="2009-08-20T12:01:12Z">Transaction T1235 ended</event> <event timestamp="2009-08-20T12:01:15Z">Transaction T1234 ended</event> </events>
The output file will have the same structure, and will contain copies of all the event 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).
This example takes as input two log files with different structure, producing a single merged output in which the entries have a common structure:
<xsl:result-document href="merged-events.xml">
<events>
<xsl:merge>
<xsl:merge-source select="doc('log-file-1.xml')/events/event">
<xsl:merge-key select="@timestamp"/>
</xsl:merge-source>
<xsl:merge-source select="doc('log-files-2.xml')/log/day/record">
<xsl:merge-key select="dateTime(../@date, time)"/>
</xsl:merge-source>
<xsl:merge-action>
<xsl:apply-templates select="current-merge-group()"
mode="standardize-log-entry"/>
</xsl:merge-action>
</xsl:merge>
</events>
</xsl:result-document>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:
<log>
<day date="2009-08-20">
<record>
<time>12:01:09-05:00</time>
<message>Temperature 15.4C</message>
</record>
<record>
<time>12:03:00-05:00</time>
<message>Temperature 18.2C</message>
</record>
</day>
</log>The templates in mode standardize-log-entry convert the log entries to a common output format, for example:
<xsl:template match="event" mode="standardize-log-entry"
as="schema-element(event)">
<xsl:copy-of select="." validation="preserve"/>
</xsl:template>
<xsl:template match="record" mode="standardize-log-entry"
as="schema-element(event)">
<event timestamp="{dateTime(../@date, time)}" xsl:validation="strict">
<xsl:value-of select="message"/>
</event>
</xsl:template>Note:
The xsl:merge 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.
[Definition: A merge source definition is the definition of one kind of input to the merge operation. It selects zero or more merge input sequences, and it includes a merge key specification to define how the merge key values are computed for each such merge input sequence.] A merge source definition corresponds to an xsl:merge-source element in the stylesheet.
[Definition: A merge input sequence is an arbitrary sequenceDM of items which is already sorted according to the merge key specification for the corresponding merge source definition.]
[Definition: A merge key specification consists of one or more adjacent xsl:merge-key elements which together define how the merge input sequences selected by a merge source definition are sorted. Each xsl:merge-key element defines one merge key component.] For example, a merge key specification for a log file might specify two merge key components, date and time.
[Definition: A merge key component specifies one component of a merge key specification; it corresponds to a single xsl:merge-key element in the stylesheet.]
[Definition: For each item in a merge input sequence, a value is computed for each merge key component within the merge key specification. The value computed for an item by using the Nth merge key component is referred to as the Nth merge key value of that item.] A merge key value may be any sequence of atomic items (including anthe empty sequence).
[Definition: The ordered collection of merge key values computed for one item in a merge input sequence (one for each merge key component within the merge key specification) is referred to as a combined merge key value.] 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.
[Definition: A merge activation is a single evaluation of the sequence constructor contained within the xsl:merge-action element, which occurs once for each distinct combined merge key value.]
The keys on which the input sequences are sorted are referred to as merge keys. If the attribute sort-before-merge has the value yes, the input sequences will be sorted into the correct sequence before the merge operation takes place (alternatively, the processor may use an algorithm that has the same effect as sorting followed by merging). If the attribute is absent or has the value no, then the input sequences must already be in the correct order.
The merge key for each type of input sequence (that is, for each xsl:merge-source element) is defined by a sequence of xsl:merge-key element children of the xsl:merge-source element. Each xsl:merge-key element defines one merge key component. The syntax and semantics of an xsl:merge-key element are closely based on the rules for the xsl:sort element (with minor exceptions noted below; the only difference in syntax is the absence of the stable attribute); the main difference is that xsl:merge-key elements do not cause a sort to take place, they merely declare the existing sort order of the input sequence.
<xsl:merge-key
select? = expression
lang? = { language }
order? = { "ascending" | "descending" }〔'ascending'〕
collation? = { uri }
case-order? = { "upper-first" | "lower-first" }
data-type? = { "text" | "number" | eqname } >
<!-- Content: sequence-constructor -->
</xsl:merge-key>
The select attribute and the contained sequence constructor are mutually exclusive:
[ERR XTSE3200] It is a static error if an xsl:merge-key element with a select attribute has non-empty content.
Note:
From XSLT 4.0, the select expression or contained sequence constructor may evaluate (after atomization) to an arbitrary sequence of atomic items. Previously, only a singleton atomic item or anthe empty sequence was allowed.
The value of Nth item in the merge key of an item J in a merge input sequenceS is computed as follows, where K is the Nth xsl:merge-key element of the relevant xsl:merge-source:
If K has a select attribute, then the result of evaluating and atomizing that select expression;
If K contains a non-empty sequence constructor, then the result of evaluating and atomizing that sequence constructor;
Otherwise, the result of atomizing the context item.
In each case the evaluation uses a singleton focus based on J, or, if streamable="yes" is specified on the xsl:merge-source element, a singleton focus based on a snapshot of J (see 10 Streamable MergingSG).
Note:
This means that position() and last() return 1 (one). This differs from the way xsl:sort keys are evaluated, where position() is the position in the unsorted sequence, and last() is the size of the unsorted sequence.
The effect of the xsl:merge-key elements is defined in terms of the rules for an equivalent sequence of xsl:sort elements: if the rules for sorting (see 13.1.1 The Sorting Process) with stable="yes" would place an item A before an item B in the sorted sequence produced by the sorting process, then A must precede B in the input sequence to the merging process.
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 xsl:merge-source children of an xsl:merge instruction:
Each xsl:merge-source element must have the same number of xsl:merge-key child elements; let this number be N.
For each integer J in 1..N, consider the set S of xsl:merge-key elements that are in position J among the xsl:merge-key children of their parent xsl:merge-source element. For each attribute A in the set lang, order, collation, case-order, and data-type it must be the case that for any two elements s1 and s2 in S, the effective value of attribute A on s1 is the same as the effective value of attribute A on s2, 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 collation attribute, the absolute collation URI must be the same after resolving against the base URI.
If any of the attributes lang, order, collation, case-order, or data-type are attribute value templates, then their effective values are evaluated using the focus of the containing xsl:merge instruction.
[ERR XTSE2200] It is a static error if the number of xsl:merge-key children of a xsl:merge-source element is not equal to the number of xsl:merge-key children of another xsl:merge-source child of the same xsl:merge instruction.
[ERR XTDE2210] It is a dynamic error if there are two xsl:merge-key elements that occupy corresponding positions among the xsl:merge-key children of two different xsl:merge-source elements and that have differing effective values for any of the attributes lang, order, collation, case-order, or data-type. Values are considered to differ if they have different effective values. In the case of the collation attribute, the values are compared as absolute URIs after resolving against the base URI. The error may be raised statically if it is detected statically.
[ERR XTDE2220] It is a dynamic error if any input sequence to an xsl:merge instruction contains two items that are not correctly sorted according to the merge key values defined on the xsl:merge-key children of the corresponding xsl:merge-source element, when compared using the collation rules defined by the attributes of the corresponding xsl:merge-key children of the xsl:merge instruction, unless the attribute sort-before-merge is present with the value yes.
[ERR XTTE2230] It is a type error if some item selected by a particular merge key in one input sequence is not comparable using the XPath le operator with the corresponding item selected by the corresponding sort key in another input sequence.
The function library for XPath 3.0 defines several functions that make use of regular expressions:
matches returns a boolean result that indicates whether or not a string matches a given regular expression.
replace takes a string as input and returns a string obtained by replacing all substrings that match a given regular expression with a replacement string.
tokenize returns a sequence of strings formed by breaking a supplied input string at any separator that matches a given regular expression.
analyze-string 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.
These functions are described in [Functions and Operators 4.0].
Supplementing these functions, XSLT provides an instruction xsl:analyze-string, which is defined in this section.
Note:
The xsl:analyze-string instruction predates the analyze-string function, and provides very similar functionality, though in a different way.
The regular expressions used by this instruction, and the flags that control the interpretation of these regular expressions, must conform to the syntax defined in [Functions and Operators 4.0] (see [Functions and Operators 4.0] section 6.1 Regular expression syntax), which is itself based on the syntax defined in [XML Schema Part 2].
As described in [Functions and Operators 4.0] section 6.1 Regular expression 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 segment 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.
xsl:analyze-string InstructionChanges in 4.0 (next | previous)
The xsl:matching-substring and xsl:non-matching-substring elements within xsl:analyze-string may now take a select attribute in place of a contained sequence constructor. [Issue 443 PR 489 16 May 2023]
The rules for xsl:analyze-string have been adjusted to allow for new capabilities in regular expressions, such as zero-width assertions. [Issue 998 PR 1856 18 March 2025]
<!-- Category: instruction -->
<xsl:analyze-string
select = expression
regex = { string }
flags? = { string }〔''〕 >
<!-- Content: (xsl:matching-substring?, xsl:non-matching-substring?, xsl:fallback*) -->
</xsl:analyze-string>
<xsl:matching-substring
select? = expression >
<!-- Content: sequence-constructor -->
</xsl:matching-substring>
<xsl:non-matching-substring
select? = expression >
<!-- Content: sequence-constructor -->
</xsl:non-matching-substring>
The xsl:analyze-string instruction takes as input a string (the result of evaluating the expression in the select attribute), a regular expression (the effective value of the regex attribute), and a set of flags.
If the result of evaluating the select expression is anthe 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 coercion rules.
The flags 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 $flags attribute of the functions matches, replace, and tokenize. Specifically, if it contains the letter m, the match operates in multiline mode. If it contains the letter s, it operates in dot-all mode. If it contains the letter i, it operates in case-insensitive mode. If it contains the letter x, then whitespace within the regular expression is ignored. For more detailed specifications of these modes, see [Functions and Operators 4.0] ([Functions and Operators 4.0] section 6.2 Flags).
Note:
Because the regex 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 regex=".{{1,5}}". For regular expressions containing many curly brackets it may be more convenient to use a notation such as regex="{'[0-9]{1,5}[a-z]{3}[0-9]{1,2}'}", or to use a variable:
<xsl:variable name="regex"
expand-text="no">[0-9]{1,5}[a-z]{3}[0-9]{1,2}</xsl:variable>
<xsl:analyze-string regex="{$regex}"....The xsl:analyze-string instruction may have two child elements: xsl:matching-substring and xsl:non-matching-substring. Both elements are optional, and neither may appear more than once. At least one of them must be present. If both are present, the xsl:matching-substring element must come first.
The content of the xsl:analyze-string instruction must take one of the following forms:
A single xsl:matching-substring instruction, followed by zero or more xsl:fallback instructions
A single xsl:non-matching-substring instruction, followed by zero or more xsl:fallback instructions
A single xsl:matching-substring instruction, followed by a single xsl:non-matching-substring instruction, followed by zero or more xsl:fallback instructions
[ERR XTSE1130] It is a static error if the xsl:analyze-string instruction contains neither an xsl:matching-substring nor an xsl:non-matching-substring element.
Any xsl:fallback elements among the children of the xsl:analyze-string 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.
For the xsl:matching-substring and xsl:non-matching-substring elements, the select attribute and the contained sequence constructor are mutually exclusive [see ERR XTSE3185].
This instruction is designed to process all the non-overlapping substrings of the input string that match the regular expression supplied: that is, the disjoint matching segmentsFO that result from processing the input string using the supplied regular expression and the supplied flags.
[ERR XTDE1140] It is a dynamic error if the effective value of the regex attribute does not conform to the required syntax for regular expressions, as specified in [Functions and Operators 4.0]. If the regular expression is known statically (for example, if the attribute does not contain any expressions enclosed in curly brackets) then the processor may raise the error as a static error.
[ERR XTDE1145] It is a dynamic error if the effective value of the flags attribute has a value other than the values defined in [Functions and Operators 4.0]. If the value of the attribute is known statically (for example, if the attribute does not contain any expressions enclosed in curly brackets) then the processor may raise the error as a static error.
Processing proceeds as follows. Let M be the sequence of disjoint matching segmentsFO 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 M1 and M2, if the end position of M1 is not the same as the start position of M2, insert a non-matching segment comprising the characters from the input string between the end of M1 and the start of M2. 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.
The instruction then processes each of these segments in turn. For a matching segment, it evaluates the xsl:matching-substring child if it exists. For a non-matching segment, it evaluates the xsl:non-matching-substring if it exists. The child xsl:matching-substring or xsl:non-matching-substring is evaluated by evaluating its select 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 xs:string); 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.
If the xsl:matching-substring or xsl:non-matching-substring child is absent, then processing proceeds as if the element were present with empty content and no select attribute. That is, the corresponding segment produces no output.
<!-- Category: instruction -->
<xsl:message
select? = expression
terminate? = { boolean }〔'no'〕
error-code? = { eqname }〔'Q{http://www.w3.org/2005/xqt-errors}XTMM9000'〕 >
<!-- Content: sequence-constructor -->
</xsl:message>
The xsl:message instruction sends a message in an implementation-defined way. The xsl:message instruction causes the creation of a new document, which is typically serialized and output to an implementation-defined destination. The result of the xsl:message instruction is anthe empty sequence.
The content of the message may be specified by using either or both of the optional select attribute and the sequence constructor that forms the content of the xsl:message instruction.
If the xsl:message instruction contains a sequence constructor, then the sequence obtained by evaluating this sequence constructor is used to construct the content of the new document node, as described in 5.7.1 Constructing Complex Content.
If the xsl:message instruction has a select attribute, then the value of the attribute must be an XPath expression. The effect of the xsl:message instruction is then the same as if a single xsl:copy-of instruction with this select attribute were added to the start of the sequence constructor.
If the xsl:message instruction has no content and no select attribute, then an empty message is produced.
The tree produced by the xsl:message instruction is not technically a final result tree. The tree has no URI and processors are not required to make the tree accessible to applications.
Note:
In many cases, the XML document produced using xsl:message will consist of a document node owning a single text node. However, it may contain a more complex structure.
Note:
An implementation might implement xsl:message 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.
The terminate attribute is interpreted as an attribute value template.
If the effective value of the terminate attribute is yes, then the processormust raise a dynamic error after sending the message. This error may be caught in the same way as any other dynamic error using xsl:catch. The default value is no. Note that because the order of evaluation of instructions is implementation-dependent, this gives no guarantee that any particular instruction will or will not be evaluated before processing terminates.
The optional error-code attribute (also interpreted as an attribute value template) may be used to indicate the error code associated with the message. This may be used irrespective of the value of terminate. The effective value of the error code attribute is expected to be an EQName. If no error code is specified, or if the effective value is not a valid EQName, the error code will have local part XTMM9000 and namespace URI http://www.w3.org/2005/xqt-errors. User-defined error codes should be in a namespace other than http://www.w3.org/2005/xqt-errors. When the value of terminate is yes, the error code may be matched in an xsl:catch element to catch the error and cause processing to continue normally.
Note:
XPath 4.0 allows an EQName to include both a prefix and a URI, for example error-code="{http://example.com/ns}my:error-code".
[ERR XTMM9000] When a transformation is terminated by use of <xsl:message terminate="yes"/>, the effect is the same as when a dynamic error occurs during the transformation. The default error code is XTMM9000; this may be overridden using the error-code attribute of the xsl:message instruction.
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 stylesheet. For example, suppose messages for a language L are stored in an XML file resources/L.xml in the form:
<messages> <message name="problem">A problem was detected.</message> <message name="error">An error was detected.</message> </messages>
Then a stylesheet could use the following approach to localize messages:
<xsl:param name="lang" select="'en'"/>
<xsl:variable name="messages"
select="document(concat('resources/', $lang, '.xml'))/messages"/>
<xsl:template name="localized-message">
<xsl:param name="name"/>
<xsl:message select="string($messages/message[@name=$name])"/>
</xsl:template>
<xsl:template name="problem">
<xsl:call-template name="localized-message">
<xsl:with-param name="name">problem</xsl:with-param>
</xsl:call-template>
</xsl:template>Any dynamic error that occurs while evaluating the select expression or the contained sequence constructor, and any serialization error 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.
Note:
An example of such an error is the serialization error that occurs when processing the instruction <xsl:message select="@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.
One possible recovery action is to include a description of the error in the generated message text.
The xsl:assert instruction is used to assert that the value of a particular expression is true; if the value of the expression is false, and assertions are enabled, then a dynamic error occurs.
<!-- Category: instruction -->
<xsl:assert
test = expression
select? = expression
error-code? = { eqname }〔'Q{http://www.w3.org/2005/xqt-errors}XTMM9001'〕 >
<!-- Content: sequence-constructor -->
</xsl:assert>
By default, assertions are disabled.
An implementation must 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 implementation-defined.
If assertion checking is enabled, the instruction is evaluated as follows:
The expression in the test attribute is evaluated. If the effective boolean value of the result is true, the assertion succeeds, and no further action is taken. If the effective boolean value is false, or if a dynamic error occurs during evaluation of the expression, then the assertion fails.
If the assertion fails, then the effect of the instruction is governed by the rules for evaluation of an xsl:message instruction with the same select attribute, error-code attribute, and contained sequence constructor, and with the value terminate="yes". However, the default error code if the error-code attribute is omitted is XTMM9001 rather than XTMM9000.
Note:
To the extent that the behavior of xsl:message is implementation-defined, this rule does not prevent an implementation treating xsl:assert and xsl:message differently.
Note:
If evaluation of the test expression fails with a dynamic error, the effect is exactly the same as if the evaluation returns false, including the fact that the instruction fails with error code XTMM9001.
If an assertion fails, then the following sibling instructions of the xsl:assert instruction are not evaluated.
Note:
This means that xsl:assert can be used (rather like xsl:if and xsl:choose) 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 xsl:call-template 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 xsl:for-each, then subsequent items in the sequence will not be processed.
[ERR XTMM9001] When a transformation is terminated by use of xsl:assert, the effect is the same as when a dynamic error occurs during the transformation. The default error code is XTMM9001; this may be overridden using the error-code attribute of the xsl:assert instruction.
As with any other dynamic error, an error caused by an assertion failing may be trapped using xsl:try: see 8.4 Try/Catch.
The result of the xsl:assert instruction is anthe empty sequence.
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 static parameter$DEBUG is set to true.
<xsl:param name="DEBUG" as="xs:boolean" select="false()"
static="yes" required="no"/>
<xsl:function name="f:days-elapsed" as="xs:integer">
<xsl:param name="date" as="xs:date"/>
<xsl:assert use-when="$DEBUG" test="$date lt current-date()"/>
<xsl:sequence select="(current-date() - $since)
div xs:dayTimeDuration('PT1D')"/>
</xsl:function>Note:
Implementations should avoid optimizing xsl:assert instructions away. As a guideline, if the result of a sequence constructor is required by the transformation, the implementation should ensure that all xsl:assert instructions in that sequence constructor are evaluated. Conversely, if the result of a sequence constructor is not required by the transformation, its xsl:assert instructions should not be evaluated.
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.
An implementation may provide a user option allowing a processor to treat assertions as being true without explicit checking. This option must not be enabled by default. If such an option is in force, the effect of any assertion not being true is implementation-dependent.
Note:
For example, given the assertion <xsl:assert test="count(//title)=1"/>, a processor might generate code for the expression <xsl:value-of select="//title"/> that stops searching for title elements after finding the first one. In the event that the source document contains more than one title, execution of the stylesheet may fail in arbitrary ways, or it may produce incorrect output.
Changes in 4.0 (next | previous)
Functions that accept a lexical QName as an argument, such as key, function-available, element-available, type-available, system-property, accumulator-before, and accumulator-after, now have the option of supplying an xs:QName value instead. [This change was in the editor's draft accepted by the WG as its baseline when it started work.] [ 1 January 2022]
XSLT allows three kinds of extension: extension attributes, extension instructions, and extension functions.
[Definition: An extension attribute is an attribute appearing on an XSLT element, where the name of the attribute is in a non-null namespace other than the XSLT namespace.]
[Definition: An extension instruction is an element within a sequence constructor that is in a namespace (not the XSLT namespace) designated as an extension namespace.]
[Definition: An extension function is a named function introduced to the static or dynamic context by mechanisms outside the scope of this specification.]
This specification does not define any mechanism for creating or binding implementations of extension attributes, extension instructions, or extension functions, and it is not required that implementations support any such mechanism. Such mechanisms, if they exist, are implementation-defined. 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.
[ERR XTSE0085] It is a static error to use a reserved namespace in the name of any extension attribute, extension function, or extension instruction, other than a function or instruction defined in this specification or in a normatively referenced specification. It is a static error to use a prefix bound to a reserved namespace in the [xsl:]extension-element-prefixes attribute.
Changes in 4.0 (next | previous)
It is possible to invoke a named template using an extension instruction, specifically, an element whose name matches the name of the named template. [Issue 168 30 September 2022]
[Definition: The extension instruction mechanism allows namespaces to be designated as extension namespaces. When a namespace is designated as an extension namespace and an element with a name from that namespace occurs in a sequence constructor, then the element is treated as an instruction rather than as a literal result element.] The namespace determines the semantics of the instruction.
Note:
Since an element that is a child of an xsl:stylesheet element is not occurring in a sequence constructor, user-defined data elements (see 3.6.4 User-defined Data Elements) are not extension elements as defined here, and nothing in this section applies to them.
In XSLT 4.0 it is possible to use extension instructions to invoke named templates: see 10.1.3 Invoking Named Templates using Extension Instructions.
<!-- Category: instruction -->
<xsl:fallback>
<!-- Content: sequence-constructor -->
</xsl:fallback>
The content of an xsl:fallback element is a sequence constructor, and when performing fallback, the value returned by the xsl:fallback element is the result of evaluating this sequence constructor.
When not performing fallback, evaluating an xsl:fallback element returns anthe empty sequence: the content of the xsl:fallback element is not evaluated.
There are two situations where a processor 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 forwards compatible behavior is enabled.
Note:
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 system-property and function-available to decide what capabilities are available.
[ERR XTDE1450] When a processor performs fallback for an extension instruction that is not recognized, if the instruction element has one or more xsl:fallback children, then the content of each of the xsl:fallback children must be evaluated; it is a dynamic error if it has no xsl:fallback children.
Note:
This is different from the situation with unrecognized XSLT elements. As explained in 3.9 Forwards Compatible Processing, an unrecognized XSLT element appearing within a sequence constructor is a static error unless (a) forwards compatible behavior is enabled, and (b) the instruction has an xsl:fallback child.
The output of a transformation includes a principal result and zero or more secondary results.
The way in which these results are delivered to an application is implementation-defined.
Serialization of results is described further in 26 Serialization
Changes in 4.0 (next | previous)
A new serialization parameter escape-solidus is provided to control whether the character / is escaped as \/ by the JSON serialization method. [Issue 530 PR 534 9 June 2023]
The input to the serializer can be defined using the select attribute of xsl:result-document as an alternative to using a sequence constructor. [Issue 1534 PR 1549 12 November 2024]
A new serialization parameter canonical is available to give control over serialization of XML, XHTML, and JSON. [Issue 938 PR 2259 2 November 2025]
A new serialization parameter json-lines is available to enable output as one JSON value per line. [Issue 1538 PRs 1497 1546 13 November 2024]
<!-- Category: instruction -->
<xsl:result-document
format? = { eqname }
href? = { uri }
select? = expression
validation? = "strict" | "lax" | "preserve" | "strip"
type? = eqname
method? = { "xml" | "html" | "xhtml" | "text" | "json" | "adaptive" | eqname }
allow-duplicate-names? = { boolean }
build-tree? = { boolean }
byte-order-mark? = { boolean }
canonical? = { boolean }
cdata-section-elements? = { eqnames }
doctype-public? = { string }
doctype-system? = { string }
encoding? = { string }
escape-solidus? = { boolean }
escape-uri-attributes? = { boolean }
html-version? = { decimal }
include-content-type? = { boolean }
indent? = { boolean }
item-separator? = { string }
json-lines? = { boolean }
json-node-output-method? = { "xml" | "html" | "xhtml" | "text" | eqname }
media-type? = { string }
normalization-form? = { "NFC" | "NFD" | "NFKC" | "NFKD" | "fully-normalized" | "none" | nmtoken }
omit-xml-declaration? = { boolean }
parameter-document? = { uri }
standalone? = { boolean | "omit" }
suppress-indentation? = { eqnames }
undeclare-prefixes? = { boolean }
use-character-maps? = eqnames
output-version? = { nmtoken } >
<!-- Content: sequence-constructor -->
</xsl:result-document>
The xsl:result-document instruction is used to create a secondary result.
The select attribute and the contained sequence constructor are mutually exclusive; if the select attribute is present then the sequence constructor must be empty, and if the sequence constructor is non-empty then the select attribute must be absent [see ERR XTSE3185]. The value of the select attribute or the immediate result of the contained sequence constructor is referred to as the raw result.
As with the principal result of the transformation, a secondary result may be delivered to the calling application in three ways (see 2.3.6 Post-processing the Raw Result):
The raw result may be delivered as is.
The raw result may be used to construct a final result tree by invoking the process of sequence normalizationSE.
The raw result may be serialized to a sequence of octets (which may then, optionally, be saved to a persistent storage location).
Note:
The name of the instruction, xsl:result-document, 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.
The decision whether or not to serialize the raw result depends on the processor and on the way it is invoked. This is implementation-defined, and it is not controlled by anything in the stylesheet.
If the result is not serialized, then the decision whether to return the raw result or to construct a tree depends on the effective value of the build-tree attribute. If the effective value of the build-tree attribute is yes, then a final result tree is created by invoking the process of sequence normalizationSE. 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 build-tree attribute is then ignored. For example, with method="xml" a tree is always constructed, whereas with method="json" a tree is never constructed.
The xsl:result-document instruction defines a URI that may be used to identify the secondary result. The instruction may optionally specify the output format to be used for serializing the result.
Technically, the result of evaluating the xsl:result-document instruction is anthe empty sequence. This means it does not contribute anything to the result of the sequence constructor it is part of.
The effective value of the format attribute, if specified, must be an EQName. The value is expanded using the namespace declarations in scope for the xsl:result-document element. The resulting expanded QNamemust match the expanded QName of a named output definition in the stylesheet. This identifies the xsl:output declaration that will control the serialization of the final result tree (see 26 Serialization), if the result tree is serialized. If the format attribute is omitted, the unnamed output definition is used to control serialization of the result tree.
[ERR XTDE1460] It is a dynamic error if the effective value of the format attribute is not a valid EQName, or if it does not match the expanded QName of an output definition in the containing package. If the processor is able to detect the error statically (for example, when the format attribute contains no curly brackets), then the processor may optionally raise this as a static error.
Note:
The only way to select the unnamed output definition is to omit the format attribute.
The parameter-document attribute allows serialization parameters to be supplied in an external document. The external document must contain an output:serialization-parameters element with the format described in [Serialization 4.0] section 3.1 Setting Serialization Parameters by Means of a Parameter Document, and the parameters are interpreted as described in that specification.
If present, the effective value of the URI supplied in the parameter-document attribute is dereferenced, after resolution against the base URI of the xsl:result-document element if it is a relative reference. The parameter document should 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 should be ignored.
A serialization parameter specified in the parameter-document takes precedence over a value supplied directly as an attribute of xsl:result-document, which in turn takes precedence over a value supplied in the selected output definition, except that the values of the cdata-section-elements and suppress-indentation attributes are merged in the same way as when multiple xsl:output declarations are merged.
The attributes method, allow-duplicate-names, build-tree, byte-order-markcanonical, cdata-section-elements, doctype-public, doctype-system, encoding, escape-solidusescape-uri-attributes, html-version, indent, item-separator, json-lines, json-node-output-method, media-type, normalization-form, omit-xml-declaration, standalone, suppress-indentation, undeclare-prefixes, use-character-maps, and output-version may be used to override attributes defined in the selected output definition.
With the exception of use-character-maps, these attributes are all defined as attribute value templates, so their values may be set dynamically. For any of these attributes that is present on the xsl:result-document instruction, the effective value of the attribute overrides or supplements the corresponding value from the output definition. This works in the same way as when one xsl:output declaration overrides another. Some of the attributes have more specific rules:
In the case of cdata-section-elements and suppress-indentation, 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.
In the case of use-character-maps, the character maps referenced in this instruction supplement and take precedence over those defined in the selected output definition.
In the case of doctype-public and doctype-system, setting the 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”).
In the case of item-separator, setting the effective value of the attribute to the special value "#absent" 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 "#absent".
In all other cases, the effective value of an attribute actually present on this instruction takes precedence over the value defined in the selected output definition.
In the case of the attributes method, json-node-output-methodcdata-section-elements, suppress-indentation, and use-character-maps, the effective value of the attribute contains an EQName or a space-separated list of EQNames. 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 xsl:output: see 26.2 Serialization parameters.
The output-version attribute on the xsl:result-document instruction overrides the version attribute on xsl:output (it has been renamed because version is available with a different meaning as a standard attribute: see 3.3 Standard Attributes). In all other cases, attributes correspond if they have the same name.
There are some serialization parameters that apply to some output methods but not to others. For example, the indent attribute has no effect on the text 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 may validate the value of such an attribute, but is not required to do so.
The item-separator serialization parameter is used when the 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 text 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 item-separator.
The href attribute is optional. The default value is the zero-length string. The effective value of the attribute must be a URI Reference, which may be absolute or relative. If it is relative, then it is resolved against the base output URI. There may be implementation-defined restrictions on the form of absolute URI that may be used, but the implementation is not required to enforce any restrictions. Any valid relative URI reference must be accepted. Note that the zero-length string is a valid relative URI reference.
If the implementation provides an API to access secondary results, then it must allow a secondary result to be identified by means of the absolutized value of the href attribute. In addition, if a final result tree is constructed (that is, if the effective value of build-tree is yes), then this value is used as the base URI of the document node at the root of the final result tree.
Note:
The base URI of the final result tree 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.
Note:
It will often be the case that one final result tree 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.
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.
The optional attributes type and validation may be used on the xsl:result-document instruction to validate the contents of a final result tree, and to determine the type annotation that elements and attributes within the final result tree will carry. The permitted values and their semantics are described in 25.4.2 Validating Document Nodes. Any such validation is applied to the document node produced as the result of sequence normalizationSE. If sequence normalization does not take place (typically because the raw result is delivered to the application directly, or because the selected serialization method does not involve sequence normalization) then the validation and type attributes are ignored.
Note:
Validation applies after inserting item separators as determined by the item-separator serialization parameter, and an inappropriate choice of item-separator may cause the result to become invalid.
A processormay allow a final result tree to be serialized. Serialization is described in 26 Serialization. However, an implementation (for example, a processor running in an environment with no access to writable filestore) is not required to support the serialization of final result trees. An implementation that does not support the serialization of final result trees may ignore the format attribute and the serialization attributes. Such an implementation must provide the application with some means of access to the (un-serialized) result tree, using its URI to identify it.
Implementations may provide additional mechanisms, outside the scope of this specification, for defining the way in which final result trees are processed. Such mechanisms may make use of the XSLT-defined attributes on the xsl:result-document and/or xsl:output elements, or they may use additional elements or attributes in an implementation-defined namespace.
The following example takes an XHTML document as input, and breaks it up so that the text following each <h1> element is included in a separate document. A new document toc.html is constructed to act as an index:
<xsl:stylesheet
version="3.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:xhtml="http://www.w3.org/1999/xhtml">
<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"/>
<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"/>
<xsl:template match="/">
<xsl:result-document href="toc.html"
format="toc-format"
validation="strict">
<html xmlns="http://www.w3.org/1999/xhtml">
<head><title>Table of Contents</title></head>
<body>
<h1>Table of Contents</h1>
<xsl:for-each select="/*/xhtml:body/(*[1] | xhtml:h1)">
<p>
<a href="section{position()}.html">
<xsl:value-of select="."/>
</a>
</p>
</xsl:for-each>
</body>
</html>
</xsl:result-document>
<xsl:for-each-group select="/*/xhtml:body/*" group-starting-with="xhtml:h1">
<xsl:result-document href="section{position()}.html"
format="section-format" validation="strip">
<html xmlns="http://www.w3.org/1999/xhtml">
<head><title><xsl:value-of select="."/></title></head>
<body>
<xsl:copy-of select="current-group()"/>
</body>
</html>
</xsl:result-document>
</xsl:for-each-group>
</xsl:template>
</xsl:stylesheet>A sequence comparator is an expression that evaluates two sequences of items and results in a true or false value.
A component of the context that has no value is said to be absent.
An accumulator 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, accumulator-before and accumulator-after.
The functions accumulator-before and accumulator-after are referred to as the accumulator functions.
A stylesheet can use the xsl:namespace-alias element to declare that a literal namespace URI is being used as an alias for a target namespace URI.
A template rule is applicable to one or more modes. The modes to which it is applicable are defined by the mode attribute of the xsl:template element. If the attribute is omitted, then the template rule is applicable to the default mode specified in the [xsl:]default-mode attribute of the innermost containing element that has such an attribute, which in turn defaults to the unnamed mode. If the mode attribute is present, then its value must be a non-empty whitespace-separated list of tokens, each of which defines a mode to which the template rule is applicable.
The applicable static namespaces for an element in a stylesheet module are the fixed namespace bindings for the module if the root element of the module has a fixed-namespaces attribute, or the native namespace bindings of the element otherwise.
A function definition has an arity range, 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 function definitions with the same name, provided that their arity ranges do not overlap.
The term atomization is defined in [XPath 4.0] section 2.6.3 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 [XDM 4.0]. Arrays (see 22 Arrays) are atomized by atomizing their members, recursively.
An attribute set is defined as a set of xsl:attribute-set declarations in the same package that share the same expanded QName.
An attribute set invocation is a pseudo-instruction corresponding to a single EQName appearing within an [xsl:]use-attribute-sets attribute; the effect of the pseudo-instruction is to cause the referenced attribute set to be evaluated.
In an attribute that is designated as an attribute value template, such as an attribute of a literal result element, an expression can be used by surrounding the expression with curly brackets ({}), following the general rules for value templates
An element is processed with backwards compatible behavior if its effective version is less than 4.0.
The base output URI is a URI to be used as the base URI when resolving a relative URI reference allocated to a final result tree. If the transformation generates more than one final result tree, then typically each one will be allocated a URI relative to this base URI.
A basic XSLT processor is an XSLT processor that implements all the mandatory requirements of this specification with the exception of constructs explicitly associated with an optional feature.
A character map allows a specific character appearing in a text or attribute node in the final result tree to be substituted by a specified string of characters during serialization.
A circularity is said to exist if a construct such as a global variable, an attribute set, or a key, cannot be evaluated without reference to its own value. For example, if the expression or sequence constructor specifying the value of a global variableX references a global variable Y, then the value for Ymust be computed before the value of X. A circularity exists if it is impossible to do this for all global variable definitions.
The term coercion rules means the coercion rules defined in [XPath 4.0], applied unless otherwise specified with XPath 1.0 compatibility mode set to false.
Facilities in XSLT 3.0 and XPath 3.0 that require strings to be ordered rely on the concept of a named collation. 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.
The ordered collection of merge key values computed for one item in a merge input sequence (one for each merge key component within the merge key specification) is referred to as a combined merge key value.
The signatures of two components are compatible if they present the same interface to the user of the component. The additional rules depend on the kind of component.
The term component is used to refer to any of the following: a stylesheet function, a named template, a mode, an accumulator, an attribute set, a key, global variable, or a mode.
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 declaring package, but each has a different containing package. 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 xsl:use-package declaration, the declaring package will be the original package, and the containing package will be the package in which the xsl:use-package declaration appears.
The context item is the item currently being processed. An item (see [XDM 4.0]) is either an atomic item (such as an integer, date, or string), a node, or a function item. It changes whenever instructions such as xsl:apply-templates and xsl:for-each are used to process a sequence of items; each item in such a sequence becomes the context item while that item is being processed.
If the context item is a node (as distinct from an atomic item such as an integer), then it is also referred to as the context node. 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.
The context position 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 xsl:apply-templates or xsl:for-each 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.
The context size is the number of items in the sequence of items currently being processed. It changes whenever instructions such as xsl:apply-templates and xsl:for-each 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).
While the xsl:matching-substring instruction is active, a set of current captured groups is available, corresponding to the capturing subexpressions of the regular expression.
The current group is the group itself, as a sequence of items
The current grouping key is a single atomic item, or in the case of a composite key, a sequence of atomic items, containing the grouping key of the items in the current group.
The current merge group is a map. During evaluation of an xsl:merge instruction, as each group of items with equal combined merge key values 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.
The current merge key is a an array, whose members are sequences of atomic items. There is one member in the array for each xsl:merge-key element in the merge key specification. During evaluation of an xsl:merge instruction, as each group of items with equal combined merge key values is processed, the current merge key is set to the combined merge key value that these items have in common.
At any point in the processing of a stylesheet, there is a current mode. When the transformation is initiated, the current mode is the initial mode, as described in 2.3 Initiating a Transformation. Whenever an xsl:apply-templates instruction is evaluated, the current mode becomes the mode selected by this instruction.
The current output URI is the URI associated with the principal result or secondary result that is currently being written.
At any point in the processing of a stylesheet, there may be a current template rule. Whenever a template rule is chosen as a result of evaluating xsl:apply-templates, xsl:apply-imports, or xsl:next-match, the template rule becomes the current template rule for the evaluation of the rule’s sequence constructor.
All the xsl:decimal-format declarations in a package that share the same name are grouped into a named decimal format; those that have no name are grouped into a single unnamed decimal format.
Top-level elements fall into two categories: declarations, and user-defined data elements. Top-level elements whose names are in the XSLT namespace are declarations. Top-level elements in any other namespace are user-defined data elements (see 3.6.4 User-defined Data Elements)
The declarations within a stylesheet level have a total ordering known as declaration order. 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 xsl:include element that references it.
The declaring package of a component is the package that contains the declaration (or, in the case of xsl:attribute-set and xsl:key, multiple declarations) of the component.
In this specification the term default collation means the collation that is used by XPath operators such as eq and lt appearing in XPath expressions within the stylesheet.
The [xsl:]default-mode attribute defines the default mode, which is used as the default value for the mode attribute of all xsl:template and xsl:apply-templates elements within its scope.
If no priority attribute is specified on an xsl:template element, a default priority is computed, based on the syntactic form of the pattern supplied in the match attribute.
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 expression 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 defining element of the lexical QName.
Some constructs defined in this specification are described as being deprecated. The use of this term implies that stylesheet authors should not use the construct, and that the construct may be removed in a later version of this specification.
The disqualifying elements are xsl:map, xsl:map-entry, xsl:array, xsl:array-member, xsl:record, and xsl:select. If a sequence constructor includes one of these elements, then construction of the implicit document node does not take place.
An error that is not capable of detection until a source document is being transformed is referred to as a dynamic error.
An xsl:function declaration F is said to be eclipsed if the containing package includes an xsl:function declaration G such that F and G have the same name, F has lower import precedence than G, and the arity range of G includes the totality of the arity range of F.
The effective value of an attribute or text node in the stylesheet is the value after any required expansion or normalization.
The effective version of an element in a stylesheet module or package manifest is the decimal value of the [xsl:]version attribute (see 3.3 Standard Attributes) on that element or on the innermost ancestor element that has such an attribute, subject to special rules for the xsl:output and xsl:fallback elements.
A stylesheet module whose outermost element is the child of a non-XSLT element in a host document is referred to as an embedded stylesheet module. See 3.11 Embedded Stylesheet Modules.
A mode declared by an xsl:mode declaration that has one or more contained xsl:template declarations is referred to as an enclosing mode.
An EQName is a string representing an expanded QName where the string, after removing leading and trailing whitespace, is in the form defined by the EQNameXP production in the XPath specification.
An expanded QName is a value in the value space of the xs:QName datatype as defined in the XDM data model (see [XDM 4.0]): 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.
An explicit default for a parameter is indicated by the presence of either a select attribute or a non-empty sequence constructor.
A parameter is explicitly mandatory if it is a function parameterwith no required attribute, or if the required attribute is present and has the value yes.
Within this specification, the term XPath expression, or simply expression, means a string that matches the production ExprXP defined in [XPath 4.0].
An extension attribute is an attribute appearing on an XSLT element, where the name of the attribute is in a non-null namespace other than the XSLT namespace.
An extension function is a named function introduced to the static or dynamic context by mechanisms outside the scope of this specification.
An extension instruction is an element within a sequence constructor that is in a namespace (not the XSLT namespace) designated as an extension namespace.
The extension instruction mechanism allows namespaces to be designated as extension namespaces. When a namespace is designated as an extension namespace and an element with a name from that namespace occurs in a sequence constructor, then the element is treated as an instruction rather than as a literal result element.
The first of the two output states is called final output state. This state applies when instructions are writing to a final result tree.
A final result tree is a result tree that forms part of the output of a transformation: specifically, a tree built by post-processing the items in the principal result or in a secondary result. Once created, the contents of a final result tree are not accessible within the stylesheet itself.
The fixed namespace bindings for a stylesheet module are established using the fixed-namespaces attribute on the xsl:stylesheet, xsl:transform, or xsl:package element enclosing the stylesheet module.
When a sequence constructor is evaluated, the processor keeps track of which items are being processed by means of a set of implicit variables referred to collectively as the focus.
An element is processed with forwards compatible behavior if its effective version is greater than 4.0.
The term function definition is defined in [XPath 4.0] section 2.2.1 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 stylesheet function, or a built-in function such as those defined in [Functions and Operators 4.0]
An xsl:param element may appear as a child of an xsl:function element, before any non-xsl:param children of that element. Such a parameter is known as a function parameter. A function parameter is a local variable with the additional property that its value can be set when the function is called, using a function call in an XPath expression.
An item that is the global context item for the transformation acts as the context item when evaluating the select expression or sequence constructor of a global variablewhose declaration is within the top-level package, as described in 5.3.3.1 Maintaining Position: the Focus. The global context item may also be available in a named template when the stylesheet is invoked as described in 2.3.4 Call-Template Invocation
A top-levelvariable-binding element declares a global variable that is visible everywhere except within any region where it is shadowed by another variable binding.
An GNode pattern 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.
The xsl:for-each-group instruction allocates the items in an input sequence into groups of items (that is, it establishes a collection of sequences) based either on common values of a grouping key, or on a pattern that the initial or final item in a group must match.
If the group-by or group-adjacent attributes is present, then for each item in the population a set of grouping keys is calculated, as follows: the expression contained in the group-by or group-adjacent attribute is evaluated; the result is atomized; and any xs:untypedAtomic items are cast to xs:string. If composite="yes" 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.
A xsl:package-location without the attribute is-priority, or with is-priority set to true is a high priority package location.
Two components are said to be homonymous if they have the same symbolic identifier.
Types S and T are considered identical for the purpose of these rules if and only if subtype(S, T) and subtype(T, S) both hold, where the subtype relation is defined in [XPath 4.0] section 3.3.1 Subtypes of Sequence Types.
The result of evaluating a 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 immediate result of the sequence constructor.
A specific product that performs the functions of an XSLT processor is referred to as an implementation.
In this specification, the term implementation-defined refers to a feature where the implementation is allowed some flexibility, and where the choices made by the implementation must be described in documentation that accompanies any conformance claim.
The term implementation-dependent refers to a feature where the behavior may vary from one implementation to another, and where the vendor is not expected to provide a full specification of the behavior.
If a parameter that is not explicitly mandatory has no explicit default value, then it has an implicit default value, which is the empty sequence if there is an as attribute, or a zero-length string if not.
If a parameter has an implicit default value which cannot be converted to the required type (that is, if it has an as attribute which does not permit the empty sequence), then the parameter is implicitly mandatory.
A declarationD in the stylesheet is defined to have lower import precedence than another declaration E if the stylesheet level containing D would be visited before the stylesheet level containing E 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.
The stylesheet levels making up a stylesheet are treated as forming an import tree. In the import tree, each stylesheet level has one child for each xsl:import declaration that it contains.
A stylesheet may be evaluated by calling a named stylesheet function, referred to as the initial function.
For each group, the item within the group that is first in population order is known as the initial item of the group.
A stylesheet may be evaluated by supplying a value to be processed, together with an initial mode. The value (which can be any sequence of items) is referred to as the initial match selection. The processing then corresponds to the effect of the xsl:apply-templates instruction.
The initial mode is the mode used to select template rules for processing items in the initial match selection when apply-templates invocation is used to initiate a transformation.
A stylesheet may be evaluated by selecting a named template to be evaluated; this is referred to as the initial named template.
The sequence to be sorted is referred to as the initial sequence.
The initial setting of a component of the dynamic context is used when evaluating global variables and stylesheet parameters, when evaluating the use and match attributes of xsl:key, and when evaluating the initial-value of xsl:accumulator and the select expressions or contained sequence constructors of xsl:accumulator-rule
The schema components that may be referenced by name in a package are referred to as the in-scope schema components.
An instruction is either an XSLT instruction or an extension instruction.
The following constructs are classified as invocation constructs: the instructions xsl:call-template, xsl:apply-templates, xsl:apply-imports, and xsl:next-match; XPath function calls that bind to stylesheet functions; XPath dynamic function calls; the functions accumulator-before and accumulator-after; the [xsl:]use-attribute-sets attribute. These all have the characteristic that they can cause evaluation of constructs that are not lexically contained within the calling construct.
A key is defined as a set of xsl:key declarations in the same package that share the same name.
The expression in the use attribute and the sequence constructor within an xsl:key declaration are referred to collectively as the key specifier. The key specifier determines the values that may be used to find a node using this key.
A lexical QName is a string representing an expanded QName where the string, after removing leading and trailing whitespace, is within the lexical space of the xs:QName datatype as defined in XML Schema (see [XML Schema Part 2]): that is, a local name optionally preceded by a namespace prefix and a colon.
Every package within a stylesheet, other than the top-level package, is referred to as a library package.
A namespace URI in the stylesheet tree that is being used to specify a namespace URI in the result tree is called a literal namespace URI.
In a sequence constructor, an element in the stylesheet that does not belong to the XSLT namespace and that is not an extension instruction (see 24.3 Extension Instructions) is classified as a literal result element.
As well as being allowed as a declaration, the xsl:variable element is also allowed in sequence constructors. Such a variable is known as a local variable.
A xsl:package-location with is-priority set to false is a low priority package location.
A merge activation is a single evaluation of the sequence constructor contained within the xsl:merge-action element, which occurs once for each distinct combined merge key value.
A merge input sequence is an arbitrary sequenceDM of items which is already sorted according to the merge key specification for the corresponding merge source definition.
A merge key component specifies one component of a merge key specification; it corresponds to a single xsl:merge-key element in the stylesheet.
A merge key specification consists of one or more adjacent xsl:merge-key elements which together define how the merge input sequences selected by a merge source definition are sorted. Each xsl:merge-key element defines one merge key component.
For each item in a merge input sequence, a value is computed for each merge key component within the merge key specification. The value computed for an item by using the Nth merge key component is referred to as the Nth merge key value of that item.
A merge source definition is the definition of one kind of input to the merge operation. It selects zero or more merge input sequences, and it includes a merge key specification to define how the merge key values are computed for each such merge input sequence.
A mode is a set of template rules; when the xsl:apply-templates 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.
All the xsl:mode declarations in a package that share the same name are grouped into a named mode definition; those that have no name are grouped into a single unnamed mode definition.
Templates can be invoked by name. An xsl:template element with a name attribute defines a named template.
The rules for the individual XSLT instructions that construct a result tree (see 11 Creating 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 must therefore add additional namespace nodes to satisfy these constraints. This process is referred to as namespace fixup.
The native namespace bindings for any element in an XSLT stylesheet module are the prefix-uri mappings defined by the namespace nodes of that element, according to the rules in [XDM 4.0].
The term non-contextual function call is used to refer to function calls that do not pass the dynamic context to the called function. This includes all calls on stylesheet functions and all dynamic function callsXP, (that is calls to function items). It excludes calls to some functions in the namespace http://www.w3.org/2005/xpath-functions, in particular those that explicitly depend on the context, such as the current-group and regex-group functions. It is implementation-defined whether, and under what circumstances, calls to extension functions are non-contextual.
A non-schema-aware processor is a processor that does not claim conformance with the schema-aware conformance feature. Such a processor must handle constructs associated with schema-aware processing as described in this section.
There is a total ordering among groups referred to as the order of first appearance. A group G is defined to precede a group H in order of first appearance if the initial item of G precedes the initial item of H in population order. If two groups G and H have the same initial item (because the item is in both groups) then G precedes H if the grouping key of G precedes the grouping key of H in the sequence that results from evaluating the group-by expression of this initial item.
All the xsl:output declarations within a package that share the same name are grouped into a named output definition; those that have no name are grouped into a single unnamed output definition.
Each instruction in the stylesheet is evaluated in one of two possible output states: final output state or temporary output state.
A component in a using package may override a component in a used package, provided that the visibility of the component in the used package is either abstract or public. The overriding declaration is written as a child of the xsl:override element, which in turn appears as a child of xsl:use-package.
An explicit package is represented by an xsl:package element, which will generally be the outermost element of an XML document. When the xsl:package element is not used explicitly, the entire stylesheet comprises a single implicit package.
The content of the xsl:package element is referred to as the package manifest
The xsl:param element declares a parameter, which may be a stylesheet parameter, a template parameter, a function parameter, or an xsl:iterate parameter. A parameter is a variable with the additional property that its value can be set by the caller.
A pattern 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.
The picture string is the string supplied as the second argument of the format-number function.
The xsl:number instruction performs two tasks: firstly, determining a place marker (this is a sequence of integers, to allow for hierarchic numbering schemes such as 1.12.2 or 3(c)ii), and secondly, formatting the place marker for output as a text node in the result sequence.
The sequence of items to be grouped, which is referred to as the population, is determined by evaluating the XPath expression contained in the select attribute.
The population is treated as a sequence; the order of items in this sequence is referred to as population order.
The integer literals and the optional NamePart within the version number are referred to as the portions of the version number.
A predicate pattern is written as . (dot) followed by zero or more predicates in square brackets, and it matches any item for which each of the predicates evaluates to true.
A principal result: this can be any sequence of items (as defined in [XDM 4.0]).
Within a package, one stylesheet module functions as the principal stylesheet module. The complete package is assembled by finding the stylesheet modules referenced directly or indirectly from the principal stylesheet module using xsl:include and xsl:import elements: see 3.10.2 Stylesheet Inclusion and 3.10.3 Stylesheet Import.
The priority of a template rule is specified by the priority attribute on the xsl:template declaration. If no priority is specified explicitly for a template rule, its default priority is used, as defined in 6.3.3 Default Priority for Patterns.
The first package location whose value of href, when resolved as described in 5.8 URI References, allows the system to find the specified resource, and its entry if the resource is an archive, is the optimal package location.
There is another total ordering among groups referred to as processing order. If group R precedes group S in processing order, then in the result sequence returned by the xsl:for-each-group instruction the items generated by processing group R will precede the items generated by processing group S.
The software responsible for transforming source trees into result trees using an XSLT stylesheet is referred to as the processor. This is sometimes expanded to XSLT processor to avoid any confusion with other processors, for example an XML processor.
The result of invoking the selected component, after any required conversion to the declared result type of the component, is referred to as the raw result.
The process of identifying the component to which a symbolic reference applies (possibly chosen from several homonymous alternatives) is called reference binding.
The context within a stylesheet where an XPath expression appears may specify the required type of the expression. The required type indicates the type of the value that the expression is expected to return.
The XSLT namespace, together with certain other namespaces recognized by an XSLT processor, are classified as reserved namespaces and must be used only as specified in this and related specifications.
The term result tree is used to refer to any tree constructed by instructions in the stylesheet. A result tree is either a final result tree or a temporary tree.
A schema-aware XSLT processor is an XSLT processor that implements the mandatory requirements of this specification connected with the xsl:import-schema declaration, the [xsl:]validation and [xsl:]type attributes, and the ability to handle input documents whose nodes have type annotations other than xs:untyped and xs:untypedAtomic. The mandatory requirements of this specification are taken to include the mandatory requirements of XPath 4.0, as described in [XPath 4.0]. A requirement is mandatory unless the specification includes wording (such as the use of the words should or may) that clearly indicates that it is optional.
Type definitions and element and attribute declarations are referred to collectively as schema components.
The schema instance namespacehttp://www.w3.org/2001/XMLSchema-instance, with conventional prefix xsi, is used as defined in [XML Schema Part 1]
The schema namespacehttp://www.w3.org/2001/XMLSchema, with conventional prefix xs, is used as defined in [XML Schema Part 1]
Zero or more secondary results: each secondary result can be any sequence of items (as defined in [XDM 4.0]).
A sequence constructor is a sequence of zero or more sibling nodes in the stylesheet 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.
A SequenceType 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 SequenceTypeXP in [XPath 4.0].
A frequent requirement is to output a final result tree as an XML document (or in other formats such as HTML). This process is referred to as serialization.
If a transformation has successfully produced a principal result or 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 serialization error.
A processor that claims conformance with the serialization featuremust support the conversion of a final result tree to a sequence of octets following the rules defined in 26 Serialization.
Within a region of the stylesheet where a binding B1 is visible, B1 shadows another binding B2 having the same name as B1 if B1 occurs at a point where B2 is visible.
A simplified stylesheet, which is a subtree rooted at a literal result element, as described in 3.7 Simplified Stylesheet Modules. This is first converted to a standard stylesheet module by wrapping it in an xsl:stylesheet element using the transformation described in 3.7 Simplified Stylesheet Modules.
A singleton focus based on an item J has the context item (and therefore the context node, if J is a node) set to J, and the context position and context size both set to 1 (one).
A snapshot of a node N is a deep copy of N, as produced by the xsl:copy-of instruction with copy-namespaces set to yes, copy-accumulators set to yes, and validation set to preserve, with the additional property that for every ancestor of N, the copy also has a corresponding ancestor whose name, node-kind, and base URI are the same as the corresponding ancestor of N, and that has copies of the attributes, namespaces and accumulator values of the corresponding ancestor of N. But the ancestor has a type annotation of xs:anyType, has the properties nilled, is-id, and is-idref set to false, and has no children other than the child that is a copy of N or one of its ancestors.
The sequence after sorting as defined by the xsl:sort elements is referred to as the sorted sequence.
Within a sort key specification, each xsl:sort element defines one sort key component.
A sort key specification is a sequence of one or more adjacent xsl:sort elements which together define rules for sorting the items in an input sequence to form a sorted sequence.
For each item in the initial sequence, a value is computed for each sort key component within the sort key specification. The value computed for an item by using the Nth sort key component is referred to as the Nth sort key value of that item.
The term source tree means any tree provided as input to the transformation. This includes the document containing the global context item if any, documents containing nodes present in the initial match selection, documents containing nodes supplied as the values of stylesheet parameters, documents obtained from the results of functions such as document, doc, and collection, documents read using the xsl:source-document instruction, and documents returned by extension functions or extension instructions. In the context of a particular XSLT instruction, the term source tree 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 temporary tree produced during the course of the transformation.
A sort key specification is said to be stable if its first xsl:sort element has no stable attribute, or has a stable attribute whose effective value is yes.
There are a number of standard attributes that may appear on any XSLT element: specifically default-collation, default-mode, default-validation, exclude-result-prefixes, expand-text, extension-element-prefixes, schema-role, use-when, version, and xpath-default-namespace.
The standard error namespacehttp://www.w3.org/2005/xqt-errors, with conventional prefix err, 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 xsl:catch element.
The standard function namespacehttp://www.w3.org/2005/xpath-functions, with conventional prefix fn, is used for functions in the function library defined in [Functions and Operators 4.0] and for standard functions defined in this specification.
A standard stylesheet module, which is a subtree rooted at an xsl:stylesheet or xsl:transform element.
An error that can be detected by examining a stylesheet before execution starts (that is, before the source document and values of stylesheet parameters are available) is referred to as a static error.
A static expression is an XPath expression whose value must be computed during static analysis of the stylesheet.
A static variable declared using an xsl:param element is referred to as a static parameter.
A top-levelvariable-binding element having the attribute static="yes" declares a static variable: that is, a global variable whose value is known during static analysis of the stylesheet.
A streamable mode is a mode that is declared in an xsl:mode declaration with the attribute streamable="yes".
A streamed document is a source tree that is processed using streaming, that is, without constructing a complete tree of nodes in memory.
A streamed node is a node in a streamed document.
The term streaming 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.
A processor that claims conformance with the streaming featuremust use streamed processing in cases where (a) streaming is requested (for example by using the attribute streamable="yes" on xsl:mode, or on the xsl:source-document instruction) and (b) the constructs in question are guaranteed-streamableSG according to this specification.
The term string value is defined in [XDM 4.0] section 7.6.12 string-value Accessor. Every node has a string value. For example, the string value of an element is the concatenation of the string values of all its descendant text nodes.
A stylesheet consists of one or more packages: specifically, one top-level package and zero or more library packages.
An xsl:function declaration declares the name, parameters, and implementation of a family of stylesheet functions that can be called from any XPath expression within the stylesheet (subject to visibility rules).
A stylesheet level is a collection of stylesheet modules connected using xsl:include declarations: specifically, two stylesheet modules A and B are part of the same stylesheet level if one of them includes the other by means of an xsl:include declaration, or if there is a third stylesheet module C that is in the same stylesheet level as both A and B.
A package consists of one or more stylesheet modules, each one forming all or part of an XML document.
A top-levelxsl:param element declares a stylesheet parameter. 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.
The value of the variable is computed using the expression given in the select attribute or the contained sequence constructor, as described in 9.3 Values of Variables and Parameters. This value is referred to as the supplied value of the variable.
The symbolic identifier of a component 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 expanded QName of the component (namespace URI plus local name), and in the case of stylesheet functions, the upper bound of the arity range.
The declaration of a component includes constructs that can be interpreted as references to other components by means of their symbolic identifiers. These constructs are generically referred to as symbolic references. Examples of constructs that give rise to symbolic references are the name attribute of xsl:call-template; the [xsl:]use-attribute-sets attribute of xsl:copy, xsl:element, and literal result elements; the explicit or implicit mode attribute of xsl:apply-templates; XPath variable references referring to global variables; XPath static function calls (including partial function applications) referring to stylesheet functions; and named function references (example: my:f#1) referring to stylesheet functions.
An instructionJ is in a tail position within a sequence constructorSC if it satisfies one of the following conditions:
J is the last instruction in SC, ignoring any xsl:fallback instructions.
J is in a tail position within the sequence constructor that forms the body of an xsl:if instruction that is itself in a tail position within SC.
J is in a tail position within the sequence constructor that forms the body of an xsl:when or xsl:otherwise branch of an xsl:chooseor xsl:switch instruction that is itself in a tail position within SC.
J is in a tail position within the sequence constructor that forms the body of an xsl:try instruction that is itself in a tail position within SC (that is, it is immediately followed by an xsl:catch element, ignoring any xsl:fallback elements).
J is in a tail position within the sequence constructor that forms the body of an xsl:catch element within an xsl:try instruction that is itself in a tail position within SC.
The string that results from evaluating the expression in the xpath attribute is referred to as the target expression.
The namespace URI that is to be used in the result tree as a substitute for a literal namespace URI is called the target namespace URI.
An xsl:template declaration defines a template, which contains a sequence constructor; this sequence constructor is evaluated to determine the result of the template. A template can serve either as a template rule, invoked by matching items against a pattern, or as a named template, invoked explicitly by name. It is also possible for the same template to serve in both capacities.
An xsl:param element may appear as a child of an xsl:template element, before any non-xsl:param children of that element. Such a parameter is known as a template parameter. A template parameter is a local variable with the additional property that its value can be set when the template is called, using any of the instructions xsl:call-template, xsl:apply-templates, xsl:apply-imports, or xsl:next-match.
A stylesheet contains a set of template rules (see 6 Template Rules). A template rule has three parts: a pattern that is matched against selected items (often but not necessarily nodes), a (possibly empty) set of template parameters, and a sequence constructor that is evaluated to produce a sequence of items.
The second of the two output states is called temporary output state. This state applies when instructions are writing to a temporary tree or any other non-final destination.
The term temporary tree means any tree that is neither a source tree nor a final result tree.
In a text node that is designated as a text value template, expressions can be used by surrounding each expression with curly brackets ({}).
An element occurring as a child of an xsl:package, xsl:stylesheet, xsl:transform, or xsl:override element is called a top-level element.
For a given transformation, one package functions as the top-level package. The complete stylesheet is assembled by finding the packages referenced directly or indirectly from the top-level package using xsl:use-package declarations: see 3.4.2 Dependencies between Packages.
A traversal of a tree is a sequence of traversal events.
a traversal event (shortened to event in this section) is a pair comprising a phase (start or end) and a node.
The term tree is used (as in [XDM 4.0]) to refer to the aggregate consisting of a parentless node together with all its descendant nodes, plus all their attributes and namespaces.
A parameter passed to a template may be defined as a tunnel parameter. 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.
The term type annotation is used in this specification to refer to the value returned by the dm:type-name accessor of a node: see [XDM 4.0] section 7.6.13 type-name Accessor.
The term typed value is defined in [XDM 4.0] section 7.6.14 typed-value Accessor. Every node, other than an element whose type annotation identifies it as having element-only content, has a typed value. For example, the typed value of an attribute of type xs:IDREFS is a sequence of zero or more xs:IDREF values.
Certain errors are classified as type errors. 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.
A type pattern is written as ~T (where T is an ItemTypeXP) followed by zero or more predicates in square brackets, and it matches any item of type T for which each of the predicates evaluates to true.
The unnamed mode is the default mode used when no mode attribute is specified on an xsl:apply-templates instruction or xsl:template declaration, unless a different default mode has been specified using the [xsl:]default-mode attribute of a containing element.
Within this specification, the term URI Reference, unless otherwise stated, refers to a string in the lexical space of the xs:anyURI datatype as defined in [XML Schema Part 2].
If a package Q contains an xsl:use-package element that references package P, then package Q is said to use package P. In this relationship package Q is referred to as the using package, package P as the used package.
In addition to declarations, the xsl:stylesheet element may contain among its children any element not from the XSLT namespace, provided that the expanded QName of the element has a non-null namespace URI. Such elements are referred to as user-defined data elements.
An item is vacuous 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 xs:string, produces a zero-length string; or an array which on flattening using the array:flatten function produces either anthe empty sequence or a sequence consisting entirely of vacuous items.
A variable is a binding between a name and a value. The value of a variable is any sequence (of nodes, atomic items, and/or function items), as defined in [XDM 4.0].
Collectively, attribute value templates and text value templates are referred to as value templates.
The xsl:variable element declares a variable, which may be a global variable or a local variable.
The two elements xsl:variable and xsl:param are referred to as variable-binding elements.
The visibility of a component is one of: private, public, abstract, final, or hidden.
A whitespace text node is a text node whose content consists entirely of whitespace characters (that is, U+0009 (TAB) , U+000A (NEWLINE) , U+000D (CARRIAGE RETURN) , or U+0020 (SPACE) ).
The XML namespace, defined in [Namespaces in XML] as http://www.w3.org/XML/1998/namespace, is used for attributes such as xml:lang, xml:space, and xml:id.
The term XPath 1.0 compatibility mode is defined in [XPath 4.0] section 2.2.1 Static Context. This is a setting in the static context of an XPath expression; it has two values, true and false. When the value is set to true, the semantics of function calls and certain other operations are adjusted to give a greater degree of backwards compatibility between XPath 4.0 and XPath 1.0.
An element in the stylesheet is processed with XSLT 1.0 behavior if its effective version is equal to 1.0.
A processor that claims conformance with the XSLT 1.0 compatibility featuremust support the processing of stylesheet instructions and XPath expressions with XSLT 1.0 behavior, as defined in 3.8 Backwards Compatible Processing.
An element is processed with XSLT 2.0 behavior if its effective version is equal to 2.0.
An element is processed with XSLT 3.0 behavior if its effective version is equal to 3.0.
An XSLT element is an element in the XSLT namespace whose syntax and semantics are defined in this specification.
An XSLT instruction is an XSLT element whose syntax summary in this specification contains the annotation <!-- category: instruction -->.
The XSLT namespace has the URI http://www.w3.org/1999/XSL/Transform. It is used to identify elements, attributes, and other names that have a special meaning defined in this specification.
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 must 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 required to raise errors using the descriptive text used here.
Note:
The appendix is non-normative because the same information is given normatively elsewhere.
Static errors
It is a static error if an XSLT-defined element is used in a context where it is not permitted, if a required attribute is omitted, or if the content of the element does not correspond to the content that is allowed for the element.
It is a static error if an attribute (other than an attribute written using curly brackets in a position where an attribute value template is permitted) contains a value that is not one of the permitted values for that attribute.
It is a static error to use a reserved namespace in the name of a named template, a mode, an attribute set, a key, a decimal-format, a variable or parameter, a stylesheet function, a named output definition, an accumulator, or a character map; except that the name xsl:initial-template is permitted as a template name.
It is a static error to use a reserved namespace in the name of any extension attribute, extension function, or extension instruction, other than a function or instruction defined in this specification or in a normatively referenced specification. It is a static error to use a prefix bound to a reserved namespace in the [xsl:]extension-element-prefixes attribute.
It is a static error 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.
The value of the version attribute must be a number: specifically, it must be a valid instance of the type xs:decimal as defined in [XML Schema Part 2].
An xsl:stylesheet, xsl:transform, or xsl:package element must not have any text node children.
It is a static error if a token appearing in the fixed-namespaces 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 xmlns. It is not permitted to bind the prefix xml or the XML namespace URI http://www.w3.org/XML/1998/namespace, other than to each other.
It is a static error if the value of an [xsl:]default-collation attribute, after resolving against the base URI, contains no URI that the implementation recognizes as a collation URI.
It is a static error if an xsl:stylesheet, xsl:transform, or xsl:package element has a child element whose name has a null namespace URI.
It is a static error if the processor is not able to retrieve the resource identified by the URI reference [ in the href attribute of xsl:include or xsl:import ] , or if the resource that is retrieved does not contain a stylesheet module.
An xsl:include element must be a top-level element.
An xsl:import element must be a top-level element.
It is a static error if a stylesheet module directly or indirectly references itself via a chain of xsl:include and xsl:import declarations that contains at least one xsl:import.
It is a static error if an xsl:import-schema element that contains an xs:schema element has a schema-location attribute, or if it has a namespace attribute that conflicts with the target namespace of the contained schema.
It is a static error if the synthetic schema document does not satisfy the constraints described in [XML Schema Part 1] (section 5.1, Errors in Schema Construction and Structure). This includes, without loss of generality, conflicts such as multiple definitions of the same name.
Within an XSLT element that is required to be empty, any content other than comments or processing instructions, including any whitespace text node preserved using the xml:space="preserve" attribute, is a static error.
It is a static error if there is a stylesheet module in a package that specifies input-type-annotations="strip" and another stylesheet module that specifies input-type-annotations="preserve", or if a stylesheet module specifies the value strip or preserve and the same value is not specified on the xsl:package element of the containing package.
It is a static error if within any package the same NameTestXP appears in both an xsl:strip-space and an xsl:preserve-space declaration if both have the same import precedence. 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).
In the case of a prefixed lexical QName used as the value (or as part of the value) of an attribute in the stylesheet, or appearing within an XPath expression in the stylesheet, it is a static error if the defining element has no namespace node whose name matches the prefix of the lexical QName.
Where an attribute is defined to contain a pattern, it is a static error if the pattern does not match the production Pattern.
It is a static error if an unescaped left curly bracket appears in a fixed part of a value template without a matching right curly bracket.
It is a static error if an unescaped right curly bracket occurs in a fixed part of a value template.
An xsl:template element must have either a match attribute or a name attribute, or both. An xsl:template element that has no match attribute must have no mode attribute and no priority attribute. An xsl:template element that has no name attribute must have no visibility attribute.
The value of the priority attribute [ of the xsl:template element] must conform to the rules for the xs:decimal type defined in [XML Schema Part 2]. Negative values are permitted.
It is a static error if for any named or unnamed mode, a package explicitly specifies two conflicting values for the same attribute in different xsl:mode declarations having the same import precedence, unless there is another definition of the same attribute with higher import precedence. The attributes in question are the attributes other than name on the xsl:mode element.
It is a static error if the list of modes [in the mode attribute of xsl:template ] 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 #all appears together with any other value.
It is a static error if the values of the name attribute of two sibling xsl:param elements represent the same expanded QName.
It is a static error if a variable-binding element has a select attribute and has non-empty content.
It is a static error if a package contains more than one non-hidden binding of a global variable with the same name and same import precedence, unless it also contains another binding with the same name and higher import precedence.
It is a static error if a package contains an xsl:call-template instruction whose name attribute does not match the name attribute of any named template visible in the containing package (this includes any template defined in this package, as well as templates accepted from used packages whose visibility in this package is not hidden). For more details of the process of binding the called template, see 3.4.4.5 Binding References to Components.
It is a static error if a package contains more than one non-hidden template with the same name and the same import precedence, unless it also contains a template with the same name and higher import precedence.
It is a static error if two or more sibling xsl:with-param elements have name attributes that represent the same expanded QName.
In the case of xsl:call-template, it is a static error to pass a non-tunnel parameter named x to a template that does not have a non-tunnel template parameter named x, unless the xsl:call-template instruction is processed with XSLT 1.0 behavior.
It is a static error if a package contains both (a) a named template named T that is not overridden by another named template of higher import precedence and that has an explicitly mandatory non-tunnel parameter named P, and (b) an xsl:call-template instruction whose name attribute equals T and that has no non-tunnel xsl:with-param child element whose name attribute equals P. (All names are compared as QNames.)
It is a static error if the value of the use-attribute-sets attribute of an xsl:copy, xsl:element, or xsl:attribute-set element, or the xsl:use-attribute-sets attribute of a literal result element, is not a whitespace-separated sequence of EQNames, or if it contains an EQName that does not match the name attribute of any xsl:attribute-set declaration in the containing package.
It is a static error if a stylesheet function has a name that is in no namespace, unless the visibility of the function is private.
It is a static error if an xsl:param child of an xsl:function element has either a select attribute or non-empty content, unless it specifies required="no".
It is a static error if an xsl:param child of an xsl:function element specifies required="no", unless all following-sibling xsl:param elements also specify required="no".
It is a static error for a package to contain an xsl:function declaration F and an xsl:function declaration G such that F and G have the same expanded QName, F has lower import precedence than G, and the arity range of G includes part but not all of the arity range of F, unless G is itself eclipsed by another xsl:function declaration.
It is a static error for a package to contain an xsl:function declaration F and an xsl:function declaration G such that F and G have the same expanded QName and the same import precedence, if the arity ranges of F and G overlap in whole or in part, unless F and G are both eclipsed by another xsl:function declaration.
It is a static error if an attribute on a literal result element is in the XSLT namespace, unless it is one of the attributes explicitly defined in this specification.
It is a static error if a namespace prefix is used within the [xsl:]exclude-result-prefixes attribute and there is no namespace binding in scope for that prefix.
It is a static error if the value #default is used within the [xsl:]exclude-result-prefixes attribute and the parent element of the [xsl:]exclude-result-prefixes attribute has no default namespace.
It is a static error if within a package there is more than one such declaration [more than one xsl:namespace-alias declaration] with the same literal namespace URI and the same import precedence and different values for the target namespace URI, unless there is also an xsl:namespace-alias declaration with the same literal namespace URI and a higher import precedence.
It is a static error if a value other than #default is specified for either the stylesheet-prefix or the result-prefix attributes of the xsl:namespace-alias element when there is no in-scope binding for that namespace prefix.
It is a static error if the select attribute of the xsl:attribute element is present unless the element has empty content.
It is a static error if the select attribute of the xsl:text or xsl:value-of element is present when the content of the element is non-empty.
It is a static error if the select attribute of the xsl:processing-instruction element is present unless the element has empty content.
It is a static error if the select attribute of the xsl:namespace element is present when the element has content other than one or more xsl:fallback instructions, or if the select attribute is absent when the element has empty content.
It is a static error if the select attribute of the xsl:comment element is present unless the element has empty content.
It is a static error if the value attribute of xsl:number is present unless the select, level, count, and from attributes are all absent.
It is a static error if an xsl:sort element with a select attribute has non-empty content.
It is a static error if an xsl:sort element other than the first in a sequence of sibling xsl:sort elements has a stable attribute.
It is a static error if an xsl:perform-sort instruction with a select attribute has any content other than xsl:sort and xsl:fallback instructions.
It is a static error if the current-group function is used within a pattern.
It is a static error if the current-grouping-key function is used within a pattern.
These six attributes [the group-by, group-adjacent, group-starting-with, group-ending-with, split-when,and merge-when attributes of xsl:for-each-group ] are mutually exclusive: it is a static error if none of these attributes is present or if more than one of them is present.
It is a static error to specify the collation attribute or the composite attribute if neither the group-by attribute nor the group-adjacent attribute is specified.
It is a static error if the xsl:analyze-string instruction contains neither an xsl:matching-substring nor an xsl:non-matching-substring element.
It is a static error if an xsl:key declaration has a use attribute and has non-empty content, or if it has empty content and no use attribute.
It is a static error if the xsl:key declaration has a collation attribute whose value (after resolving against the base URI) is not a URI recognized by the implementation as referring to a collation.
It is a static error if there are several xsl:key declarations in the same package with the same key name and different effective collations. Two collations are the same if their URIs are equal under the rules for comparing xs:anyURI values, or if the implementation can determine that they are different URIs referring to the same collation.
It is a static error if there are several xsl:key declarations in a package with the same key name and different effective values for the composite attribute.
It is a static error if a named or unnamed decimal format contains two conflicting values for the same attribute in different xsl:decimal-format declarations having the same import precedence, unless there is another definition of the same attribute with higher import precedence.
It is a static error if the character specified in the zero-digit attribute is not a digit or is a digit that does not have the numeric value zero.
It is a static error if, for any named or unnamed decimal format, the properties identifying marker characters to be used in a picture string do not identify distinct values. These properties are decimal-separator, grouping-separator, exponent-separator, percent, per-mille, zero-digit, digit, and pattern-separator.
It is a static error if there is no namespace bound to the prefix on the element bearing the [xsl:]extension-element-prefixes attribute or, when #default is specified, if there is no default namespace.
It is a static error if both the [xsl:]type and [xsl:]validation attributes are present on the xsl:element, xsl:attribute, xsl:copy, xsl:copy-of, xsl:document, xsl:result-document, xsl:source-document, or xsl:merge-source elements, or on a literal result element.
It is a static error if the value of the type attribute of an xsl:element, xsl:attribute, xsl:copy, xsl:copy-of, xsl:document, xsl:result-document, xsl:source-document, or xsl:merge-source instruction, or the xsl:type attribute of a literal result element, is not a valid QName, or if it uses a prefix that is not defined in the applicable static namespaces of the containing instruction, or if the QName is not the name of a type definition included in the in-scope schema components for the package.
It is a static error if the value of the type attribute of an xsl:attribute instruction refers to a complex type definition
It is a static error if two xsl:output declarations within an output definition specify explicit values for the same attribute (other than cdata-section-elements, suppress-indentation, and use-character-maps), with the values of the attributes being not equal, unless there is another xsl:output declaration within the same output definition that has higher import precedence and that specifies an explicit value for the same attribute.
The value [of the method attribute on xsl:output ] must (if present) be a valid EQName. If it is a lexical QName in no namespace, then it identifies a method specified in [Serialization 4.0] and must be one of xml, html, xhtml, text, json, or adaptive.
It is a static error if a package contains two or more character maps with the same name and the same import precedence, unless it also contains another character map with the same name and higher import precedence.
It is a static error if a name in the use-character-maps attribute of the xsl:output or xsl:character-map elements does not match the name attribute of any xsl:character-map in the containing package.
It is a static error if a character map references itself, directly or indirectly, via a name in the use-character-maps attribute.
A non-schema-aware processormust raise a static error if a package includes an xsl:import-schema declaration.
A non-schema-aware processormust raise a static error if a package includes an [xsl:]type attribute; or an [xsl:]validation or [xsl:]default-validation attribute with a value other than strip, preserve, or lax; or an xsl:mode element whose typed attribute is equal to yes or strict; or an as attribute whose value is a SequenceType that can only match nodes with a type annotation other than xs:untyped or xs:untypedAtomic (for example, as="element(*, xs:integer)").
It is a static error if the number of xsl:merge-key children of a xsl:merge-source element is not equal to the number of xsl:merge-key children of another xsl:merge-source child of the same xsl:merge instruction.
It is a static error if after evaluating each xsl:package-location declaration and implementation-defined package location, no priority package location is found.
It is a static error if the package manifest returned by the priority package location does not conform to the rules of the implicit or explicit value of attribute format.
It is a static error if the package manifest returned by the priority package location does not conform to the name and version specified in an xsl:use-package declaration.
It is a static error if the attribute archive-type is present without the attribute path-in-archive, or if it does not have the value zip or an implementation-defined value.
It is a static error if a package is dependent on itself, where package A is defined as being dependent on package B if A contains an xsl:use-package declaration that references B, or if A contains an xsl:use-package declaration that references a package C that is itself dependent on B.
It is a static error if an xsl:use-package declaration appears in a stylesheet module that is not in the same stylesheet level as the principal stylesheet module of the package.
It is a static error 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 visibility attribute, and the component is also listed explicitly by name in an xsl:expose declaration.)
It is a static error if a token in the names attribute of xsl:expose, other than a wildcard, matches no component in the containing package.
It is a static error if the component attribute of xsl:expose specifies * (meaning all component kinds) and the names attribute is not a wildcard.
It is a static error if the effect of an xsl:expose declaration would be to make a component abstract, unless the component is already abstract in the absence of the xsl:expose declaration.
It is a static error if a token in the names attribute of xsl:accept, other than a wildcard, matches no component in the used package.
It is a static error if the component attribute of xsl:accept specifies * (meaning all component kinds) and the names attribute is not a wildcard.
It is a static error if the visibility assigned to a component by an xsl:accept 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 xsl:accept element is treated as not matching that component.
It is a static error if the xsl:use-package elements in a package manifest cause two or more homonymous components to be accepted with a visibility other than hidden.
It is a static error if a token in the names attribute of xsl:accept, other than a wildcard, matches the symbolic name of a component declared within an xsl:override child of the same xsl:use-package element.
It is a static error if a component declaration appearing as a child of xsl:override is homonymous with any other declaration in the using package, regardless of import precedence, including any other overriding declaration in the package manifest of the using package.
It is a static error if a component declaration appearing as a child of xsl:override does not match (is not homonymous with) some component in the used package.
It is a static error if the component referenced by an xsl:override declaration has visibility other than public or abstract
It is a static error if the signature of an overriding component is not compatible with the signature of the component that it is overriding.
It is a static error to use the component reference xsl:original when the overridden component has visibility="abstract".
It is a static error if a top-level package (as distinct from a library package) contains components whose visibility is abstract.
It is a static error, when the effective value of the declared-modes attribute of an xsl:package element is yes, 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.
It is a static error if more than one xsl:global-context-item declaration appears within a stylesheet module, or if several modules within a single package contain inconsistent xsl:global-context-item declarations
It is a static error if the as attribute is present [on the xsl:context-item element] when use="absent" is specified.
It is a static error if the as attribute is present [on the xsl:global-context-item element] when use="absent" is specified.
It is a static error if a template rule applicable to a mode that is defined with typed="strict" uses a match pattern that contains a RelativePathExprP whose first StepExprP is an AxisStepP whose ForwardStepP uses an axis whose principal node kind is Element and whose NodeTest is an EQName that does not correspond to the name of any global element declaration in the in-scope schema components.
It is a static error if an xsl:break or xsl:next-iteration element appears other than in a tail position within the sequence constructor forming the body of an xsl:iterate instruction.
It is a static error if the select attribute of xsl:break or xsl:on-completion is present and the instruction has children.
It is a static error if the name attribute of an xsl:with-param child of an xsl:next-iteration element does not match the name attribute of an xsl:param child of the innermost containing xsl:iterate instruction.
It is a static error if the select attribute of the xsl:try element is present and the element has children other than xsl:catch and xsl:fallback elements.
It is a static error if the select attribute of the xsl:catch element is present unless the element has empty content.
For the elements xsl:sequence, xsl:on-empty, xsl:on-non-empty, xsl:when, xsl:otherwise, xsl:matching-substring, xsl:non-matching-substring, xsl:map, xsl:map-entry, xsl:array, xsl:array-member, and xsl:result-document, it is a static error if the select attribute is present and the instruction has children other than xsl:fallback.
It is a static error if two sibling xsl:merge-source elements have the same name.
If the for-each-item attribute is present then the for-each-source, use-accumulators, and streamable attributes must all be absent. If either or both of the use-accumulators or streamable attributes is present then the for-each-source attribute must be present. If the for-each-source attribute is present then the for-each-item attribute must be absent.
It is a static error if an xsl:merge-key element with a select attribute has non-empty content.
It is a static errorXT if the list of accumulator names [in the use-accumulators attribute] contains an invalid token, contains the same token more than once, or contains the token #all along with any other value; or if any token (other than #all) is not the name of a declared-streamableSG accumulator visible in the containing package.
It is a static errorXT for a package to contain two or more accumulators with the same expanded QName and the same import precedence, unless there is another accumulator with the same expanded QName, and a higher import precedence.
It is a static errorXT for a an xsl:accumulator-rule element to specify capture="yes" unless it also specifies phase="end".
In the case of a template rule (that is, an xsl:template element having a match attribute) appearing as a child of xsl:override, it is a static error if the list of modes in the mode attribute contains #all or #unnamed, or if it contains #default and the default mode is the unnamed mode, or if the mode attribute is omitted when the default mode is the unnamed mode.
It is a static error if a variable declared with static="yes" is inconsistent with another static variable of the same name that is declared earlier in stylesheet tree order and that has lower import precedence.
It is a static error if an xsl:apply-imports element appears in a template rule declared within an xsl:override element. (To invoke the template rule that is being overridden, xsl:next-match should therefore be used.)
It is a static error if the current-merge-group function is used within a pattern.
It is a static error if the current-merge-key-array or current-merge-key function is used within a pattern.
It is a static error if a parameter to xsl:iterate is implicitly mandatory.
It is a static error if an xsl:mode declaration with one or more xsl:template children has no name attribute.
It is a static error if an xsl:mode declaration has a child xsl:template element with a name attribute, with a mode attribute, or with no match attribute.
It is a static error if an xsl:mode declaration having one or more child xsl:template elements has a default-mode attribute whose value differs from its name attribute, or if any of those child xsl:template elements has a default-mode attribute that differs from the name attribute of the xsl:mode declaration.
It is a static error if a package contains both (a) an xsl:mode declaration having one or more child xsl:template elements, and (b) an xsl:template declaration that is not one of those children but that references that xsl:mode declaration in its mode attribute.
It is a static error if a package contains (a) an xsl:mode declaration having one or more child xsl:template elements, and (b) a second xsl:mode declaration having the same name and the same import precedence.
It is a static error if a package contains two xsl:item-type or xsl:record-type declarations having the same name and the same import precedence, 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 reserved namespace, or if it has the same name as a type in the in-scope schema typesXP of the static context.
It is a static error for an item type named N to contain in its as attribute a reference to N, or to an item type that references N directly or indirectly.
It is a static error if a template ruleR has an as attribute S, and the template rule is applicable to a modeM that is declared with an as attribute T, and the sequence type S is not a subtype of the sequence type T as defined by the relationship subtype(S, T) in [XPath 4.0] section 3.3.1 Subtypes of Sequence Types.
It is a static error if the value of any [xsl:]schema-role in a stylesheet package does not match the value of the role attribute on some xsl:import-schema element in the same package.
It is a static error if the names of the fields in an xsl:record-type declaration are not distinct.
It is a static error if an xsl:field element has a default attribute unless it specifies required="no".
Type errors
It is a type error if the result sequence contains a function item.
It is a type error if the result of evaluating the sequence constructor cannot be coerced to the required type.
It is a type error if an xsl:apply-templates instruction with no select attribute is evaluated when the context item is not a node.
It is a type error if the supplied value of a variable cannot be converted to the required type.
It is a type error if the conversion of the supplied value of a parameter, or of the context item, does not match the required type, after applying any permitted conversions.
If the as attribute [of xsl:function ] is specified, then the result evaluated by the sequence constructor (see 5.7 Sequence Constructors) is converted to the required type, using the coercion rules. It is a type error if this conversion fails.
It is a type error to use the xsl:copy instruction with no select attribute when the context item is absent.
It is a type error to use the xsl:copy or xsl:copy-of instruction to copy a node that has namespace-sensitive content if the copy-namespaces attribute has the value no and its explicit or implicit validation attribute has the value preserve. It is also a type error if either of these instructions (with validation="preserve") 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 xs:QName or xs:NOTATION 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.
It is a type error if the xsl:number instruction is evaluated, with no value or select attribute, when the context item is not a node.
It is a type error if the result of evaluating the select attribute of the xsl:number instruction is anything other than a single node.
It is a type error if the result of evaluating the group-adjacent expression is anthe empty sequence or a sequence containing more than one item, unless composite="yes" is specified.
If the validation attribute of an xsl:element, xsl:attribute, xsl:copy, xsl:copy-of, or xsl:result-document instruction, or the xsl:validation attribute of a literal result element, has the effective valuestrict, and schema validity assessment concludes that the validity of the element or attribute is invalid or unknown, a type error occurs. As with other type errors, the error may be raised statically if it can be detected statically.
If the validation attribute of an xsl:element, xsl:attribute, xsl:copy, xsl:copy-of, or xsl:result-document instruction, or the xsl:validation attribute of a literal result element, has the effective valuestrict, and there is no matching top-level declaration in the schema, then a type error occurs. As with other type errors, the error may be raised statically if it can be detected statically.
If the validation attribute of an xsl:element, xsl:attribute, xsl:copy, xsl:copy-of, or xsl:result-document instruction, or the xsl:validation attribute of a literal result element, has the effective valuelax, and schema validity assessment concludes that the element or attribute is invalid, a type error occurs. As with other type errors, the error may be raised statically if it can be detected statically.
It is a type error if the value of the type attribute of an xsl:copy or xsl:copy-of instruction refers to a complex type definition and one or more of the items being copied is an attribute node.
It is a type error if an [xsl:]type attribute is defined for a constructed element or attribute, and the outcome of schema validity assessment against that type is that the validity property of that element or attribute information item is other than valid.
A type error occurs if a type or validation 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 xs:QName or xs:NOTATION.
A type error occurs [when a document node is validated] 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.
It is a type error if, when validating a document node, document-level constraints (such as ID/IDREF constraints) are not satisfied.
It is a type error if some item selected by a particular merge key in one input sequence is not comparable using the XPath le operator with the corresponding item selected by the corresponding sort key in another input sequence.
It is a type error if the xsl:context-item child of xsl:template 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 xsl:call-template is evaluated.
It is a type error if an xsl:apply-templates instruction in a particular mode selects an item that does not satisfy the constraints imposed by the @typed attribute.
It is a type error if the result of evaluating the expression in the with-params attribute of the xsl:evaluate instruction is anything other than a single map of type map(xs:QName, item()*).
It is a type error if the result of evaluating the namespace-context attribute of the xsl:evaluate instruction is anything other than a single node.
It is a type error if the result of evaluating the select expression [of the xsl:copy element] is a sequence of more than one item.
A type error occurs if the result of the input sequence [of an xsl:map instruction] is not an instance of the required type map(*)*.
Dynamic errors
It is a dynamic error if the effective value of an attribute written using curly brackets, in a position where an attribute value template 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.
It is a dynamic error if the invocation of the stylesheet specifies a template name that does not match the expanded QName of a named template defined in the stylesheet, whose visibility is public or final.
It is a dynamic error if the invocation of the stylesheet specifies a function name and arity that does not match the expanded QName and arity of a named stylesheet function defined in the stylesheet, whose visibility is public or final.
It is a dynamic error if the invocation of the stylesheet specifies an initial mode when no initial match selection is supplied (either explicitly, or defaulted to the global context item).
It is a dynamic error if the invocation of the stylesheet specifies an initial mode and the specified mode is not eligible as an initial mode (as defined above).
It is a dynamic error if a stylesheet declares a visible stylesheet parameter that is explicitly or implicitly 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 import precedence. If the parameter is a static parameter then the value must be supplied prior to the static analysis phase.
It is a dynamic error if an element has an effective version of V (with V < 4.0) when the implementation does not support backwards compatible behavior for XSLT version V.
Where the result of evaluating an XPath expression (or an attribute value template) is required to be a lexical QName, or if it is permitted to be a lexical QName and the actual value takes the form of a lexical QName, then unless otherwise specified it is a dynamic error if the value has a prefix and the defining element has no namespace node whose name matches that prefix. This error may be raised as a static error if the value of the expression can be determined statically.
It is a dynamic error 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.
It is a dynamic error if the sequence used to construct the content of a document node contains a namespace node or attribute node.
It is a dynamic error if the sequence contains two or more namespace nodes having the same name but different string values (that is, namespace nodes that map the same prefix to different namespace URIs).
It is a dynamic error 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).
It is a dynamic error if the conflict resolution algorithm for template rules leaves more than one matching template rule when the declaration of the relevant mode has an on-multiple-match attribute with the value fail.
It is a dynamic error if xsl:apply-templates, xsl:apply-imports or xsl:next-match is used to process an item using a mode whose declaration specifies on-no-match="fail" when there is no template rule in the stylesheet whose match pattern matches that item.
It is a dynamic error if xsl:apply-imports or xsl:next-match is evaluated when the current template rule is absent.
It is a dynamic error if a call on the apply-templates function selects a mode that is not explicitly declared in the containing package, or accepted from a used package, or whose visibility is private.
In general, a circularity in a stylesheet is a dynamic error.
It is a dynamic error if a template that has an explicitly mandatory or implicitly mandatory parameter is invoked without supplying a value for that parameter.
It is a dynamic error if the effective value of the name attribute [of the xsl:element instruction] is not a lexical QName.
In the case of an xsl:element instruction with no namespace attribute, it is a dynamic error if the effective value of the name attribute is a lexical QName whose prefix is not declared in the applicable static namespaces for the xsl:element instruction.
It is a dynamic error if the effective value of the namespace attribute [of the xsl:element instruction] is not in the lexical space of the xs:anyURI datatype or if it is the string http://www.w3.org/2000/xmlns/.
It is a dynamic error if the effective value of the name attribute [of an xsl:attribute instruction] is not a lexical QName.
In the case of an xsl:attribute instruction with no namespace attribute, it is a dynamic error if the effective value of the name attribute is the string xmlns.
In the case of an xsl:attribute instruction with no namespace attribute, it is a dynamic error if the effective value of the name attribute is a lexical QName whose prefix is not declared in the applicable static namespaces for the xsl:attribute instruction.
It is a dynamic error if the effective value of the namespace attribute [of the xsl:attribute instruction] is not in the lexical space of the xs:anyURI datatype or if it is the string http://www.w3.org/2000/xmlns/.
It is a dynamic error if the effective value of the name attribute [of the xsl:processing-instruction instruction] is not both an NCNameNames and a PITargetXML.
It is a dynamic error if the string value of the new namespace node is not valid in the lexical space of the datatype xs:anyURI, or if it is the string http://www.w3.org/2000/xmlns/.
It is a dynamic error if the effective value of the name attribute [of the xsl:namespace instruction] is neither a zero-length string nor an NCNameNames, or if it is xmlns.
It is a dynamic error if the xsl:namespace instruction generates a namespace node whose name is xml and whose string value is not http://www.w3.org/XML/1998/namespace, or a namespace node whose string value is http://www.w3.org/XML/1998/namespace and whose name is not xml.
It is a dynamic error if evaluating the select attribute or the contained sequence constructor of an xsl:namespace instruction results in a zero-length string.
It is a dynamic error if any undiscarded item in the atomized sequence supplied as the value of the value attribute of xsl:number cannot be converted to an integer, or if the resulting integer is less than 0 (zero).
It is a dynamic error if, for any sort key component, the set of sort key values evaluated for all the items in the initial sequence, after any type conversion requested, contains a pair of atomic items that are not comparable using the fn:compare. If the processor is able to detect the error statically, it may optionally raise it as a static error.
It is a dynamic error if the collation attribute of xsl:sort (after resolving against the base URI) is not a URI that is recognized by the implementation as referring to a collation.
It is a dynamic error if the current-group function is used when the current group is absent , or when it is invoked in the course of evaluating a pattern. The error may be reported statically if it can be detected statically.
It is a dynamic error if the current-grouping-key function is used when the current grouping key is absent, or when it is invoked in the course of evaluating a pattern. The error may be reported statically if it can be detected statically.
It is a dynamic error if the collation URI specified to xsl:for-each-group (after resolving against the base URI) is a collation that is not recognized by the implementation. (For notes, [see ERR XTDE1035].)
It is a dynamic error if the effective value of the regex attribute [of the xsl:analyze-string instruction] does not conform to the required syntax for regular expressions, as specified in [Functions and Operators 4.0]. If the regular expression is known statically (for example, if the attribute does not contain any expressions enclosed in curly brackets) then the processor may raise the error as a static error.
It is a dynamic error if the effective value of the flags attribute [of the xsl:analyze-string instruction] has a value other than the values defined in [Functions and Operators 4.0]. If the value of the attribute is known statically (for example, if the attribute does not contain any expressions enclosed in curly brackets) then the processor may raise the error as a static error.
When a URI reference [supplied to the document function] contains a fragment identifier, it is a 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).
When a URI reference [supplied to the document function] is a relative reference, it is a dynamic error 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.
It is a dynamic error if the value of $key-name 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 xsl:key declaration in the containing package. If the processor is able to detect the error statically (for example, when the argument is supplied as a string literal), then the processor may optionally raise this as a static error.
It is a dynamic error if the key identified in a call to the function map-for-key is unsuitable because it uses a collation other than the Unicode Codepoint Collation, or because it is defined with composite=yes.
It is a dynamic error to call the key function with two arguments if there is no context node, 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.
If the current function is evaluated within an expression that is evaluated when the context item is absent, a dynamic error occurs.
It is a dynamic error if $node, or the context item if the second argument is omitted, is a node in a tree whose root is not a document node.
It is a dynamic error if $node, or the context item if the second argument is omitted, is a node in a tree whose root is not a document node.
It is a dynamic error if the value supplied as the $property-name argument [to the system-property function] 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 may optionally raise this as a static error.
It is a dynamic error if the $name argument [passed to the function-available function] evaluates to a string that is not a valid EQName, or if the value is a lexical QName 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 may optionally raise this as a static error.
It is a dynamic error 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.
When the containing element is processed with XSLT 1.0 behavior, it is a dynamic error to evaluate an extension function call if no implementation of the extension function is available.
It is a dynamic error if the argument [passed to the type-available function] evaluates to a string that is not a valid EQName, or if the value is a lexical QName 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 may optionally raise this as a static error.
It is a dynamic error if the argument [passed to the element-available function] evaluates to a string that is not a valid EQName, or if the value is a lexical QName 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 may optionally raise this as a static error.
When a processor performs fallback for an extension instruction that is not recognized, if the instruction element has one or more xsl:fallback children, then the content of each of the xsl:fallback children must be evaluated; it is a dynamic error if it has no xsl:fallback children.
It is a dynamic error if the effective value of the format attribute [of an xsl:result-document element] is not a valid EQName, or if it does not match the expanded QName of an output definition in the containing package. If the processor is able to detect the error statically (for example, when the format attribute contains no curly brackets), then the processor may optionally raise this as a static error.
It is a dynamic error to evaluate the xsl:result-document instruction in temporary output state.
It is a dynamic error for a transformation to generate two or more final result trees with the same URI.
It is a dynamic error for a stylesheet 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.
A dynamic errormay be raised if the input to the processor includes an item that requires availability of an optional feature that the processor does not provide.
It is a dynamic error if there are two xsl:merge-key elements that occupy corresponding positions among the xsl:merge-key children of two different xsl:merge-source elements and that have differing effective values for any of the attributes lang, order, collation, case-order, or data-type. Values are considered to differ if they have different effective values. In the case of the collation attribute, the values are compared as absolute URIs after resolving against the base URI. The error may be raised statically if it is detected statically.
It is a dynamic error if any input sequence to an xsl:merge instruction contains two items that are not correctly sorted according to the merge key values defined on the xsl:merge-key children of the corresponding xsl:merge-source element, when compared using the collation rules defined by the attributes of the corresponding xsl:merge-key children of the xsl:merge instruction, unless the attribute sort-before-merge is present with the value yes.
It is a dynamic error if an invocation of an abstract component is evaluated.
It is a dynamic error if an xsl:global-context-item declaration specifies use="required", and no global context item is supplied.
It is a dynamic error if the target expression [of an xsl:evaluate instruction] is not a valid expression (that is, if a static error occurs when analyzing the string according to the rules of the XPath specification).
It is a dynamic error if an xsl:evaluate instruction is evaluated when use of xsl:evaluate has been statically or dynamically disabled.
It is a dynamic error if the value of the first argument to the accumulator-before or accumulator-after function is a string that is not a valid 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 xsl:accumulator declaration appearing in the package 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 may optionally raise this as a static error.
It is a dynamic error to call the accumulator-before or accumulator-after function when there is no context item.
It is a type error to call the accumulator-before or accumulator-after function when the context item is not a node, or when it is an attribute or namespace node.
It is a dynamic error to call the accumulator-before or accumulator-after 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 streamable="yes"). Implementations may raise this error but are not required to do so, if they are capable of streaming documents without imposing this restriction.
In the absence of the [xsl:]duplicates attribute, a dynamic error occurs if the set of keys in the maps making up the input sequence [of an xsl:map or xsl:record instruction] contains duplicates.
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 may report this as a static error if it can be detected statically. Alternatively a processor may report this as a dynamic error. As a further option, a processor may fail catastrophically when this error occurs.
It is a dynamic error if the current-merge-group function is used when the current merge group is absent. The error may be reported statically if it can be detected statically.
It is a dynamic error if the $source argument of the current-merge-group function (when supplied) does not match the name attribute of any xsl:merge-source element for the current merge operation. The error may be reported statically if it can be detected statically.
It is a dynamic error if the current-merge-key-array or current-merge-key function is used when the current merge key is absent, or when it is invoked in the course of evaluating a pattern. The error may be reported statically if it can be detected statically.
It is a dynamic error if an xsl:try instruction is unable to recover the state of a final result tree because recovery has been disabled by use of the attribute rollback-output="no".
It is a dynamic error if an xsl:array instruction with a for-each attribute includes items constructed using an xsl:array-member instruction mixed (in the same array member) with items not so constructed.
When a transformation is terminated by use of <xsl:message terminate="yes"/>, the effect is the same as when a dynamic error occurs during the transformation. The default error code is XTMM9000; this may be overridden using the error-code attribute of the xsl:message instruction.
When a transformation is terminated by use of xsl:assert, the effect is the same as when a dynamic error occurs during the transformation. The default error code is XTMM9001; this may be overridden using the error-code attribute of the xsl:assert instruction.