View Old View New View Both View Only Previous Next

This draft contains only sections that have differences from the version that it modified.

W3C

XSL Transformations (XSLT) Version 4.0

W3C Editor's Draft 23 February 2026

This version:
https://qt4cg.org/specifications/xslt-40/
Latest version:
https://qt4cg.org/specifications/xslt-40/
Most recent Recommendation of XSL Transformations (XSLT):
https://www.w3.org/TR/xslt-30/
Editor:
Michael Kay, Saxonica <http://www.saxonica.com/>

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)


Abstract

This specification defines the syntax and semantics of XSLT 4.0, a language designed primarily for transforming XML documents into other XML documents.

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 3.04.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.

Status of this Document

This section describes the status of this document at the time of its publication. Other documents may supersede this document. A list of current W3C publications and the latest revision of this technical report can be found in the W3C technical reports index at https://www.w3.org/TR/.

This document has no official standing. It is produced by the editor as a proposal for community review. Insofar as it copies large amounts of text from the W3C XSLT 3.0 Recommendation, W3C copyright and similar provisions apply.

Dedication

The publications of this community group are dedicated to our co-chair, Michael Sperberg-McQueen (1954–2024).


1 Introduction

1.1 What is XSLT?

XSLT is a programming language designed principally to transform data.

A transformation in the XSLT language is expressed in the form of a stylesheet. A stylesheet is made up of one or more well-formed XML [XML 1.0] documents conforming to the Namespaces in XML Recommendation [Namespaces in XML].

A stylesheet generally includes elements that are defined by XSLT as well as elements that are not defined by XSLT. XSLT-defined elements are distinguished by use of the namespace http://www.w3.org/1999/XSL/Transform (see 3.1.1 XSLT Namespace), which is referred to in this specification as the XSLT namespace. Thus this specification is a definition of the syntax and semantics of the XSLT namespace.

The term stylesheet reflects the fact that one of the important roles of XSLT is to add styling information to an XML source document, by transforming it into a document consisting of XSL formatting objects (see [XSL-FO]), or into another presentation-oriented format such as HTML, XHTML, or SVG. However, XSLT is used for a wide range of transformation tasks, not exclusively for formatting and presentation applications.

A transformation expressed in XSLT describes rules for transforming input data into output data. The inputs and outputs will all be instances of the XDM data model, described in [XDM 3.04.0]. In the simplest and most common case, the input is an XML document referred to as the source document or source tree, and the output is an XML document referred to as the result tree. It is also possible to process multiple source documents, to generate multiple result documents, and to handle formats other than XML.

The transformation is achieved by a set of template rules. A template rule associates a pattern, which typically matches nodes in the source document, with a sequence constructor. In many cases, evaluating the sequence constructor will cause new nodes to be constructed, which can be used to produce part of a result tree. The structure of the result trees can be completely different from the structure of the source trees. In constructing a result tree, nodes from the source trees can be filtered and reordered, and arbitrary structure can be added. Because patterns can point to nodes according to typological features, a stylesheet can be applicable to a wide class of source documents that have similar tree structures.

Stylesheets are modular; they may contain several packages developed independently of each other, and each package may consist of several stylesheet modules.

[Definition: A stylesheet consists of one or more packages: specifically, one top-level package and zero or more library packages.]

[Definition: 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.5.2 Dependencies between Packages.]

[Definition: Every package within a stylesheet, other than the top-level package, is referred to as a library package.]

[Definition: 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.11.2 Stylesheet Inclusion and 3.11.3 Stylesheet Import.]

1.2 What’s New in XSLT 4.0?

Changes in 4.0 

  1. Use the arrows to browse significant changes since the 3.0 version of this specification.

  2. Sections with significant changes are marked Δ in the table of contents.

XSLT 4.0 is a revised version of the XSLT 3.0 Recommendation [XSLT 3.0] published on 8 June 2017.

The changes in this version of the language are relatively minor usability enhancements. There are no changes to the data model or processing model. Instead, the specification attempts to fill a number of gaps in functionality resulting from feedback from XSLT 3.0 users. The main areas covered are:

  • Enhancements to the type system to allow more expressive constraints, especially for maps and atomic values.

  • Additional functionality for processing arrays.

  • Exploitation of the power afforded by first-class function items.

XSLT 4.0 also includes optional facilities to serialize the results of a transformation, by means of an interface to the serialization component described in [XSLT and XQuery Serialization 4.0].

XSLT 4.0 requires support for XPath 4.0.

A full list of changes is at I Changes since XSLT 3.0.

2 Concepts

2.1 Terminology

Changes in 4.0  

  1. The term atomic value has been replaced by atomic item.   [Issue 1337 PR 1361 2 August 2024]

For a full glossary of terms, see B Glossary.

[Definition: 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.]

[Definition: A specific product that performs the functions of an XSLT processor is referred to as an implementation.]

[Definition: The term tree is used (as in [XDM 3.04.0]) to refer to the aggregate consisting of a parentless node together with all its descendant nodes, plus all their attributes and namespaces.]

Note:

The use of the term tree in this document in phrases such as source tree, result tree, and temporary tree does not imply the use of a data structure in memory that holds the entire contents of the document at one time. It implies rather a logical view of the XML input and output in which elements have a hierarchic relationship to each other. When a source document is being processed in a streaming manner, access to the nodes in this tree is constrained, but it is still viewed and described as a tree.

The output of a transformation consists of the following:

  1. [Definition: A principal result: this can be any sequence of items (as defined in [XDM 3.04.0]).] The principal result is the value returned by the function or template in the stylesheet that is nominated as the entry point, as described in 2.3 Initiating a Transformation.

  2. [Definition: Zero or more secondary results: each secondary result can be any sequence of items (as defined in [XDM 3.04.0]).] A secondary result is the value returned by evaluating the body of an xsl:result-document instruction.

  3. Zero or more messages. Messages are generated by the xsl:message and xsl:assert instructions, and are described in 23.1 Messages and 23.2 Assertions.

  4. Static or dynamic errors: see 2.14 Error Handling.

The principal result and the secondary results may be post-processed as described in 2.3.6 Post-processing the Raw Result.

[Definition: 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.]

[Definition: 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.] Any final result tree may be serialized as described in 26 Serialization.

[Definition: 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.]

[Definition: The term temporary tree means any tree that is neither a source tree nor a final result tree.] Temporary trees are used to hold intermediate results during the execution of the transformation.

Unless otherwise stated, the term “tree” refers to a tree rooted at a parentless node: that is, the term does not include subtrees of larger trees. Every node therefore belongs to exactly one tree.

In this specification the phrases must, must not, should, should not, may, required, and recommended, when used in normative text and rendered in small capitals, are to be interpreted as described in [RFC2119].

Where the phrase must, must not, or required relates to the behavior of the XSLT processor, then an implementation is not conformant unless it behaves as specified, subject to the more detailed rules in 27 Conformance.

Where the phrase must, must not, or required relates to a stylesheet then the processor must enforce this constraint on stylesheets by raising an error if the constraint is not satisfied.

Where the phrase should, should not, or recommended relates to a stylesheet then a processor may produce warning messages if the constraint is not satisfied, but must not treat this as an error.

[Definition: 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.]

[Definition: 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.] (This might apply, for example, to limits on the size of source documents that can be transformed.)

In all cases where this specification leaves the behavior implementation-defined or implementation-dependent, the implementation has the option of providing mechanisms that allow the user to influence the behavior.

A paragraph labeled as a Note or described as an example is non-normative.

Many terms used in this document are defined in the XPath specification [XPath 4.0] or the XDM specification [XDM 3.04.0]. Particular attention is drawn to the following:

  • [Definition: The term atomization is defined in [XPath 4.0] section Section 2.5.3 AtomizationXP. 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 3.04.0]. Arrays (see 22 Arrays) are atomized by atomizing their members, recursively.] For some items (for example, elements with element-only content, function items, and maps, atomization raises a dynamic error.

  • [Definition: The term typed value is defined in [XDM 4.0] section Section 5.157.5.14 typed-value Accessor DM30. 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.]

  • [Definition: The term string value is defined in [XDM 4.0] section Section 5.137.5.12 string-value Accessor DM30. 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.]

  • [Definition: The term XPath 1.0 compatibility mode is defined in [XPath 4.0] section Section 2.2.1 Static ContextXP. 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.]

  • [Definition: The term function definition is defined in [XPath 4.0] section Section 2.2.1 Static ContextXP. 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]]

  • [Definition: 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.]

2.3 Initiating a Transformation

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.13.3 Conditional Element Inclusion) and shadow attributes (see 3.13.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.

2.3.2 Priming a Stylesheet

The information needed when priming a stylesheet is as follows:

  • A set (possibly empty) of values for non-static stylesheet parameters (see 9.5 Global Variables and Parameters). These values are available for use within expressions in the stylesheet. As a minimum, values must be supplied for any parameters declared with the attribute required="yes".

    A supplied value is converted if necessary to the declared type of the stylesheet parameter using the coercion rules.

    Note:

    Non-static stylesheet parameters are implicitly public, which ensures that all the parameters in the stylesheet for which values can be supplied externally have distinct names. Static parameters, by contrast, are local to a package.

  • [Definition: 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]. [XSLT 3.0 Erratum E7, bug 30179].

    Note:

    In previous releases of this specification, a single node was typically supplied to represent the source document for the transformation. This node was used as the target node for the implicit call on xsl:apply-templates used to start the transformation process (now called the initial match selection), and the root node of the containing tree was used as the context item for evaluation of global variables (now called the global context item). This relationship between the initial match selection and the global context item is likely to be found for compatibility reasons in a transformation API designed to work with earlier versions of this specification, but it is no longer a necessary relationship; the two values can in principle be completely independent of each other.

    Stylesheet authors wanting to write code that can be invoked using legacy APIs should not rely on the caller being able to supply different values for the initial match selection and the global context item.

    In XPath 4.0, the concept of context item has been generalized and is now referred to as the context valueXP. For XSLT 4.0, however, the global context item is still constrained to be either a single item, or absent.

    The value given to the global context item (and the values given to stylesheet parameters) cannot be nodes in a streamed document. This rule ensures that all global variables can freely navigate within the relevant tree, with no constraints imposed by the streamability rules.

    The global context item is potentially used when initializing global variables and parameters. If the initialization of any global variables or parameter depends on the context item, a dynamic error can occur if the context item is absent. It is implementation-defined whether this error occurs during priming of the stylesheet or subsequently when the variable is referenced; and it is implementation-defined whether the error occurs at all if the variable or parameter is never referenced. The error can be suppressed by use of xsl:try and xsl:catch within the sequence constructor used to initialize the variable or parameter. It cannot be suppressed by use of xsl:try around a reference to the global variable.

    In a library package, the context item, context position, and context size used for evaluation of global variables will be absent, and the evaluation of any expression that references these values will result in a dynamic error. This will also be the case in the top-level package if no global context item is supplied.

    Note:

    If a context item is available within a global variable declaration, then the context position and context size will always be 1 (one).

    Note:

    For maximum reusability of code, it is best to avoid use of the context item when initializing global variables and parameters. Instead, all external information should be supplied using named stylesheet parameters, ideally with namespaces, to avoid confusion and conflicts in the information supplied externally to different packages.

    When a stylesheet parameter is defined in a library package, it is possible for a using package to supply a value for the parameter by overriding the parameter declaration within an xsl:override element. If the using package is the top-level package then the overriding declaration can refer to the global context item.

  • A mechanism for obtaining a document node and a media type, given an absolute URI. The total set of available documents (modeled as a mapping from URIs to document nodes) forms part of the context for evaluating XPath expressions, specifically the doc function. The XSLT document function additionally requires the media type of the resource representation, for use in interpreting any fragment identifier present within a URI Reference.

    Note:

    The set of documents that are available to the stylesheet is implementation-dependent, as is the processing that is carried out to construct a tree representing the resource retrieved using a given URI. Some possible ways of constructing a document (specifically, rules for constructing a document from an Infoset or from a PSVI) are described in [XDM 3.04.0].

Once a stylesheet is primed, the values of global variables remain stable through all component invocations. In addition, priming a stylesheet creates an execution scopeFO during which the dynamic context and all calls on deterministicFO functions remain stable; for example two calls on the current-dateTime function within an execution scope are defined to return the same result.

Parameters passed to the transformation by the client application when a stylesheet is primed are matched against stylesheet parameters (see 9.5 Global Variables and Parameters), not against the template parameters of any template executed during the course of the transformation.

[ERR XTDE0050] 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.

2.3.6 Post-processing the Raw Result

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.)

  1. The raw result (a sequence of values) may be returned directly to the calling application.

  2. 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.

  3. 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.

2.3.6.1 Result Tree Construction

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 normalizationSER30SE as defined in [XSLT and XQuery Serialization][xslt-xquery-serialization-30]. 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. [XSLT 3.0 Erratum E14, bug 30208].

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 an 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.

2.3.6.2 Serializing the Result

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 normalizationSER30SE, takes place for some output methods but not others. For example, if the json output method (defined in [XSLT and XQuery 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 an 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 an 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.

2.7 Parsing and Serialization

An XSLT stylesheet describes a process that constructs a set of results from a set of inputs. The inputs are the data provided at stylesheet invocation, as described in 2.3 Initiating a Transformation. The results include the principal result (an arbitrary sequence), which is the result of the initial component invocation, together with any secondary results produced using xsl:result-document instructions.

The stylesheet does not describe how a source tree is constructed. Some possible ways of constructing source trees are described in [XDM 3.04.0]. Frequently an implementation will operate in conjunction with an XML parser (or more strictly, in the terminology of [XML 1.0], an XML processor), to build a source tree from an input XML document. An implementation may also provide an application programming interface allowing the tree to be constructed directly, or allowing it to be supplied in the form of a DOM Document object (see [DOM Level 2]). This is outside the scope of this specification. Users should be aware, however, that since the input to the transformation is a tree conforming to the XDM data model as described in [XDM 3.04.0], constructs that might exist in the original XML document, or in the DOM, but which are not within the scope of the data model, cannot be processed by the stylesheet and cannot be guaranteed to remain unchanged in the transformation output. Such constructs include CDATA section boundaries, the use of entity references, and the DOCTYPE declaration and internal DTD subset.

[Definition: 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.]

Like parsing, serialization is not part of the transformation process, and it is not required that an XSLT processor must be able to perform serialization. However, for pragmatic reasons, this specification describes declarations (the xsl:output element and the xsl:character-map declarations, see 26 Serialization), and attributes on the xsl:result-document instruction, that allow a stylesheet to specify the desired properties of a serialized output file. When serialization is not being performed, either because the implementation does not support the serialization option, or because the user is executing the transformation in a way that does not invoke serialization, then the content of the xsl:output and xsl:character-map declarations has no effect. Under these circumstances the processor may raise any errors in an xsl:output or xsl:character-map declaration, or in the serialization attributes of xsl:result-document, but is not required to do so.

2.10 Stylesheets and XML Schemas

Changes in 4.0  

  1. Different parts of a stylesheet may now use different imported schemas.   [Issue 451 PR 1819 18 February 2025]

An XSLT stylesheet can make use of information from a schema. An XSLT transformation can take place in the absence of a schema (and, indeed, in the absence of a DTD), but where the source document has undergone schema validity assessment, the XSLT processor has access to the type information associated with individual nodes, not merely to the untyped text.

Information from a schema can be used both statically (when the stylesheet is compiled), and dynamically (during evaluation of the stylesheet to transform a source document).

There are places within a stylesheet, and within XPath expressions and patterns in a stylesheet, where it is possible to refer to named type definitions in a schema, or to element and attribute declarations. For example, it is possible to declare the types expected for the parameters of a function. This is done using a SequenceType.

[Definition: 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].]

[Definition: Type definitions and element and attribute declarations are referred to collectively as schema components.]

[Definition: The schema components that may be referenced by name in a package are referred to as the in-scope schema components.]

The set of in-scope schema components may vary between one package and another, and between different parts of the same package, but as explained in 3.15 Importing Schema Components, the schema components used in different parts of the stylesheet must be consistent with each other.

The conformance rules for XSLT 4.0, defined in 27 Conformance, distinguish between a basic XSLT processor and a schema-aware XSLT processor. As the names suggest, a basic XSLT processor does not support the features of XSLT that require access to schema information, either statically or dynamically. A stylesheet that works with a basic XSLT processor will produce the same results with a schema-aware XSLT processor provided that the source documents are untyped (that is, they are not validated against a schema). However, if source documents are validated against a schema then the results may be different from the case where they are not validated. Some constructs that work on untyped data may fail with typed data (for example, an attribute of type xs:date cannot be used as an argument of the substring function) and other constructs may produce different results depending on the datatype (for example, given the element <product price="10.00" discount="2.00"/>, the expression @price gt @discount will return true if the attributes have type xs:decimal, but will return false if they are untyped).

There is a standard set of type definitions that are always available as in-scope schema components in every stylesheet. These are defined in 3.14 Built-in Types.

The remainder of this section describes facilities that are available only with a schema-aware XSLT processor.

Additional schema components (type definitions, element declarations, and attribute declarations) may be added to the in-scope schema components by means of the xsl:import-schema declaration in a stylesheet.

The xsl:import-schema declaration may reference an external schema document by means of a URI, or it may contain an inline xs:schema element.

An xsl:import-schema declaration may include a role attribute, which indicates that the schema components are only to be present in the static context of a region of the stylesheet where they are explicitly invoked by means of an [xsl:]schema-role attribute.

It is only necessary to import a schema explicitly if one or more of its schema components are referenced explicitly by name in the stylesheet; it is not necessary to import a schema merely because the stylesheet is used to process a source document that has been assessed against that schema. It is possible to make use of the information resulting from schema assessment (for example, the fact that a particular attribute holds a date) even if no schema has been imported by the stylesheet.

Importing a schema does not of itself say anything about the type of the source document that the stylesheet is expected to process. The imported type definitions can be used for temporary nodes or for nodes on a result tree just as much as for nodes in source documents. It is possible to make assertions about the type of an input document by means of tests within the stylesheet. For example:

Example: Asserting the Required Type of the Source Document
<xsl:mode typed="lax"/>
<xsl:global-context-item use="required"
            as="document-node(schema-element(my:invoice))"/>

This example will cause the transformation to fail with an error message, unless the global context item is valid against the top-level element declaration my:invoice, and has been annotated as such.

A schema-role attribute could be added to the declaration to indicate which schema the element declaration my:invoice is to be taken from.

The setting typed="lax" further ensures that in any match pattern for a template rule in this mode, an element name that corresponds to the name of an element declaration in the schema is taken as referring to elements validated against that declaration: for example, match="employee" will only match a validated employee element. Selecting this option enables the XSLT processor to do more compile-time type-checking against the schema, for example it allows the processor to produce warning or error messages when path expressions contain misspelt element names, or confuse an element with an attribute.

It is also true that importing a schema does not of itself say anything about the structure of the result tree. It is possible to request validation of a result tree against the schema by using the xsl:result-document instruction, for example:

Example: Requesting Validation of the Result Document
<xsl:template match="/">
  <xsl:result-document validation="strict">
    <xhtml:html>
      <xsl:apply-templates/>
    </xhtml:html>
  </xsl:result-document>
</xsl:template>

This example will cause the transformation to fail with an error message unless the document element of the result document is valid against the top-level element declaration xhtml:html.

A schema-role attribute could be added to the xsl:result-document instruction to indicate which schema the document is to be validated against.

It is possible that a source document may contain nodes whose type annotation is not one of the types imported by the stylesheet. This creates a potential problem because in the case of an expression such as data(.) instance of xs:integer the system needs to know whether the type named in the type annotation of the context node is derived by restriction from the type xs:integer. This information is not explicitly available in an XDM tree, as defined in [XDM 3.04.0]. The implementation may choose one of several strategies for dealing with this situation:

  1. The processor may raise a dynamic error if a source document is found to contain a type annotation that is not known to the processor.

  2. The processor may maintain additional metadata, beyond that described in [XDM 3.04.0], that allows the source document to be processed as if all the necessary schema information had been imported using xsl:import-schema. Such metadata might be held in the data structure representing the source document itself, or it might be held in a system catalog or repository.

  3. The processor may be configured to use a fixed set of schemas, which are automatically used to validate all source documents before they can be supplied as input to a transformation. In this case it is impossible for a source document to have a type annotation that the processor is not aware of.

  4. The processor may be configured to treat the source document as if no schema processing had been performed, that is, effectively to strip all type annotations from elements and attributes on input, marking them instead as having type xs:untyped and xs:untypedAtomic respectively.

Where a stylesheet author chooses to make assertions about the types of nodes or of variables and parameters, it is possible for an XSLT processor to perform static analysis of the stylesheet (that is, analysis in the absence of any source document). Such analysis may reveal errors that would otherwise not be discovered until the transformation is actually executed. An XSLT processor is not required to perform such static type-checking. Under some circumstances (see 2.14 Error Handling) type errors that are detected early may be raised as static errors. In addition an implementation may report any condition found during static analysis as a warning, provided that this does not prevent the stylesheet being evaluated as described by this specification.

A stylesheet can also control the type annotations of nodes that it constructs in a result tree. This can be done in a number of ways.

  • It is possible to request explicit validation of a complete document, that is, a result tree rooted at a document node. Validation is either strict or lax, as described in [XML Schema Part 1]. If validation of a result tree fails (strictly speaking, if the outcome of the validity assessment is invalid), then the transformation fails, but in all other cases, the element and attribute nodes of the tree will be annotated with the names of the types to which these nodes conform. These type annotations will be discarded if the result tree is serialized as an XML document, but they remain available when the result tree is passed to an application (perhaps another stylesheet) for further processing.

  • It is also possible to validate individual element and attribute nodes as they are constructed. This is done using the type and validation attributes of the xsl:element, xsl:attribute, xsl:copy, and xsl:copy-of instructions, or the xsl:type and xsl:validation attributes of a literal result element.

  • When elements, attributes, or document nodes are copied, either explicitly using the xsl:copy or xsl:copy-of instructions, or implicitly when nodes in a sequence are attached to a new parent node, the options validation="strip" and validation="preserve" are available, to control whether existing type annotations are to be retained or not.

When nodes in a temporary tree are validated, type information is available for use by operations carried out on the temporary tree, in the same way as for a source document that has undergone schema assessment.

For details of how validation of element and attribute nodes works, see 25.4 Validation.

2.14 Error Handling

[Definition: 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.]

Generally, errors in the structure of the stylesheet, or in the syntax of XPath expressions contained in the stylesheet, are classified as static errors. Where this specification states that an element in the stylesheet must or must not appear in a certain position, or that it must or must not have a particular attribute, or that an attribute must or must not have a value satisfying specified conditions, then any contravention of this rule is a static error unless otherwise specified.

A processor must provide a mode of operation that takes a (possibly erroneous) stylesheet package as input and enables the user to determine whether or not that package contains any static errors.

Note:

The manner in which static errors are reported, and the behavior when there are multiple static errors, are left as design choices for the implementer. It is recommended that the error codes defined in this specification should be made available in any diagnostics.

A processor may also provide a mode of operation in which static errors in parts of the stylesheet that are not evaluated can go unreported.

Note:

For example, when operating in this mode, a processor might report static errors in a template rule only if the input document contains nodes that match that template rule. Such a mode of operation can provide performance benefits when large and well-tested stylesheets are used to process source documents that might only use a small part of the XML vocabulary that the stylesheet is designed to handle.

[Definition: An error that is not capable of detection until a source document is being transformed is referred to as a dynamic error.]

When a dynamic error occurs, and is not caught using xsl:catch, the processormust raise the error, and the transformation fails.

Because different implementations may optimize execution of the stylesheet in different ways, the detection of dynamic errors is to some degree implementation-dependent. In cases where an implementation is able to produce a principal result or secondary result without evaluating a particular construct, the implementation is never required to evaluate that construct solely in order to determine whether doing so causes a dynamic error. For example, if a variable is declared but never referenced, an implementation may choose whether or not to evaluate the variable declaration, which means that if evaluating the variable declaration causes a dynamic error, some implementations will raise this error and others will not.

There are some cases where this specification requires that a construct must not be evaluated: for example, the content of an xsl:if instruction must not be evaluated if the test condition is false. This means that an implementation must not raise any dynamic errors that would arise if the construct were evaluated.

An implementation may raise a dynamic error before any source document is available, but only if it can determine that the error would be raised for every possible source document and every possible set of parameter values. For example, some circularity errors fall into this category: see 9.11 Circular Definitions.

There are also some dynamic errors where the specification gives a processor license to raise the error during the analysis phase even if the construct might never be executed; an example is the use of an invalid QName as a literal argument to a function such as key, or the use of an invalid regular expression in the regex attribute of the xsl:analyze-string instruction.

A dynamic error is also raised during the static analysis phase if the error occurs during evaluation of a static expression.

The XPath specification states (see [XPath 4.0] section Section 2.4.1 Kinds of ErrorsXP) that if any expression (at any level) can be evaluated during the analysis phase (because all its explicit operands are known and it has no dependencies on the dynamic context), then any error in performing this evaluation may be raised as a static error. For XPath expressions used in an XSLT stylesheet, however, any such errors must not be raised as static errors in the stylesheet unless they would occur in every possible evaluation of that stylesheet; instead, they must be raised as dynamic errors, and raised only if the XPath expression is actually evaluated.

Example: Errors in Constant Subexpressions

An XPath processor may report statically that the expression 1 div 0 fails with a “divide by zero” error. But suppose this XPath expression occurs in an XSLT construct such as:

<xsl:choose>
  <xsl:when test="system-property('xsl:version') = '1.0'">
    <xsl:value-of select="1 div 0"/>
  </xsl:when>
  <xsl:otherwise>
    <xsl:value-of select="xs:double('INF')"/>
  </xsl:otherwise>
</xsl:choose>

Then the XSLT processor must not report an error, because the relevant XPath construct appears in a context where it will never be executed by an XSLT 4.0. (An XSLT 1.0 processor will execute this code successfully, returning positive infinity, because it uses double arithmetic rather than decimal arithmetic.)

[Definition: 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.] If a type error occurs in an instruction that is actually evaluated, then it must be raised in the same way as a dynamic error. Alternatively, an implementation may raise a type error during the analysis phase in the same way as a static error, even if it occurs in part of the stylesheet that is never evaluated, provided it can establish that execution of a particular construct would never succeed.

It is implementation-defined whether type errors are raised statically.

Example: A Type Error

The following construct contains a type error, because 42 is not allowed as the value of the select expression of the xsl:number instruction (it must be a node). An implementation may optionally raise this as a static error, even though the offending instruction will never be evaluated, and the type error would therefore never be raised as a dynamic error.

<xsl:if test="false()">
  <xsl:number select="42"/>
</xsl:if>

On the other hand, in the following example it is not possible to determine statically whether the operand of xsl:number will have a suitable dynamic type. An implementation may produce a warning in such cases, but it must not treat it as an error.

<xsl:template match="para">
  <xsl:param name="p" as="item()"/>
  <xsl:number select="$p"/>
</xsl:template>

If more than one error arises, an implementation is not required to raise any errors other than the first one that it detects. It is implementation-dependent which of the several errors is raised. This applies both to static errors and to dynamic errors. An implementation is allowed to raise more than one error, but if any errors have been raised, it must not finish as if the transformation were successful.

When a transformation raises one or more dynamic errors, the final state of any persistent resources updated by the transformation is implementation-dependent. Implementations are not required to restore such resources to their initial state. In particular, where a transformation produces multiple result documents, it is possible that one or more serialized result documents may be written successfully before the transformation terminates, but the application cannot rely on this behavior.

Everything said above about error handling applies equally to errors in evaluating XSLT instructions, and errors in evaluating XPath expressions. Static errors and dynamic errors may occur in both cases.

[Definition: 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.] If the processor performs serialization, then it must do so as specified in 26 Serialization, and in particular it must raise any serialization errors that occur.

Errors are identified by a QName. For errors defined in this specification, the namespace of the QName is always http://www.w3.org/2005/xqt-errors (and is therefore not given explicitly), while the local part is an 8-character code in the form PPSSNNNN. Here PP is always XT (meaning XSLT), and SS is one of SE (static error), DE (dynamic error), or TE (type error). Note that the allocation of an error to one of these categories is purely for convenience and carries no normative implications about the way the error is handled. Many errors, for example, can be raised either dynamically or statically. These error codes are used to label error conditions in this specification, and are summarized in D Summary of Error Conditions.

Errors defined in related specifications ([XPath 4.0], [Functions and Operators 4.0][XSLT and XQuery Serialization][xslt-xquery-serialization-30]) use QNames with a similar structure, in the same namespace. When errors occur in processing XPath expressions, an XSLT processor should use the original error code reported by the XPath processor, unless a more specific XSLT error code is available.

Implementations must use the codes defined in these specifications when raising dynamic errors, to ensure that xsl:catch behaves in an interoperable way across implementations. Stylesheet authors should note, however, that there are many examples of errors where more than one rule in this specification is violated, and where the processor therefore has discretion in deciding which error code to associate with the condition: there is therefore no guarantee that different processors will always use the same error code for the same erroneous input.

Additional errors defined by an implementation (or by an application) may use QNames in an implementation-defined (or user-defined) namespace without risk of collision.

3 Stylesheet Structure

This section describes the overall structure of a stylesheet as a collection of XML documents.

3.1 Namespaces

A stylesheet module is typically written as a namespace well-formed XML document: more formally, as described in 3.6 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 3.04.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.7.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.

3.2 Extension Attributes

[Definition: An element from the XSLT namespace may have any attribute not from the XSLT namespace, provided that the expanded QName (see [XPath 4.0]) of the attribute has a non-null namespace URI. These attributes are referred to as extension attributes.] The presence of an extension attribute must not cause the principal result or any secondary result of the transformation to be different from the results that a conformant XSLT 4.0 processor might produce. They must not cause the processor to fail to raise an error that a conformant processor is required to raise. This means that an extension attribute must not change the effect of any instruction except to the extent that the effect is implementation-defined or implementation-dependent.

Furthermore, if serialization is performed using one of the serialization methods described in [XSLT and XQuery Serialization][xslt-xquery-serialization-30], the presence of an extension attribute must not cause the serializer to behave in a way that is inconsistent with the mandatory provisions of that specification.

Note:

Extension attributes may be used to modify the behavior of extension functions and extension instructions. They may be used to select processing options in cases where the specification leaves the behavior implementation-defined or implementation-dependent. They may also be used for optimization hints, for diagnostics, or for documentation.

Extension attributes may also be used to influence the behavior of the standard serialization methods xml, xhtml, html, text, json, and adaptive, to the extent that the behavior of the serialization method is implementation-defined or implementation-dependent. For example, an extension attribute might be used to define the amount of indentation to be used when indent="yes" is specified. If a serialization method other than one of these four is requested (using a namespaced QName in the method parameter) then extension attributes may influence its behavior in arbitrary ways. Extension attributes must not be used to cause the standard serialization methods to behave in a non-conformant way, for example by failing to report serialization errors that a serializer is required to report. An implementation that wishes to provide such options must create a new serialization method for the purpose.

An implementation that does not recognize the name of an extension attribute, or that does not recognize its value, must perform the transformation as if the extension attribute were not present. As always, it is permissible to produce warning messages.

The namespace used for an extension attribute will be copied to the result tree in the normal way if it is in scope for a literal result element. This can be prevented using the [xsl:]exclude-result-prefixes attribute.

Example: An Extension Attribute for xsl:message

The following code might be used to indicate to a particular implementation that the xsl:message instruction is to ask the user for confirmation before continuing with the transformation:

<xsl:message abc:pause="yes"
    xmlns:abc="http://vendor.example.com/xslt/extensions">
       Phase 1 complete
</xsl:message>

Implementations that do not recognize the namespace http://vendor.example.com/xslt/extensions will simply ignore the extra attribute, and evaluate the xsl:message instruction in the normal way.

[ERR XTSE0090] 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.

3.5 Packages

[Definition: 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.] (This specification does not preclude the xsl:package being embedded in another XML document, but it will never have any other XSLT element as an ancestor).

<xsl:package
  id? = id
  name? = uri
  package-version? = string〔'1'〕
  version = decimal
  input-type-annotations? = "preserve" | "strip" | "unspecified"〔'unspecified'〕
  declared-modes? = boolean〔'yes'〕
  default-mode? = eqname | "#unnamed"〔'#unnamed'〕
  default-validation? = "preserve" | "strip"〔'strip'〕
  default-collation? = uris
  extension-element-prefixes? = prefixes
  exclude-result-prefixes? = prefixes
  expand-text? = boolean〔'no'〕
  fixed-namespaces? = string
  schema-role? = ncname
  use-when? = expression〔true()〕
  xpath-default-namespace? = uri >
  <!-- Content: ((xsl:expose | declarations)*) -->
</xsl:package>

[Definition: The content of the xsl:package element is referred to as the package manifest].

The version attribute indicates the version of the XSLT language specification to which the package manifest conforms. The value should normally be 4.0. If the value is numerically less than 4.0, the content of the xsl:package element is processed using the rules for backwards compatible behavior (see 3.9 Backwards Compatible Processing). If the value is numerically greater than 4.0, it is processed using the rules for forwards compatible behavior (see 3.10 Forwards Compatible Processing).

A package typically has a name, given in its name attribute, which must be an absolute URI. Unnamed packages are allowed, but they can only be used as the “top level” of an application; they cannot be the target of an xsl:use-package declaration in another package.

A package may have a version identifier, given in its package-version attribute. This is used to distinguish different versions of a package. The value of the version attribute, after trimming leading and trailing whitespace, must conform to the syntax given in 3.5.1 Versions of a Package. If no version number is specified for a package, version 1 is assumed.

The attributes default-collation, default-mode, default-validation, exclude-result-prefixes, expand-text, extension-element-prefixes, use-when, version, and xpath-default-namespace are standard attributes that can appear on any XSLT element, and potentially affect all descendant elements. Their meaning is described in 3.4 Standard Attributes.

The package manifest contains the following elements, arbitrarily ordered:

  1. Zero or more xsl:expose declarations that define the interface offered by this package to the outside world. An xsl:expose declaration may appear only as a child of xsl:package.

  2. Zero or more additional declarations. These are the same as the declarations permitted as children of xsl:stylesheet or xsl:transform.

    Some declarations of particular relevance to packages include:

    1. The xsl:use-package declaration, which declares the names and versions of the packages on which this package depends.

    2. The optional xsl:global-context-item element; if present this element defines constraints on the existence and type of the global context item.

    3. Zero or more xsl:include and xsl:import declarations, which define additional stylesheet modules to be incorporated into this package.

    4. Zero or more ordinary declarations, that is, elements that are permitted as children of xsl:stylesheet or xsl:transform. One possible coding style is to include in the package manifest just a single xsl:import or xsl:include declaration as a reference to the effective top-level stylesheet module; this approach is particularly suitable when writing code that is required to run under releases of XSLT earlier than 3.0. Another approach is to include the substance of the top-level stylesheet module inline within the package manifest.

Example: An example package

The following example shows a package that offers a number of functions for manipulating complex numbers. A complex number is represented as a map with two entries, the keys being 0 for the real part, and 1 for the imaginary part.

<xsl:package
  name="http://example.org/complex-arithmetic.xsl"
  package-version="1.0"
  version="3.0"
  xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
  xmlns:xs="http://www.w3.org/2001/XMLSchema"
  xmlns:f="http://example.org/complex-arithmetic.xsl">
  
  <xsl:function name="f:complex-number" 
                as="map(xs:integer, xs:double)" visibility="public">
    <xsl:param name="real" as="xs:double"/>
    <xsl:param name="imaginary" as="xs:double"/>
    <xsl:sequence select="{ 0: $real, 1: $imaginary }"/>
  </xsl:function>
  
  <xsl:function name="f:real" 
                as="xs:double" visibility="public">
    <xsl:param name="complex" as="map(xs:integer, xs:double)"/>
    <xsl:sequence select="$complex(0)"/>
  </xsl:function>
  
  <xsl:function name="f:imag" 
                as="xs:double" visibility="public">
    <xsl:param name="complex" as="map(xs:integer, xs:double)"/>
    <xsl:sequence select="$complex(1)"/>
  </xsl:function>
  
  <xsl:function name="f:add" 
                as="map(xs:integer, xs:double)" visibility="public">
    <xsl:param name="x" as="map(xs:integer, xs:double)"/>
    <xsl:param name="y" as="map(xs:integer, xs:double)"/>
    <xsl:sequence select="
         f:complex-number(
           f:real($x) + f:real($y), 
           f:imag($x) + f:imag($y))"/>
  </xsl:function>
  
  <xsl:function name="f:multiply" 
                as="map(xs:integer, xs:double)" visibility="public">
    <xsl:param name="x" as="map(xs:integer, xs:double)"/>
    <xsl:param name="y" as="map(xs:integer, xs:double)"/>
    <xsl:sequence select="
         f:complex-number(
           f:real($x)*f:real($y) - f:imag($x)*f:imag($y),
           f:real($x)*f:imag($y) + f:imag($x)*f:real($y))"/>
  </xsl:function>
  
  <!-- etc. -->
  
</xsl:package>

A more complex package might include private or abstract functions as well as public functions; it might expose components other than functions (for example, templates or global variables), and it might contain xsl:use-package elements to allow it to call on the services of other packages.

Note:

In this example, the way in which complex numbers are represented is exposed to users of the package. It would be possible to hide the representation by declaring the types on public functions simply as item(); but this would be at the cost of type safety.

A package that does not itself expose any components may be written using a simplified syntax: the xsl:package element is omitted, and the xsl:stylesheet or xsl:transform element is now the outermost element of the stylesheet module. For compatibility reasons, all the named templates and modes declared in the package are made public. More formally, the principal stylesheet module of the top-level package may be expressed as an xsl:stylesheet or xsl:transform element, which is equivalent to the package represented by the output of the following transformation, preserving the base URI of the source:

<xsl:transform version="3.0" 
    xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    xmlns:t="http://www.w3.org/1999/XSL/TransformAlias">
 
    <xsl:namespace-alias stylesheet-prefix="t" result-prefix="xsl"/>
    
    <xsl:template match="xsl:stylesheet|xsl:transform">
      <t:package declared-modes="no">
        <xsl:copy-of select="@*"/>
        <t:expose component="mode" names="*" visibility="public"/>
        <t:expose component="template" names="*" visibility="public"/>
        <xsl:copy-of select="node()"/>
      </t:package>
    </xsl:template>
 </xsl:transform>

The effect of the input-type-annotations attribute is defined in 4.3.1 Stripping Type Annotations from a Source Tree.

A more extensive example of a package, illustrating how components in a package can be overridden in a client package, is given in 3.5.8 Worked Example of a Library Package.

3.5.4 Named Components in Packages

This section discusses the use of named components in packages.

The components which can be declared in one package and referenced in another are: functions, named templates, attribute sets, modes, and global variables and parameters.

In addition, keys and accumulators are classified as named components because they can contain references to components in another package, even though they cannot themselves be referenced from outside the package.

Named and unnamed modes come within the scope of this section, but there are differences noted in 3.5.5 Overriding Template Rules from a Used Package.

Not all declarations result in components:

  • Named declarations that can neither be referenced from outside their containing package, nor can contain references to components in other packages (examples are xsl:output, xsl:character-map, and xsl:decimal-format) are not considered to be components and are therefore outside the scope of this section.

  • Some declarations, such as xsl:decimal-format and xsl:strip-space, declare aspects of the processing context which are not considered to be components as defined here.

  • Template rules (xsl:template with a match attribute) are also not considered to be components for the purposes of this section, which is concerned only with components that are bound by name. However, when an xsl:template has both a match attribute and a name attribute, then it establishes both a template rule and a named template, and in its role as a named template it comes within the scope of this discussion.

  • A named declaration, for example a named template, a function, or a global variable, may be overridden within the same package by another like-named declaration having higher import precedence. When a declaration is overridden in this way it cannot be referenced by name either from within its containing package or from outside that package.

  • In the case of xsl:attribute-set and xsl:key declarations, several declarations combine to form a single component.

The section is largely concerned with details of the rules that affect references from one component to another by name, whether the components are in the same package or in different packages. The rules are designed to meet a number of requirements:

  • A component defined in one package can be overridden by a component in another package, provided the signatures are type-compatible.

  • The author of a package can declare whether the components in the package are public or private (that is, whether or not they can be used from outside the package) and whether they are final, overridable, or abstract (that is whether they can or must be overridden by the using package).

  • Within an application, two packages can make use of a common library and override its components in different ways.

  • Visibility of components can be defined either as part of the declaration of the component, or in the package manifest.

  • An application that wishes to make use of a library package can be selective about which components from the library it acquires, perhaps to avoid name clashes between components acquired from different libraries.

[Definition: 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.]

[Definition: 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.]

Note:

In the case of the unnamed mode, the expanded QName of the component may be considered to be some system-allocated name different from any user-defined mode name.

[Definition: Two components are said to be homonymous if they have the same symbolic identifier.]

Every component has a declaration in some stylesheet module and therefore within some package. In the case of attribute sets and keys, there may be several declarations. The declaration is an element in an XDM tree representing the stylesheet module. Declarations therefore have identity, based on XDM node identity.

[Definition: 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.]

When a component declared in one package is made available in another, the using package will contain a separate component that can be regarded as a modified copy of the original. The new component shares the same symbolic identifier as the original, and it has the same declaration, but it has other properties such as its visibility that may differ from the original.

[Definition: 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.]

Note:

Within this specification, we generally use the notation CP for a component named C whose declaring package and containing package are both P; and the notation CPQ for a component whose containing package is P and whose declaring package is Q (that is, a component in P that is derived from a component CQ in the used package Q).

The properties of a component are as follows:

Note:

When a function F defined in a package P is acquired by two using packages Q and R, we may think of P, Q, and R as all providing access to the “same” function. The detailed semantics, however, demand an understanding that there is one function declaration, but three components. The three components representing the function F within packages P, Q, and R have some properties in common (the same symbolic identifier, the same declaration), but other properties (the visibility and the bindings of symbolic references) that may vary from one of these components to another.

[Definition: 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. ]

Symbolic references exist as properties of the declaration of a component. The symbolic identifier being referred to can be determined straightforwardly from the syntactic form and context of the reference: for example, the instruction <xsl:value-of select="f:price($o)" xmlns:f="http://f.com/"/> contains a symbolic reference to a function with expanded name {http://f.com/}price and with arity=1. However, because there may be several (homonymous) function components with this symbolic identifier, translating this symbolic reference into a reference to a specific component (a process called “binding”) is less straightforward, and is described in the text that follows.

The process of assembling a stylesheet from its constituent packages is primarily a process of binding these symbolic references to actual components. Within any component whose declaration is D, there is a set of bindings; each binding is an association between a symbolic reference in D and a component whose symbolic identifier matches the outward reference. Outward references for which a component C contains a binding are said to be bound in C; those for which C contains no binding are said to be unbound.

For example, suppose that in some package Q, function A calls B, which in turn calls C, and that B is private. Now suppose that in some package P which uses Q, C is overridden. The effect of the binding process is that P will contain three components corresponding to A, B, and C, which we might call AP, BP, and CP. The declarations of AP and BP are in package Q, but the declaration of CP is in P. The internal visibility of BP will be hidden (meaning that it cannot be referenced from within P), and BP will contain a binding for the component CP that corresponds to the outward reference from B to C. The effect is that when A calls B and B calls C, it is the overriding version of C that is executed.

In another package R that uses Q without overriding C, there will be three different components AR, BR, and CR. This time the declaration of all three components is in the original package Q. Component BR will contain a binding to CR, so in this package, the original version of C is executed. The fact that one package P overrides C thus has no effect on R, which does not override it.

The binding process outlined above is described in more detail in 3.5.4.5 Binding References to Components.

Template rules are not components in their own right; unlike named templates, they are never referenced by name. Component references within a template rule (for example, references to functions, global variables, or named templates) are treated as occurring within the component that represents the containing mode. This includes component references within the match patterns of template rules. If a template rule lists several modes, it is treated as if there were multiple template rules one in each mode.

An xsl:apply-templates instruction with no mode attribute is treated as a reference to the default mode defined for that instruction (see 3.7.3 The default-mode Attribute), which in turn defaults to the unnamed mode. An implicit reference to the unnamed made is treated in the same way as any other symbolic reference. Note that there is an unnamed mode in every package, and the unnamed mode always has private visibility.

Where an xsl:template element has both a name and a match attribute, it is treated as if there were two separate xsl:template elements, one with a name attribute and one with a match attribute.

Keys and accumulators behave rather differently from other components. Their visibility is always private, which means they can only be used within their declaring package. In addition, the component binding is generally made dynamically rather than statically, by virtue of a string passed as an argument to the function key, accumulator-before, or accumulator-after. (In the case of accumulators, there can also be static references: see the use-accumulators attribute of xsl:source-document, xsl:merge-source, and xsl:mode.) However, outward references from key definitions and accumulators to other components (such as global variables and functions) behave in the same way as component references contained in any other private component, in that they may be re-bound to an overriding declaration of the target component.

3.5.4.3 Overriding Components from a Used Package

[Definition: 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.]

<xsl:override>
  <!-- Content: (xsl:template | xsl:function | xsl:variable | xsl:param | xsl:attribute-set)* -->
</xsl:override>

Note:

This mechanism is distinct from the mechanism for overriding declarations within the same package by relying on import precedence. It imposes stricter rules: the overriding component is required to be type-compatible with the component that it overrides.

If the used package Q contains a componentCQ and the xsl:use-package element contains an xsl:override element which contains a declaration D whose symbolic identifier matches the symbolic identifier of CQ, then the using package P will contain a component CP whose declaration is D, whose symbolic identifier is that of D, and whose visibility is equal to the value of the visibility attribute of D, or private if this is absent, except in the case of xsl:param, which is implicitly public.

The using package P will also contain a component CPQ whose body is the same as the body of CQ and whose visibility is hidden. This component is used as the target of a binding for the symbolic reference xsl:original described below.

Other than its appearance as a child of xsl:override, the overriding declaration is a normal xsl:function, xsl:template, xsl:variable, xsl:param, or xsl:attribute-set element. In the case of xsl:variable and xsl:param, the variable that is declared is a global variable.

The rules in the remainder of this section apply to components having a name attribute (named components). The only element with no name attribute that can appear as a child of xsl:override is an xsl:template declaration having a match attribute (that is, a template rule). The rules for overriding of template rules appear in 3.5.5 Overriding Template Rules from a Used Package. If an xsl:template element has both a name attribute and a match attribute, then it defines both a named component and a template rule, and both sections apply.

[ERR XTSE3055] 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.

Note:

When an attribute set is overridden, the overriding attribute set must be defined using a single xsl:attribute-set element. Attribute sets defined in different packages are never merged by virtue of having the same name, though they may be merged explicitly by using the use-attribute-sets attribute.

[ERR XTSE3058] 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.

[ERR XTSE3060] It is a static error if the component referenced by an xsl:override declaration has visibility other than public or abstract

A package is executable if and only if it contains no component whose visibility is abstract. A package that is not executable is not a stylesheet, and therefore cannot be nominated as the stylesheet to be used when initiating a transformation.

Note:

In other words, if a component is declared as abstract, then some package that uses the declaring package of that component directly or indirectly must override that component with one that is not abstract. It is not necessary for the override to happen in the immediately using package.

[ERR XTSE3070] 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.

[Definition: 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.]

Compatibility is only relevant when comparing two components that have the same symbolic identifier. The compatibility rules for each kind of component are as follows:

  • Two attribute sets with the same name are compatible if and only if they satisfy the following rule:

    1. If the overridden attribute set specifies streamable="yes" then the overriding attribute set also specifies streamable="yes".

  • Two functions with the same symbolic identifier are compatible if and only if they satisfy all the following rules:

    1. They have the same arity range (which implies they have the same number of required and optional parameters)

    2. The declared types of the parameters (defaulting to item()*) are pairwise identical.

    3. The declared return types (defaulting to item()*) are identical.

    4. The effective value of the new-each-time attribute on the overriding function is the same as its value on the overridden function.

    5. If the overridden function has a streamability attribute with a value other than unspecified, then the overriding function has a streamability attribute with the same value. [XSLT 3.0 Erratum E32, bug 30297]

    It is recommended that the parameter names on the overriding function should be the same as on the overridden function. (However, in order to maintain backwards compatibility with XSLT 3.0, this is not required.) If the parameter names are not the same, then the parameter names on the overriding function are effectively replaced with the names declared on the overridden function, so that any static function calls using keyword arguments to set the values of arguments must use the names defined on the overridden function.

  • Two named templates with the same name are compatible if and only if they satisfy all the following rules:

    1. Their return types are identical.

    2. For every non-tunnel parameter on the overridden template, there is a non-tunnel parameter on the overriding template that has the same name, an identical required type, and the same effective value for the required attributes.

    3. For every tunnel parameter P on the overridden template, if there is a parameter Q on the overriding template that has the same name as P then Q is also a tunnel parameter, and P and Q have identical required types.

    4. Any parameter on the overriding template for which there is no corresponding parameter on the overridden template specifies required="no".

    5. The two templates have equivalent xsl:context-item children, where equivalence means that the use attributes are the same and the required types are identical; an absent xsl:context-item is equivalent to one that specifies use="optional" and as="item()".

  • Two variables (including parameters) with the same name are compatible if and only if they satisfy all the following rules:

    1. Their declared types are identical. For this purpose, the declared type is the first of the following that applies:

      • If there is an as attribute, then the type defined by that attribute.

      • If there is a select attribute, then item()*.

      • If there is a non-empty sequence constructor, then document-node().

      • Otherwise, xs:string. [XSLT 3.0 Erratum E35, bug 30313].

    Note:

    A variable may override a parameter or vice-versa, and the initial value may differ.

    Because static variables and parameters are constrained to have visibility private , they cannot be overridden in another package. The compatibility rules therefore do not arise. The reason that such variables cannot be overridden is that they are typically used during stylesheet compilation (for example, in [xsl:]use-when expressions and shadow attributes) and it is a design goal that packages should be capable of independent compilation.

[Definition: 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 Section 3.3.1 Subtypes of Sequence TypesXP.]

Note:

  1. One consequence of this rule is that two plain union types are considered identical if they have the same set of member types, even if the union types have different names or the ordering of the member types is different.

    Consider a function that accepts an argument whose declared type is a union type with member types xs:double and xs:decimal, in that order (we might write this as (xs:double | xs:decimal)). Using the same notation, this can be overridden by a function that declares the argument type as (xs:decimal | xs:double). This does not affect type checking: a function call that passes the type checking rules with one signature will also pass the type checking rules with the other. It does however affect the way that the function conversion rules work: a call that passes the xs:untypedAtomic item "93.7" (or an untyped node with this as its string value) will be converted to an xs:decimal in one case and an xs:double in the other.

  2. While this rule may appear formal, it is not as straightforward as might be supposed, because the subtype relation in XPath has a dependency on the “Type derivation OK (Simple)” relation in XML Schema, which itself appeals to a judgement as to whether the two type definitions being compared “are the same type definition”. Both XSD 1.0 and XSD 1.1 add the note “The wording of [this rule] appeals to a notion of component identity which is only incompletely defined by this version of this specification.” However, they go on to say that component identity is well defined if the components are named simple type definitions, which will always apply in this case. For named atomic types, the final result of these rules is that two atomic types are identical if and only if they have the same name.

  3. A named item type (declared in an xsl:item-type declaration) is considered identical to its expansion.

  4. Two named record types are compared by name, not by content. This is because named record types may potentially be recursive, so the name cannot always be expanded to an expressible record type designator. By implication, the named record type must itself be declared or exposed with visibility="public".

Modes, named item types, and named record type are not overridable, so xsl:mode, xsl:item-type, and xsl:record-type declarations cannot appear as children of xsl:override. However, the constructor function implicitly created from an xsl:record-type declaration may be overridden in an xsl:function declaration.

3.6 Stylesheet Modules

[Definition: A package consists of one or more stylesheet modules, each one forming all or part of an XML document.]

Note:

A stylesheet module is represented by an XDM element node (see [XDM 3.04.0]). In the case of a standard stylesheet module, this will be an xsl:stylesheet or xsl:transform element. In the case of a simplified stylesheet module, it can be any element (not in the XSLT namespace) that has an xsl:version attribute.

Although stylesheet modules will commonly be maintained in the form of documents conforming to XML 1.0 or XML 1.1, this specification does not mandate such a representation. As with source trees, the way in which stylesheet modules are constructed, from textual XML or otherwise, is outside the scope of this specification.

The principal stylesheet module of a package may take one of three forms:

A stylesheet module other than the principal stylesheet module of a package may take either of two forms:

Whichever of the above forms a module takes, the outermost element (xsl:package, xsl:stylesheet, or a literal result element) may either be the outermost element of an XML document, or it may be a child of some (non-XSLT) element in a host document.

[Definition: 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.12 Embedded Stylesheet Modules.]

3.7 Stylesheet Element

Changes in 4.0  

  1. A new attribute, main-module, is added to the xsl:stylesheet element. The attribute is provided for the benefit of development tools such as syntax-directed editors to provide information about all the components (variables, functions, etc) visible within a stylesheet module.   [Issue 87 PR 353 19 April 2023]

<xsl:stylesheet
  id? = id
  version = decimal
  default-mode? = eqname | "#unnamed"〔'#unnamed'〕
  default-validation? = "preserve" | "strip"〔'strip'〕
  input-type-annotations? = "preserve" | "strip" | "unspecified"〔'unspecified'〕
  default-collation? = uris
  extension-element-prefixes? = prefixes
  exclude-result-prefixes? = prefixes
  expand-text? = boolean
  fixed-namespaces? = string
  main-module? = uri
  schema-role? = ncname
  use-when? = expression〔true()〕
  xpath-default-namespace? = uri >
  <!-- Content: (declarations) -->
</xsl:stylesheet>

<xsl:transform
  id? = id
  version = decimal
  default-mode? = eqname | "#unnamed"〔'#unnamed'〕
  default-validation? = "preserve" | "strip"〔'strip'〕
  input-type-annotations? = "preserve" | "strip" | "unspecified"〔'unspecified'〕
  default-collation? = uris
  extension-element-prefixes? = prefixes
  exclude-result-prefixes? = prefixes
  expand-text? = boolean〔'no'〕
  fixed-namespaces? = string
  main-module? = uri
  schema-role? = ncname
  use-when? = expression〔true()〕
  xpath-default-namespace? = uri >
  <!-- Content: (declarations) -->
</xsl:transform>

A stylesheet module is represented by an xsl:stylesheet element in an XML document. xsl:transform is allowed as a synonym for xsl:stylesheet; everything this specification says about the xsl:stylesheet element applies equally to xsl:transform.

The version attribute indicates the version of XSLT that the stylesheet module requires. The attribute is required.

[ERR XTSE0110] 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].

The version attribute is intended to indicate the version of the XSLT specification against which the stylesheet is written. In a stylesheet written to use XSLT 4.0, the value should normally be set to 4.0. If the value is numerically less than 4.0, the stylesheet is processed using the rules for backwards compatible behavior (see 3.9 Backwards Compatible Processing). If the value is numerically greater than 4.0, the stylesheet is processed using the rules for forwards compatible behavior (see 3.10 Forwards Compatible Processing).

The effect of the input-type-annotations attribute is described in 4.3.1 Stripping Type Annotations from a Source Tree.

The [xsl:]default-validation attribute defines the default value of the validation attribute of all relevant instructions appearing within its scope. For details of the effect of this attribute, see 25.4 Validation.

The optional main-module attribute is purely documentary. By including this attribute in every stylesheet module of a package, an XSLT editing tool may be enabled to locate the top-level module of the relevant package, and thus to gather information about all the global variables, templates, and functions available within the module being edited. This information can be used (for example) to enable auto-completion and error highlighting of the code as it is entered. Note that it may be inconvenient or misleading to use this attribute when the stylesheet module is used as a shared component within multiple stylesheets.

[ERR XTSE0120] An xsl:stylesheet, xsl:transform, or xsl:package element must not have any text node children. (This rule applies after stripping of whitespace text nodes as described in 3.13.1 Stripping Whitespace and Commentary from the Stylesheet.)

[Definition: An element occurring as a child of an xsl:package, xsl:stylesheet, xsl:transform, or xsl:override element is called a top-level element.]

[Definition: 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.7.4 User-defined Data Elements)].

The declaration elements permitted in the xsl:stylesheet element are:

xsl:accumulator
xsl:attribute-set
xsl:character-map
xsl:decimal-format
xsl:function
xsl:global-context-item
xsl:import
xsl:import-schema
xsl:include
xsl:item-type
xsl:key
xsl:mode
xsl:namespace-alias
xsl:output
xsl:param
xsl:preserve-space
xsl:record-type
xsl:strip-space
xsl:template
xsl:use-package
xsl:variable

Note that the xsl:variable and xsl:param elements can act either as declarations or as instructions. A global variable or parameter is defined using a declaration; a local variable or parameter using an instruction.

The child elements of the xsl:stylesheet element may appear in any order. In most cases, the ordering of these elements does not affect the results of the transformation; however:

3.7.2 The default-collation Attribute

The default-collation attribute is a standard attribute that may appear on any element in the XSLT namespace, or (as xsl:default-collation) on a literal result element.

The attribute, when it appears on an element E, is used to specify the default collation used by all XPath expressions appearing in attributes or text value templates that have E as an ancestor, unless overridden by another default-collation attribute on an inner element. It also determines the collation used by certain XSLT constructs (such as xsl:key and xsl:for-each-group) within its scope.

The value of the attribute is a whitespace-separated list of collation URIs. If any of these URIs is a relative URI reference, then it is resolved as described in [Functions and Operators 4.0] section Section 5.3.1 CollationsFO.. If the implementation recognizes one or more of the resulting absolute collation URIs, then it uses the first one that it recognizes as the default collation.

[ERR XTSE0125] 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.

Note:

The reason the attribute allows a list of collation URIs is that collation URIs will often be meaningful only to one particular XSLT implementation. Stylesheets designed to run with several different implementations can therefore specify several different collation URIs, one for use with each. To avoid the above error condition, it is possible to include as the last collation URI in the list either the Unicode Codepoint Collation or a collation in the UCA family (see 13.4 The Unicode Collation Algorithm) with the parameter fallback=yes.

The [xsl:]default-collation attribute does not affect the collation used by xsl:sort or by xsl:merge.

In the absence of an [xsl:]default-collation attribute, the default collation may be set by the calling application in an implementation-defined way. The recommended default, unless the user chooses otherwise, is to use the Unicode codepoint collation.

3.9 Backwards Compatible Processing

[Definition: The effective version of an element in a stylesheet module or package manifest is the decimal value of the [xsl:]version attribute (see 3.4 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.]

These rules do not apply to the xsl:output element, whose version attribute has an entirely different purpose: it is used to define the version of the output method to be used for serialization. The effective version of an xsl:output element is the effective version of its parent element.

There are additional rules for an xsl:fallback element: see 3.10 Forwards Compatible Processing.

[Definition: An element is processed with backwards compatible behavior if its effective version is less than 4.0.]

Specifically:

  • If the effective version is equal to 1.0, then the element is processed with XSLT 1.0 behavior as described in 3.9.1 XSLT 1.0 Compatibility Mode.

  • If the effective version is equal to 2.0, then the element is processed with XSLT 2.0 behavior as described in 3.9.2 XSLT 2.0 Compatibility Mode.

  • If the effective version is equal to 3.0, then the element is processed with XSLT 3.0 behavior as described in 3.9.3 XSLT 3.0 Compatibility Mode.

  • If the effective version is any other value less than 4.0, the recommended action is to raise a static error; however, processors may recognize such values and process the element in an implementation-defined way.

    Note:

    XSLT 1.0 allowed the version attribute to take any decimal value, and invoked forwards compatible processing for any value other than 1.0. XSLT 2.0 allowed the attribute to take any decimal value, and invoked backwards compatible (i.e. 1.0-compatible) processing for any value less than 2.0. Some stylesheets may therefore be encountered that use values other than 1.0 or 2.0. In particular, the value 1.1 is sometimes encountered, as it was used at one stage in a draft language proposal.

It is implementation-defined whether a particular XSLT 4.0 implementation supports backwards compatible behavior for any XSLT version earlier than XSLT 4.0.

[ERR XTDE0160] 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.

Note:

By making use of backwards compatible behavior, it is possible to write the stylesheet in a way that ensures that its results when processed with an XSLT 4.0 processor are identical to the effects of processing the same stylesheet using a processor for an earlier version of XSLT. To assist with transition, some parts of a stylesheet may be processed with backwards compatible behavior enabled, and other parts with this behavior disabled.

All data values manipulated by an XSLT 4.0 processor are defined by the XDM data model, whether or not the relevant expressions use backwards compatible behavior. Because the same data model is used in both cases, expressions are fully composable. The result of evaluating instructions or expressions with backwards compatible behavior is fully defined in the XSLT 4.0 and XPath 4.0 specifications, it is not defined by reference to earlier versions of the XSLT and XPath specifications.

To write a stylesheet that makes use of features that are new in version N, while also working with a processor that only supports XSLT version M (M < N), it is necessary to understand both the rules for backwards compatible behavior in XSLT version N, and the rules for forwards compatible behavior in XSLT version M. If the xsl:stylesheet element specifies a version attribute with a value greater than 1.0, then an XSLT 1.0 processor will ignore declarations that were not defined in XSLT 1.0, for example xsl:function, xsl:import-schema, and xsl:mode. If any new XSLT 4.0 instructions are used (for example xsl:switch or xsl:array), or if new XPath 4.0 features are used (for example, keyword arguments in function calls), then the stylesheet must provide fallback behavior that relies only on facilities available in the earliest XSLT version supported. The fallback behavior can be invoked by using the xsl:fallback instruction, or by testing the results of the function-available or element-available functions, or by testing the value of the xsl:version property returned by the system-property function.

3.9.1 XSLT 1.0 Compatibility Mode

[Definition: An element in the stylesheet is processed with XSLT 1.0 behavior if its effective version is equal to 1.0.]

In this mode, if any attribute contains an XPath expression, then the expression is evaluated with XPath 1.0 compatibility mode set to true. For details of this mode, see [XPath 4.0] section Section 2.2.1 Static ContextXP. Expressions contained in text value templates are always evaluated with XPath 1.0 compatibility mode set to false, since this construct was not available in XSLT 1.0.

Furthermore, in such an expression any function call for which no implementation is available (unless it uses the standard function namespace) is bound to a fallback error function whose effect when evaluated is to raise a dynamic error [see ERR XTDE1425] . The effect is that with backwards compatible behavior enabled, calls on extension functions that are not available in a particular implementation do not cause an error unless the function call is actually evaluated. For further details, see 24.1 Extension Functions.

Note:

This might appear to contradict the specification of XPath 3.0, which states that a static error [XPST0017] is raised when an expression contains a call to a function that is not present (with matching name and arity) in the static context. This apparent contradiction is resolved by specifying that the XSLT processor constructs a static context for the expression in which every possible function name and arity (other than names in the standard function namespace) is present; when no other implementation of the function is available, the function call is bound to a fallback error function whose run-time effect is to raise a dynamic error.

Certain XSLT constructs also produce different results when XSLT 1.0 compatibility mode is enabled. This is described separately for each such construct.

Processing an instruction with XSLT 1.0 behavior is not compatible with streaming. More specifically, and notwithstanding anything stated in 19 Streamability, an instruction that is processed with XSLT 1.0 behavior is roaming and free-ranging, which has the effect that any construct containing such an instruction is not guaranteed-streamable.

3.12 Embedded Stylesheet Modules

An embedded stylesheet module is a stylesheet module whose containing element is not the outermost element of the containing XML document. Both standard stylesheet modules and simplified stylesheet modules may be embedded in this way.

Two situations where embedded stylesheets may be useful are:

  • The stylesheet may be embedded in the source document to be transformed.

  • The stylesheet may be embedded in an XML document that describes a sequence of processing of which the XSLT transformation forms just one part.

The xsl:stylesheet element may have an id attribute to facilitate reference to the stylesheet module within the containing document.

Note:

In order for such an attribute value to be used as a fragment identifier in a URI, the XDM attribute node must generally have the is-id property: see [XDM 4.0] section Section 5.57.5.5 is-id Accessor DM30. This property will typically be set if the attribute is defined in a DTD as being of type ID, or if it is defined in a schema as being of type xs:ID. It is also necessary that the media type of the containing document should support the use of ID values as fragment identifiers. Such support is widespread in existing products, and is endorsed in respect of the media type application/xml by [RFC7303].

An alternative, if the implementation supports it, is to use an xml:id attribute. XSLT allows this attribute (like other namespaced attributes) to appear on any XSLT element.

Example: The xml-stylesheet Processing Instruction

The following example shows how the xml-stylesheet processing instruction (see [XML Stylesheet]) can be used to allow a source document to contain its own stylesheet. The URI reference uses a fragment identifier to locate the xsl:stylesheet element:

<?xml-stylesheet type="application/xslt+xml" href="#style1"?>
<!DOCTYPE doc SYSTEM "doc.dtd">
<doc>
  <head>
    <xsl:stylesheet id="style1"
                    version="3.0"
                    xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
                    xmlns:fo="http://www.w3.org/1999/XSL/Format">
    <xsl:import href="doc.xsl"/>
    <xsl:template match="id('foo')">
      <fo:block font-weight="bold"><xsl:apply-templates/></fo:block>
    </xsl:template>
    <xsl:template match="xsl:stylesheet">
      <!-- ignore -->
    </xsl:template>
    </xsl:stylesheet>
  </head>
  <body>
    <para id="foo">
    ...
    </para>
  </body>
</doc>

Note:

A stylesheet module that is embedded in the document to which it is to be applied typically needs to contain a template rule that specifies that xsl:stylesheet elements are to be ignored.

Note:

The above example uses the pseudo-attribute type="application/xslt+xml" in the xml-stylesheet processing instruction to denote an XSLT stylesheet. This is the officially registered media type for XSLT: see 3.3 XSLT Media Type. However, browsers developed before this media type was registered are more likely to accept the unofficial designation type="text/xsl".

Note:

Support for the xml-stylesheet processing instruction is not required for conformance with this Recommendation. Implementations are not constrained in the mechanisms they use to identify a stylesheet when a transformation is initiated: see 2.3 Initiating a Transformation.

4 Data Model

The data model used by XSLT is the XPath 3.04.0 and XQuery 3.04.0 data model (XDM), as defined in [XDM 3.04.0]. XSLT operates on source, result and stylesheet documents using the same data model.

This section elaborates on some particular features of XDM as it is used by XSLT:

The rules in 3.13.1 Stripping Whitespace and Commentary from the Stylesheet and 4.3.2 Stripping Whitespace from a Source Tree make use of the concept of a whitespace text node.

[Definition: 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) ).]

Note:

Features of a source XML document that are not represented in the XDM tree will have no effect on the operation of an XSLT stylesheet. Examples of such features are entity references, CDATA sections, character references, whitespace within element tags, and the choice of single or double quotes around attribute values.

4.1 XML Versions

The XDM data model defined in [XDM 3.04.0] is capable of representing either an XML 1.0 document (conforming to [XML 1.0] and [Namespaces in XML]) or an XML 1.1 document (conforming to [XML 1.1] and [Namespaces in XML 1.1]), and it makes no distinction between the two. In principle, therefore, XSLT 4.0 can be used with either of these XML versions.

Construction of the XDM tree is outside the scope of this specification, so XSLT 4.0 places no formal requirements on an XSLT processor to accept input from either XML 1.0 documents or XML 1.1 documents or both. This specification does define a serialization capability (see 26 Serialization), though from a conformance point of view it is an optional feature. Although facilities are described for serializing the XDM tree as either XML 1.0 or XML 1.1 (and controlling the choice), there is again no formal requirement on an XSLT processor to support either or both of these XML versions as serialization targets.

Because the XDM tree is the same whether the original document was XML 1.0 or XML 1.1, the semantics of XSLT processing do not depend on the version of XML used by the original document. There is no reason in principle why all the input and output documents used in a single transformation must conform to the same version of XML.

Some of the syntactic constructs in XSLT 4.0 and XPath 3.0, for example the productions CharXML and NCNameNames, are defined by reference to the XML and XML Namespaces specifications. There are slight variations between the XML 1.0 and XML 1.1 versions of these productions (and, indeed, between different editions of XML 1.0). Implementations may support any version; it is recommended that an XSLT 4.0 processor that implements the 1.1 versions should also provide a mode that supports the 1.0 versions. It is thus implementation-defined which versions and editions of XML and XML Namespaces are supported by the implementation.

Note:

The specification referenced as [Namespaces in XML] was actually published without a version number.

The current version of [XML Schema 1.1 Part 2] references the XML 1.1 specifications, but the previous version ([XML Schema Part 2]) (that is, XSD 1.0) remains in widespread use, and only references XML 1.0. With processors lacking support for XSD 1.1, therefore, datatypes such as xs:NCName and xs:ID may be constrained by the XML 1.0 rules, and not allow the full range of values permitted by XML 1.1. It is recommended that implementers wishing to support XML 1.1 should consult [XML Schema 1.0 and XML 1.1] for guidance.

4.2 XDM versions

XSLT 4.0 requires a processor to support XDM 3.14.0 as defined in [XDM 3.14.0].

A processor may also provide a user option to support versions of XDM later than 3.1, in which case the way it does so is implementation-defined.

4.3 Preprocessing Source Documents

Source documents supplied as input to a transformation may be subject to preprocessing. Two kinds of preprocessing are defined: stripping of type annotations (see 4.3.1 Stripping Type Annotations from a Source Tree), and stripping of whitespace text nodes (see 4.3.2 Stripping Whitespace from a Source Tree).

Stripping of type annotations happens before stripping of whitespace text nodes.

The source documents to which this applies are as follows:

Note:

This list excludes documents passed as the values of stylesheet parameters or parameters of the initial named template or initial function, trees created by functions such as parse-xml, parse-xml-fragment, analyze-string, or json-to-xml, and values returned from extension functions.

If a node other than a document node is supplied (for example as the global context item), then the preprocessing is applied to the entire document containing that node. If several nodes within the same document are supplied (for example as nodes in the initial match selection, or as nodes returned by the collection function), then the preprocessing is only applied to that document once. If a whitespace text node is supplied (for example as the global context item) and the rules cause this node to be stripped from its containing tree, then the behavior is as if this node had not been supplied (which may cause an error, for example if a global context item is required.)

The rules determining whether or not stripping of annotations and/or whitespace happens are defined at the level of a package. Declarations within a library package only affect the handling of documents loaded using a call on the document, doc, or collection functions or an evaluation of an xsl:source-document instruction appearing lexically within the same package. Declarations within the top-level package also affect the processing of the global context item and the initial match selection.

The semantics of the document, doc, and collection functions are formally defined in terms of mappings from URIs to document nodes maintained within the dynamic context (see 5.3.3 Initializing the Dynamic Context). The effect of the declarations that control stripping of type annotations and whitespace is therefore to modify this mapping (so it now maps the URI to a stripped document). The modification applies to the dynamic context for calls to these function appearing within a particular package; each package therefore has a different set of mappings. This means that when two calls to the doc function appear in different packages, specifying the same absolute URI, then in general different documents are returned. An implementation may return the same document for two such calls if it is able to determine that the effect of the annotation and whitespace stripping rules in both packages is the same.

The effect of dynamic calls to the document, doc, and collection functions is defined in the same way as for other functions with dependencies on the dynamic context. As described in 5.3.4 Additional Dynamic Context Components used by XSLT, named function references (such as doc#1) and calls on function-lookup (for example, function-lookup("doc", 1)) 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.

4.3.1 Stripping Type Annotations from a Source Tree

[Definition: 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 Section 5.147.5.13 type-name Accessor DM30.]

There is sometimes a requirement to write stylesheets that produce the same results whether or not the source documents have been validated against a schema. To achieve this, an option is provided to remove any type annotations on element and attribute nodes in a source tree, replacing them with an annotation of xs:untyped in the case of element nodes, and xs:untypedAtomic in the case of attribute nodes.

Such stripping of type annotations can be requested by specifying input-type-annotations="strip" on the xsl:package element. This attribute has three permitted values: strip, preserve, and unspecified. The default value is unspecified. Specifying unspecified has the same effect as omitting the attribute [XSLT 3.0 Erratum E43, bug 30383].

The input-type-annotations attribute may also be specified on the xsl:stylesheet element; if it is specified at this level then it must be consistent for all stylesheet modules within the same package.

[ERR XTSE0265] 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.

Type annotations are stripped from relevant source documents if at least one stylesheet module in the stylesheet specifies input-type-annotations="strip" on the xsl:package, xsl:stylesheet, or xsl:transform element [XSLT 3.0 Erratum E43, bug 30383].

When type annotations are stripped, the following changes are made to the source tree:

  • The type annotation of every element node is changed to xs:untyped

  • The type annotation of every attribute node is changed to xs:untypedAtomic

  • The typed value of every element and attribute node is set to be the same as its string value, as an instance of xs:untypedAtomic.

  • The is-nilled property of every element node is set to false.

The values of the is-id and is-idrefs properties are not changed.

Note:

Stripping type annotations does not necessarily return the document to the state it would be in had validation not taken place. In particular, any defaulted elements and attributes that were added to the tree by the validation process will still be present, and elements and attributes validated as IDs will still be accessible using the id function.

4.3.2 Stripping Whitespace from a Source Tree

A source tree supplied as input to the transformation process may contain whitespace text nodes that are of no interest, and that do not need to be retained by the transformation. Conceptually, an XSLT processor makes a copy of the source tree from which unwanted whitespace text nodes have been removed. This process is referred to as whitespace stripping.

The stripping process takes as input a set of element names whose child whitespace text nodes are to be preserved. The way in which this set of element names is established using the xsl:strip-space and xsl:preserve-space declarations is described later in this section.

The stripping process that applies for a particular package is determined by the xsl:strip-space and xsl:preserve-space declarations within that package.

A whitespace text node is preserved if either of the following apply:

  • The element name of the parent of the text node is in the set of whitespace-preserving element names.

  • An ancestor element of the text node has an xml:space attribute with a value of preserve, and no closer ancestor element has xml:space with a value of default.

Otherwise, the whitespace text node is stripped.

The xml:space attributes are not removed from the tree.

<!-- Category: declaration -->
<xsl:strip-space
  elements = tokens />

<!-- Category: declaration -->
<xsl:preserve-space
  elements = tokens />

The set of whitespace-preserving element names is specified by xsl:strip-space and xsl:preserve-spacedeclarations. Whether an element name is included in the set of whitespace-preserving names is determined by the best match among all the xsl:strip-space or xsl:preserve-space declarations: it is included if and only if there is no match or the best match is an xsl:preserve-space element. The xsl:strip-space and xsl:preserve-space elements each have an elements attribute whose value is a whitespace-separated list of NameTestsXP; an element name matches an xsl:strip-space or xsl:preserve-space element if it matches one of the NameTestsXP. An element matches a NameTestXP if and only if the NameTestXP would be true for the element as an XPath node test.

[ERR XTSE0270] 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).

Otherwise, when more than one xsl:strip-space and xsl:preserve-space element within the relevant package matches, the best matching element is determined by the best matching NameTestXP. The rules are similar to those for template rules:

If an element in a source document has a type annotation that is a simple type or a complex type with simple content, then any whitespace text nodes among its children are preserved, regardless of any xsl:strip-space declarations. The reason for this is that stripping a whitespace text node from an element with simple content could make the element invalid: for example, it could cause the minLength facet to be violated.

Stripping of type annotations happens before stripping of whitespace text nodes, so this situation will not occur if input-type-annotations="strip" is specified.

Note:

In [XDM 3.04.0], processes are described for constructing an XDM tree from an Infoset or from a PSVI. Those processes deal with whitespace according to their own rules, and the provisions in this section apply to the resulting tree. In practice this means that elements that are defined in a DTD or a Schema to contain element-only content will have whitespace text nodes stripped, regardless of the xsl:strip-space and xsl:preserve-space declarations in the stylesheet.

However, source trees are not necessarily constructed using those processes; indeed, they are not necessarily constructed by parsing XML documents. Nothing in the XSLT specification constrains how the source tree is constructed, or what happens to whitespace text nodes during its construction. The provisions in this section relate only to whitespace text nodes that are present in the tree supplied as input to the XSLT processor. The XSLT processor cannot preserve whitespace text nodes unless they were actually present in the supplied tree.

4.4 Attribute Types and DTD Validation

The mapping from the Infoset to the XDM data model, described in [XDM 3.04.0], does not retain attribute types. This means, for example, that an attribute described in the DTD as having attribute type NMTOKENS will be annotated in the XDM tree as xs:untypedAtomic rather than xs:NMTOKENS, and its typed value will consist of a single xs:untypedAtomic item rather than a sequence of xs:NMTOKEN items.

Attributes with a DTD-derived type of ID, IDREF, or IDREFS will be marked in the XDM tree as having the is-id or is-idrefs properties. It is these properties, rather than any type annotation, that are examined by the functions id and idref described in [Functions and Operators 4.0].

4.6 Limits

The XDM data model (see [XDM 3.04.0]) leaves it to the host language to define limits. This section describes the limits that apply to XSLT.

Limits on some primitive datatypes are defined in [XML Schema Part 2]. Other limits, listed below, are implementation-defined. Note that this does not necessarily mean that each limit must be a simple constant: it may vary depending on environmental factors such as available resources.

The following limits are implementation-defined:

  1. For the xs:decimal type, the maximum number of decimal digits (the totalDigits facet). This must be at least 18 digits. (Note, however, that support for the full value range of xs:unsignedLong requires 20 digits.)

  2. For the types xs:date, xs:time, xs:dateTime, xs:gYear, and xs:gYearMonth: the range of values of the year component, which must be at least +0001 to +9999; and the maximum number of fractional second digits, which must be at least 3.

  3. For the xs:duration type: the maximum absolute values of the years, months, days, hours, minutes, and seconds components.

  4. For the xs:yearMonthDuration type: the maximum absolute value, expressed as an integer number of months.

  5. For the xs:dayTimeDuration type: the maximum absolute value, expressed as a decimal number of seconds.

  6. For the types xs:string, xs:hexBinary, xs:base64Binary, xs:QName, xs:anyURI, xs:NOTATION, and types derived from them: the maximum length of the value.

  7. For sequences, the maximum number of items in a sequence.

5 Features of the XSLT Language

5.1 Names

5.1.1 Qualified Names

Many constructs appearing in a stylesheet, for example named templates, modes, and attribute sets, are named using a qualified name: this consists of a local name and an optional namespace URI.

In most cases where such names are written in a stylesheet, the syntax for expressing the name is given by the production EQNameXP in the XPath specification. In practice, this means that three forms are permitted:

  • A simple NCName appearing on its own (without any prefix). This represents the local name of the object. The interpretation of unprefixed names is described below.

  • A lexical QName written in the form NCName ":" NCName where the first part is a namespace prefix and the second part is the local name. The namespace part of the object’s name is then derived from the prefix by examining the applicable static namespaces for the element node in the stylesheet where the name appears.

  • A URIQualifiedNameXP in the form "Q{" URI? "}" NCName where the two parts of the name, that is the namespace part and the local part, both appear explicitly. If the URI part is omitted (for example Q{}local), the resulting expanded QName is a QName whose namespace part is absent.

The rules for the use of these constructs generally permit leading and trailing whitespace, which is ignored.

Note:

There are a few places where the third form, a URIQualifiedName, is not permitted. These include the name attribute of xsl:element and xsl:attribute (which have a separate namespace attribute for the purpose), and constructs defined by other specifications. For example, names appearing within an embedded xs:schema element must follow the XSD rules.

[Definition: An expanded QName is a value in the value space of the xs:QName datatype as defined in the XDM data model (see [XDM 3.04.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.]

[Definition: 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.]

[Definition: 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.]

Note that every lexical QName is an EQName, but the converse is not true.

The following rules are used when interpreting a lexical QName:

  1. [Definition: 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.]

  2. If the lexical QName has a prefix, then the prefix is expanded into a URI reference using the namespace declarations in effect on its defining element. The expanded QName consisting of the local part of the name and the possibly null URI reference is used as the name of the object. The default namespace of the defining element (see Section 6.2 Element Nodes [XDM 4.0] DM30section 7.4.2 Element nodes) is not used for unprefixed names.

    [ERR XTSE0280] 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.

    [ERR XTDE0290] 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.

  3. If the lexical QName has no prefix, then:

    1. In the case of an unprefixed QName used as a NameTest within an XPath expression (see 5.2 Expressions), and in certain other contexts, the namespace to be used in expanding the QName may be specified by means of the [xsl:]xpath-default-namespace attribute, as specified in 5.1.2 Unprefixed Lexical QNames in Expressions and Patterns.

    2. If the name is in one of the following categories, then the default namespace of the defining element is used:

      1. Where a QName is used to define the name of an element being constructed. This applies both to cases where the name is known statically (that is, the name of a literal result element) and to cases where it is computed dynamically (the value of the name attribute of the xsl:element instruction).

      2. The default namespace is used when expanding the first argument of the function element-available.

      3. The default namespace applies to any unqualified element names appearing in the cdata-section-elements or suppress-indentation attributes of xsl:output or xsl:result-document

    3. In all other cases, a lexical QName with no prefix represents an expanded QName in no namespace (that is, an xs:QName value in which both the prefix and the namespace URI are absent).

5.1.2 Unprefixed Lexical QNames in Expressions and Patterns

Changes in 4.0  

  1. The [xsl:]xpath-default-namespace attribute can be set to the value ##any, which causes unprefixed element names to match in any namespace or none.   [Issue 296 PR 1181 30 April 2024]

5.1.2.1 Unprefixed Element Names

The attribute [xsl:]xpath-default-namespace (see 3.4 Standard Attributes) may be used on an element in the stylesheet to define the namespace that will be used for an unprefixed element or type name within an XPath expression, and in certain other contexts listed below.

The value of the attribute is either the namespace URI to be used, or a zero-length string, or the value ##any.

For any element in the stylesheet, this attribute has an effective value, which is the value of the [xsl:]xpath-default-namespace on that element or on the innermost containing element that specifies such an attribute, or the zero-length string if no containing element specifies such an attribute.

For any element in the stylesheet, the effective value of the attribute determines the value of the default namespace for elements and typesXP in the static context of any XPath expression contained in an attribute or text node of that element (including XPath expressions in attribute value templates and text value templates). The effect of this is specified in [XPath 4.0]; in summary, it determines the namespace used for any unprefixed type name or element name.

The special value ##any only affects:

  • An unprefixed element name used in a NameTestXP, either within an XPath expression or a pattern. Its effect is that an unprefixed name matches any element having the required local name, irrespective of the namespace URI (or lack of it). A pattern such as match="title" is therefore interpreted as a wildcard match match="*:title. The default priority of such a pattern changes accordingly.

  • An unprefixed type name; the effect is to treat the name as referring to a type whose namespace is http://www.w3.org/2001/XMLSchema.

Note:

To take an example, older versions of the internet index of RFCs (requests for comments) use the namespace URI http://www.rfc-editor.org/rfc-index, while newer versions use https://www.rfc-editor.org/rfc-index (note the change of URI scheme). XSLT code that needs to work with either version can be simplified by setting the default namespace to ##any: but be aware that this might lead to spurious matching of names in an unrelated namespace.

Any other value of this attribute sets the default namespace for any of the following constructs appearing within its scope:

  • any unprefixed element name used in a pattern

  • any unprefixed element name used in the elements attribute of the xsl:strip-space or xsl:preserve-space instructions

  • any unprefixed element name used in the as attribute of an XSLT element

  • any unprefixed type name used in the type attribute of an XSLT element

  • any unprefixed type name used in the xsl:type attribute of a literal result element.

The [xsl:]xpath-default-namespace attribute must be in the XSLT namespace if and only if its parent element is not in the XSLT namespace.

If the effective value of the attribute is a zero-length string, which will be the case if it is explicitly set to a zero-length string or if it is not specified at all, then an unprefixed element name or type name refers to a name that is in no namespace. The default namespace of the parent element (see Section 6.2 Element Nodes [XDM 4.0] DM30section 7.4.2 Element nodes) is not used.

The attribute does not affect other names, for example function names, variable names, or template names, or strings that are interpreted as lexical QNames during stylesheet evaluation, such as the effective value of the name attribute of xsl:element or the string supplied as the first argument to the key function.

5.1.3 Reserved Namespaces

[Definition: 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 reserved namespaces are those listed below.

Each of the reserved namespaces has a conventional prefix. As described in 3.7.1 The fixed-namespaces Attribute, the fixed-namespaces attribute may bind one of the reserved namespaces simply by referring to its conventional prefix. For example, fixed-namespaces="xs" has the effect of binding the prefix xs to the namespace http://www.w3.org/2001/XMLSchema.

  • The XSLT namespace described in 3.1.1 XSLT Namespace, is reserved, with conventional prefix xsl.

  • [Definition: 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.]

  • The namespace http://www.w3.org/2005/xpath-functions/math, with conventional prefix math, is used for mathematical functions in the function library defined in [Functions and Operators 3.0][xpath-functions-30].

  • The namespace http://www.w3.org/2005/xpath-functions/map, with conventional prefix map, is used for functions defined in this specification relating to the manipulation of maps.

  • The namespace http://www.w3.org/2005/xpath-functions/array, with conventional prefix array, is reserved for use as described in [Functions and Operators 3.1][xpath-functions-31].

  • [Definition: 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.]This namespace is always bound to the prefix xml.

  • [Definition: The schema namespacehttp://www.w3.org/2001/XMLSchema, with conventional prefix xs, is used as defined in [XML Schema Part 1]]. In a stylesheet this namespace may be used to refer to built-in schema datatypes and to the constructor functions associated with those datatypes.

  • [Definition: The schema instance namespacehttp://www.w3.org/2001/XMLSchema-instance, with conventional prefix xsi, is used as defined in [XML Schema Part 1]]. Attributes in this namespace, if they appear in a stylesheet, are treated by the XSLT processor in the same way as any other attributes.

  • [Definition: 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 namespace http://www.w3.org/2000/xmlns/ is reserved for use as described in [Namespaces in XML]. No element or attribute node can have a name in this namespace, and although the prefix xmlns is implicitly bound to this namespace, no namespace node will ever define this binding.

Note:

With the exception of the XML namespace, any of the above namespaces that are used in a stylesheet must be explicitly declared with a namespace declaration. Although conventional prefixes are used for these namespaces in this specification, any prefix may be used in a user stylesheet.

Reserved namespaces may be used without restriction to refer to the names of elements and attributes in source documents and result documents. As far as the XSLT processor is concerned, reserved namespaces other than the XSLT namespace may be used without restriction in the names of literal result elements and user-defined data elements, and in the names of attributes of literal result elements or of XSLT elements: but other processors may impose restrictions or attach special meaning to them. Reserved namespaces must not be used, however, in the names of stylesheet-defined objects such as variables and stylesheet functions, nor in the names of extension functions or extension instructions.

It is not an error to use a reserved namespace in the name of an extension attribute: attributes such as xml:space and xsi:type fall into this category. XSLT processors must not reject such attributes, and must not attach any meaning to them other than any meaning defined by the relevant specification.

[ERR XTSE0080] 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.

Note:

The name xsl:original is used within xsl:override to refer to a component that is being overridden. Although the name xsl:original is used to refer to the component, the component has its own name, and no component ever has the name xsl:original.

5.2 Expressions

XSLT uses the expression language defined by XPath 4.0 [XPath 4.0]. Expressions are used in XSLT for a variety of purposes including:

  • selecting nodes for processing;

  • specifying conditions for different ways of processing a node;

  • generating text to be inserted in a result tree.

[Definition: Within this specification, the term XPath expression, or simply expression, means a string that matches the production ExprXP defined in [XPath 4.0].]

XPath expressions may occur:

In the above cases, the static processing (compilation) of XPath expressions takes place at the same time as the static processing of the stylesheet itself, while evaluation of the XPath expressions takes place dynamically during stylesheet evaluation. There are also, however:

  • XPath expressions where both the static processing and dynamic evaluation of the XPath expression takes place during static processing of the stylesheet. These are referred to as static expressions, and they perform the same function as preprocessing directives in other languages.

  • XPath expressions that are dynamically constructed (as character strings): both the static processing and dynamic evaluation of these expressions occurs during stylesheet evaluation. See ???.

In general:

  • It is a static error if an XPath expression does not match the XPath production ExprXP, or if it fails to satisfy other static constraints defined in the XPath specification, for example that all variable references must refer to variables that are in scope. Error codes are defined in [XPath 4.0].

  • The transformation fails with a dynamic error if any XPath expression is evaluated and raises a dynamic error. Error codes are defined in [XPath 4.0].

  • The transformation fails with a type error if an XPath expression raises a type error, or if the result of evaluating the XPath expression is evaluated and raises a type error, or if the XPath processor raises a type error during static analysis of an expression. Error codes are defined in [XPath 3.0][xpath-30].

There are some exceptions to these rules, for example:

[Definition: 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.] If no required type is specified, the expression may return any value: in effect, the required type is then item()*.

[Definition:  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.]

Note:

In earlier versions of this specification, the coercion rules were referred to as the function conversion rules.

Note:

These are the rules defined in [XPath 4.0] for converting the supplied argument of a function call to the required type of that argument, as defined in the function signature. The same rules are used in XSLT for converting the value of a variable to the declared type of the variable, or the result of evaluating a function or template body to the declared type of the function or template. They are also used when parameters are supplied to a template using xsl:with-param. In all such cases, the rules that apply are the XPath 4.0 rules without XPath 1.0 compatibility mode. The rules with XPath 1.0 compatibility mode set to true are used only for XPath function calls, and for the operands of certain XPath operators.

This specification also invokes the XPath coercion rules to convert the result of evaluating an XSLT sequence constructor to a required type (for example, the sequence constructor enclosed in an xsl:variable, xsl:template, or xsl:function element).

Any dynamic error or type error that occurs when applying the coercion rules to convert a value to a required type results in the transformation failing, in the same way as if the error had occurred while evaluating an expression.

Note:

Note the distinction between the two kinds of error that may occur. Attempting to convert an integer to a date is a type error, because such a conversion is never possible. Type errors can be raised statically if they can be detected statically, whether or not the construct in question is ever evaluated. Attempting to convert the xs:untypedAtomic item 2003-02-29 to a date is a dynamic error rather than a type error, because the problem is with this particular value, not with its type. Dynamic errors are raised only if the instructions or expressions that cause them are actually evaluated. [XSLT 3.0 Erratum E21, bug 30236]

The XPath specification states (see [XPath 4.0] section Section A.3.3 End-of-Line HandlingXP) that the host language must specify whether the XPath processor normalizes all line breaks on input, before parsing, and if it does so, whether it uses the rules of [XML 1.0] or [XML 1.1]. In the case of XSLT, all handling of line breaks is the responsibility of the XML parser (which may support either XML 1.0 or XML 1.1); the XSLT and XPath processors perform no further changes.

Note:

Most XPath expressions in a stylesheet appear within XML attributes. They are therefore subject to XML line-ending normalization (for example, a CRLF sequence is normalized to LF) and also to XML attribute-value normalization, which replaces tabs and newlines by spaces. Normalization of whitespace can be prevented by using character references such as &#x9;.

XPath expressions appearing in text nodes, (specifically, in text value templates — see 5.6.2 Text Value Templates, or in the xsl:select instruction) are subject to line-ending normalization but not attribute-value normalization.

In both cases it is unwise to include the characters U+0009 (TAB) , U+000A (NEWLINE) , and U+000D (CARRIAGE RETURN) , as literal characters within string literals. Instead they should be escaped as &#x9;, &#xA;, and &#xD; respectively, or constructed dynamically by a call on the char function. This can be conveniently embedded within a string template delimited by backticks: for example `Width:{char(9)}8mm`. (The advantage of using this form in preference to XML character references is that they are more likely to survive when the stylesheet is processed using tools such as XML editors.)

5.3 The Static and Dynamic Context

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 Section 2.2 Expression ContextXP). 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). [XSLT 3.0 Erratum E24, bug 30241]

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

5.3.1 Initializing the Static Context

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.

5.3.3 Initializing the Dynamic Context

For convenience, the dynamic context is described in two parts: the focus, which represents the place in the source document that is currently being processed, and a collection of additional context variables.

A number of functions specified in [Functions and Operators 4.0] are defined to be deterministicFO, meaning that if they are called twice during the same execution scopeFO, with the same arguments, then they return the same results (see [Functions and Operators 4.0] section Section 1.9 TerminologyFO). In XSLT, the execution of a stylesheet defines the execution scope. This means, for example, that if the function current-dateTime is called repeatedly during a transformation, it produces the same result each time. By implication, the components of the dynamic context on which these functions depend are also stable for the duration of the transformation. Specifically, the following components defined in [XPath 4.0] section Section 2.2.2 Dynamic ContextXP must be stable: function implementations, current dateTime, implicit timezone, available documents, available collections, and default collection. The values of global variables and stylesheet parameters are also stable for the duration of a transformation. The focus is not stable; the additional dynamic context components defined in 5.3.4 Additional Dynamic Context Components used by XSLT are also not stable.

As specified in [Functions and Operators 4.0], implementations may provide user options that relax the requirement for the doc and collection functions (and therefore, by implication, the document function) to return stable results. By default, however, the functions must be stable. The manner in which such user options are provided, if at all, is implementation-defined.

XPath expressions contained in [xsl:]use-when attributes are not considered to be evaluated “during the transformation” as defined above. For details see 3.13.3 Conditional Element Inclusion.

[Definition: A component of the context that has no value is said to be absent.] This is a distinguishable state, and is not the same as having the empty sequence as its value.

5.3.3.1 Maintaining Position: the Focus

[Definition: 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.] More specifically, the focus consists of the following three values:

  • [Definition: The context item is the item currently being processed. An item (see [XDM 3.04.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.] The context item is returned by the XPath expression. (dot).

    Note:

    Although XPath 4.0 allows the context value to be an arbitrary sequence, at the interface between XSLT 4.0 and XPath 4.0 it is always either a single item, or absent. XSLT 4.0 therefore continues to use the term context item rather than context valueXP.

  • [Definition: 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 position is returned by the XPath expressionposition().

  • [Definition: 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).] The context size is returned by the XPath expressionlast().

[Definition: 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 node is returned by the XPath expressionself::node(), and it is used as the starting node for all relative path expressions.

Where the containing element of an XPath expression is an instruction or a literal result element, the initial context item, context position, and context size for the XPath expression are the same as the context item, context position, and context size for the evaluation of the containing instruction or literal result element.

The context valueXP for evaluating global variables declared in the top-level package is set to the global context item supplied when the transformation is invoked (see 2.3 Initiating a Transformation). For global variables declared in a library package, the context value is absent. [XSLT 3.0 Erratum E7, bug 30179].

For an XPath expression contained in a value template, the initial context item, context position, and context size for the XPath expression are the same as the context item, context position, and context size for the evaluation of the containing sequence constructor.

In other cases (for example, where the containing element is xsl:sort, xsl:with-param, or xsl:key), the rules are given in the specification of the containing element.

The current function can be used within any XPath expression to select the item that was supplied as the context item to the XPath expression by the XSLT processor. Unlike . (dot) this is unaffected by changes to the context item that occur within the XPath expression. The current function is described in 20.4.1 fn:current.

On completion of an instruction that changes the focus (such as xsl:apply-templates or xsl:for-each), the focus reverts to its previous value.

When a stylesheet function is called, the focus within the body of the function is initially absent.

When the focus is absent, evaluation of any expression that references the context item, context position, or context size results in a type error[ERR XPDY0002] XP40

The description above gives an outline of the way the focus works. Detailed rules for the effect of each instruction are given separately with the description of that instruction. In the absence of specific rules, an instruction uses the same focus as its parent instruction.

[Definition: 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).]

5.3.4 Additional Dynamic Context Components used by XSLT

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 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.

Components of the Dynamic Evaluation Context
ComponentInitial SettingSet byCleared by
focusSee 2.3 Initiating a Transformation.xsl:apply-templates, xsl:for-each, xsl:for-each-group, xsl:analyze-string, evaluation of patternsCalls to stylesheet functions
current template ruleIf apply-templates invocation is used (see 2.3.3 Apply-Templates Invocation), then for each item in the initial match selection, the current template rule is initially set to the template rule chosen for processing that item. Otherwise, absent. xsl:apply-templates, xsl:apply-imports, xsl:next-matchSee 6.10 Overriding Template Rules.
current modethe initial modexsl:apply-templatesCalls to stylesheet functions. Also cleared while evaluating global variables and stylesheet parameters, patterns, and the sequence constructor contained in xsl:key or xsl:sort. Clearing the current mode causes the current mode to be set to the default (unnamed) mode.
current groupabsentxsl:for-each-groupSee 14.2.1 fn:current-group.
current grouping keyabsentxsl:for-each-groupSee 14.2.2 fn:current-grouping-key.
current merge groupabsentxsl:mergeSee 15.6.1 fn:current-merge-group.
current merge keyabsentxsl:mergeSee 15.6.3 fn:current-merge-key and 15.6.2 fn:current-merge-key-array.
current captured substringsempty sequencexsl:matching-substringxsl:non-matching-substring; Calls to stylesheet functions, dynamic function calls, evaluation of global variables, stylesheet parameters, and patterns
output statefinal output stateSet to temporary output state by instructions such as xsl:variable, xsl:attribute, etc., and by calls on stylesheet functionsNone
current output URIbase output URIxsl:result-documentCalls to stylesheet functions, dynamic function calls, evaluation of global variables, stylesheet parameters, and patterns.

[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 calls[TERMDEF dt-dynamic-function-invocation IN XP40]dynamic function invocationsXP, (that is calls to function items as permitted by XPath 3.0). 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. This rule does not extend to the XSLT extensions to the dynamic context defined in this section. If a dynamic function call is made that depends on the XSLT part of the dynamic context (for example, regex-group#1(2)), then the relevant components of the context are cleared as described in the table above.

5.4 Named Types

XSLT 4.0 introduces two new and closely-related constructs allowing item types to be given names, and to be referred to by name anywhere that item types are used, for example in function declarations and variable declarations.

The xsl:item-type declaration allows any item type to be given a name. It is particularly useful to avoid repetitive use of the same choice types, enumeration types, or function types, and means that if the definition changes, the change only needs to be made in one place.

The xsl:record-type declaration takes this a step further. Like xsl:item-type, it allows a name to be given to any record type. In addition, though, it offers two further capabilities:

  • Named record types can be recursive, allowing definitions of recursive data structures such as lists and trees.

  • Declaring a named record type automatically establishes a constructor function for records of that type; the constructor function has the same name as the record type itself.

5.4.2 Named Record Types

Changes in 4.0  

  1. Named record types are introduced.   [Issue 1485  16 January 2025]

<!-- Category: declaration -->
<xsl:record-type
  name = eqname
  constructor? = boolean〔'no'〕
  extensible? = boolean〔'no'〕
  visibility? = "private" | "public"〔'private'〕 >
  <!-- Content: (xsl:field*) -->
</xsl:record-type>

<xsl:field
  name = ncname
  as? = sequence-type〔'item()*'〕
  required? = boolean〔'yes'〕
  default? = expression />

An xsl:record-type declaration associates a name with a record type, and allows the record type to be referenced by name throughout the stylesheet package.

The following example declares a named record type for complex numbers, and uses it in a variable declaration and a function declaration.

<xsl:record-type name="cx:complex">
    <xsl:field name="r" as="xs:double"/>
    <xsl:field name="i" as="xs:double"/>
</xsl:record-type>
   
<xsl:variable name="i" as="cx:complex" select="cx:complex(0, 1)"/>
   
<xsl:function name="cx:add" as="cx:complex">
  <xsl:param name="x" as="cx:complex"/>
  <xsl:param name="y" as="cx:complex"/>
  <xsl:sequence select="cx:complex($x?r + $y?r, $x?i + $y?i)"/>
</xsl:function>

Note how the record type declaration has implicitly declared a constructor function cx:complex that can be used to create instances of the item type.

[ERR XTSE4050] It is a static error if the names of the fields in an xsl:record-type declaration are not distinct.

[ERR XTSE4051] It is a static error if an xsl:field element has a default attribute unless it specifies required="no".

An xsl:record-type declaration has two effects:

  • In the same way as xsl:item-type, it defines a named item type in the static context, allowing the record type to be referenced by name anywhere an ItemType can appear, for example in the declarations of functions and variables. Unlike types declared in xsl:item-type, however, named record types can be recursive.

  • An xsl:record-type declaration also implicitly defines a constructor function, of the same name, and adds this to the set of statically known function definitionsXP in the static context.

Because of its dual role, the name of an xsl:record-type declaration must be valid both as an item type name and as a function name. This means the name must be distinct from other type names and function names in the static context. It also means that the name must be in a namespace.

Considered as an item type, the xsl:record-type declaration is equivalent to an xsl:item-type declaration formed by the following template rule, evaluated in the context of a namespace alias <xsl:namespace-alias stylesheet-prefix="t" result-prefix="xsl"/>:

<xsl:template match="xsl:record-type" expand-text="yes">
   <t:item-type name="{@name}"
                visibility="{@visibility otherwise 'private'}">
     <xsl:attribute name="as">
        <xsl:text>record(</xsl:text>
        <xsl:for-each select="xsl:field" separator=", ">
           <xsl:variable name="optional"
                         as="xs:boolean"
                         select="normalize-space(@required) = ('no','false','0')"/>
           {@name}{'?'[$optional]} as {@as otherwise 'item()*'}
        </xsl:for-each>
        <xsl:if test="normalize-space(@extensible) = ('yes','true','1')">
           <xsl:text>, *</xsl:text>
        </xsl:if>
        <xsl:text>)</xsl:text>
      </xsl:attribute>  
   </t:item-type>
</xsl:template>

This generated xsl:item-type declaration must meet all the constraints placed on user-written xsl:item-type declarations, including the rule requiring names to be unique, but not including the rule disallowing recursive references.

For example, the declaration:

<xsl:record-type name="cx:complex" extensible="yes">
    <xsl:field name="r" as="xs:double"/>
    <xsl:field name="i" as="xs:double" required="no" default="0"/>
</xsl:record-type>

produces the equivalent item type declaration:

<xsl:item-type name="cx:complex"
       as="record(r as xs:double, i? as xs:double, *)"/>

Considered as a function declaration, an xsl:record-type declaration is equivalent to an xsl:function declaration formed by the following template rule, evaluated in the context of a namespace alias <xsl:namespace-alias stylesheet-prefix="t" result-prefix="xsl"/>:

<xsl:template match="xsl:record-type">
    <t:function name="{@name}"
                as="{@name}"
                visibility="{(@visibility otherwise 'private')}">
                
      <!-- if the record type is extensible, choose a name for the options parameter -->
      <xsl:variable name="options-param" as="xs:string?">
         <xsl:if test="normalize-space(@extensible) = ('yes', 'true', 'a')"
                 then="('options', (1 to count(xsl:field)) ! `options{.}`)
                         [not(. = current()/xsl:field/@name)][1]"/>
      </xsl:variable>                   
      
      <!-- declare the parameters -->
      <xsl:for-each select="xsl:field">
         <t:param name="{@name}"
                  required="{@required otherwise 'yes'}">
            <xsl:attribute name="as">
               <xsl:variable name="as" 
                             select="normalize-space(@as otherwise 'item()*')"/>
               <xsl:variable name="optional" 
                             select="normalize-space(@required) = ('no', 'false', '0')"/>
               <xsl:choose>
                  <xsl:when test="not($optional)" select="$as"/>
                  <!-- for optional fields, amend the required type to allow () -->
                  <xsl:when test="matches($as, '[?*]$')" select="$as"/>
                  <xsl:when test="matches($as, '\+$')" select="replace($as, '\+$', '*')"/>
                  <xsl:otherwise select="$as || '?'"/>
               </xsl:choose>
            </xsl:attribute>
            <xsl:if test="@default">
               <xsl:attribute name="select" select="@default"/>
            </xsl:if>   
         </t:param>
      </xsl:for-each>
      
      <!-- for an extensible record type, declare the options parameter -->
      <xsl:if test="exists($options-param)">
         <t:param name="{$options-param}" as="map(*)" required="no" select="{}"/>
      </xsl:if>           
      
      <!-- function body: construct a map -->
      <t:map duplicates="fn($first, $second){{$first}}">
         <xsl:for-each select="xsl:field">
            <xsl:variable name="optional" 
                          select="normalize-space(@required) = ('no', 'false', '0')"/>
            <xsl:choose>
              <xsl:when test="$optional and not(@default)">
                 <!-- omit map entries for optional fields if no value is supplied -->
                 <t:if test="exists(${@name})">
                    <t:map-entry key="'{@name}'" select="${@name}"/>
                 </t:if>
              </xsl:when>
              <xsl:otherwise>
                <t:map-entry key="'{@name}'" select="${@name}"/>
              </xsl:otherwise>  
            </xsl:choose>  
         </xsl:for-each>
        
         <!-- if the record type is extensible, 
              add entries from the options parameter -->
              
         <xsl:if test="exists($options-param)">
            <t:sequence select="${$options-param}"/>
         </xsl:if>   

      </t:map>
    </t:function>          
</xsl:template>

For example, the declaration:

<xsl:record-type name="cx:complex">
    <xsl:field name="r" as="xs:double"/>
    <xsl:field name="i" as="xs:double" required="no" default="0"/>
</xsl:record-type>

produces the equivalent function declaration:

<xsl:function name="cx:complex" as="cx:complex" visibility="private">
    <xsl:param name="r" as="xs:double"/>
    <xsl:param name="i" as="xs:double" required="no" select="0"/>
    <xsl:map>
       <xsl:map-entry key="'r'" select="$r"/>
       <xsl:map-entry key="'i'" select="$i"/>
    </xsl:map>
</xsl:function>

No entry is generated in the constructed map for a field that is declared as optional with no default. So the declaration:

<xsl:record-type name="cx:complex" visibility="public">
    <xsl:field name="r" as="xs:double"/>
    <xsl:field name="i" as="xs:double" required="no"/>
</xsl:record-type>

produces the equivalent function declaration:

<xsl:function name="cx:complex" as="cx:complex" visibility="public">
    <xsl:param name="r" as="xs:double"/>
    <xsl:param name="i" as="xs:double?" required="no"/>
    <xsl:map>
       <xsl:map-entry key="'r'" select="$r"/>
       <xsl:if test="exists($i)">
          <xsl:map-entry key="'i'" select="$i"/>
       </xsl:if>   
    </xsl:map>
</xsl:function>

If the record type is extensible, the generated function includes an optional options parameter So the declaration:

<xsl:record-type name="cx:complex" extensible="yes">
    <xsl:field name="r" as="xs:double"/>
    <xsl:field name="i" as="xs:double"/>
</xsl:record-type>

produces the equivalent function declaration:

<xsl:function name="cx:complex" as="cx:complex" visibility="private">
    <xsl:param name="r" as="xs:double"/>
    <xsl:param name="i" as="xs:double"/>
    <xsl:param name="options" as="map(*)" required="no" default="{}"/>
    <xsl:map duplicates="fn($first, $second){$first}">
       <xsl:map-entry key="'r'" select="$r"/>
       <xsl:map-entry key="'i'" select="$i"/>
       <xsl:sequence select="$options"/>   
    </xsl:map>
</xsl:function>

This generated xsl:function declaration must meet all the constraints placed on user-written xsl:function declarations, including the rule requiring the combination of name and arity to be unique.

The generated xsl:function declaration has the import precedence associated with the stylesheet module in which the xsl:record-type declaration appears, and it may be overridden by another xsl:function declaration with higher import precedence. If the visibility is public then it can also be overridden using xsl:override in another package.

The scope of a named record type is the package in which it is declared. If it is declared with visibility="public" then it also becomes available for use in using packages.

The name of the record type is the expanded name formed by resolving the name attribute. Because function names are always in a namespace, the name must be prefixed.

If two xsl:record-type declarations in a package have the same name, then the one with higher import precedence is used.

A record type declaration may refer directly or indirectly to itself if it satisfies the conditions defined in [XPath 4.0] section Section 3.2.8.3.1 Recursive Record TypesXP. This allows types to be declared that match recursive data structures such as linked lists and trees.

A named record type with visibility private may be used in the definition of a component (such as a variable, a function, a template, or another named record type) that is itself public. Another package may reference such a component even though it cannot reference the types used in its definition. The fact that the record type is private, however, means that it is impossible to override a variable or function that references the record type.

Example: Defining a Binary Tree

This example illustrates the definition of a recursive record type. The record type represents a node of a binary tree containing a payload value in each node, together with optional references to left and right subtrees. As well as the data fields, the record type defines a depth function that returns the maximum depth of the tree, by making recursive calls on its subtrees.

<xsl:record-type name="my:binary-tree">
   <xsl:field name="left" as="my:binary-tree?"/>
   <xsl:field name="payload" as="item()*"/>
   <xsl:field name="right" as="my:binary-tree?"/>
   <xsl:field name="depth" as="fn(my:binary-tree) as xs:integer"
      default="fn {1 + max((?left ?> depth(), ?right ?> depth())) otherwise 0)}"/>
</xsl:record-type>

Method calls (using the operator ?>) are described in [XPath 4.0] section Section 4.13.4 Method CallsXP. The effect is to give a function item contained in a map access to the containing map. They thus mimic method invocation in object-oriented languages, though there is no inheritance or encapsulation.

The following code builds a simple tree and calculates its depth:

let $tree := my:binary-tree(
               my:binary-tree((), 17, ()),
               18,
               my:binary-tree((), 19, 
                 my:binary-tree((), 20, ())))
return $tree ?> depth()

Returning the result 3.

A more detailed example that uses a recursive named record type appears in the following section.

5.7 Sequence Constructors

[Definition: 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.]

Many XSLT elements, and also literal result elements, are defined to take a sequence constructor as their content.

Four kinds of nodes may be encountered in a sequence constructor:

  1. A Text node appearing in the stylesheet (if it has not been removed in the process of whitespace stripping: see 3.13.1 Stripping Whitespace and Commentary from the Stylesheet) is processed as follows:

    1. if the effective value of the standard attribute [xsl:]expand-text is no, or in the absence of this attribute, the text node in the stylesheet is copied to create a new parentless text node in the result of the sequence constructor.

    2. Otherwise (the effective value of [xsl:]expand-text is yes), the text node in the stylesheet is processed as described in 5.6.2 Text Value Templates.

  2. A literal result element is evaluated to create a new parentless element node, having the same expanded QName as the literal result element: see 11.1 Literal Result Elements.

  3. An XSLT instruction produces a sequence of zero, one, or more items as its result. For most XSLT instructions, these items are nodes, but some instructions (such as xsl:sequence, xsl:select, xsl:map, xsl:array, and xsl:copy-of) can also produce atomic items or function items.

    Several instructions, such as xsl:element, return a newly constructed parentless node (which may have its own attributes, namespaces, children, and other descendants). Other instructions, such as xsl:if, pass on the items produced by their own nested sequence constructors.

    Three instructions serve primarily to evaluate XPath expressions:

    • The xsl:sequence instruction evaluates an XPath expression written statically in its select attribute.

    • The xsl:select instruction evaluates an XPath expression written statically in its contained text node.

    • The xsl:evaluate instruction compiles and evaluates an XPath expression that is constructed dynamically as a character string.

    These three instructions may return atomic items, function items, or nodes.

  4. An extension instruction (see 24.2 Extension Instructions) also produces a sequence of items as its result.

[Definition: 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.]

However:

The way that immediate result of a sequence constructor is used depends on the containing element in the stylesheet, and is specified in the rules for that element. It is typically one of the following:

5.7.1 Constructing Complex Content

Many instructions, for example xsl:copy, xsl:element, xsl:document, xsl:result-document, and literal result elements, create a new parent node, and evaluate a sequence constructor forming the content of the instruction to create the attributes, namespaces, and children of the new parent node. The immediate result of the sequence constructor is processed to create the content of the new parent node as described in this section.

When constructing the content of an element, the inherit-namespaces attribute of the xsl:element or xsl:copy instruction, or the xsl:inherit-namespaces property of the literal result element, determines whether namespace nodes are to be inherited. The effect of this attribute is described in the rules that follow.

The immediate result of the sequence constructor is processed as follows (applying the rules in the order they are listed):

  1. The containing instruction may generate attribute nodes and/or namespace nodes, as specified in the rules for the individual instruction. For example, these nodes may be produced by expanding an [xsl:]use-attribute-sets attribute, or by expanding the attributes of a literal result element. Any such nodes are prepended to the immediate result of the sequence constructor.

  2. Any array item in the sequence (see 22 Arrays) is replaced by its members, recursively. This is equivalent to applying the array:flatten function defined in [Functions and Operators 3.1][xpath-functions-31].

  3. Any atomic item in the sequence is cast to a string.

    Note:

    Casting from xs:QName or xs:NOTATION to xs:string always succeeds, because these values retain a prefix for this purpose. However, there is no guarantee that the prefix used will always be meaningful in the context where the resulting string is used.

  4. Any consecutive sequence of strings in the sequence is converted to a single text node, whose string value contains the content of each of the strings in turn, with U+0020 (SPACE) used as a separator between successive strings.

  5. Any document node within the sequence is replaced by a sequence containing each of its children, in document order.

  6. Zero-length text nodes within the sequence are removed.

  7. Adjacent text nodes within the sequence are merged into a single text node.

  8. Invalid items in the sequence are detected as follows.

    [ERR XTDE0410] 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.

    [ERR XTDE0420] It is a dynamic error if the sequence used to construct the content of a document node contains a namespace node or attribute node.

    [ERR XTDE0430] 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).

    [ERR XTDE0440] 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).

    [ERR XTDE0450] It is a type error if the result sequence contains a function item.

    Note:

    The error code reflects the fact that this error was at one time classified as a dynamic error rather than a type error. [XSLT 3.0 Erratum E17, bug 30223].

  9. If the sequence contains two or more namespace nodes with the same name (or no name) and the same string value (that is, two namespace nodes mapping the same prefix to the same namespace URI), then all but one of the duplicate nodes are discarded.

    Note:

    Since the order of namespace nodes is implementation-dependent, it is not significant which of the duplicates is retained.

  10. If an attribute A in the sequence has the same name as another attribute B that appears later in the sequence, then attribute A is discarded from the sequence. Before discarding attribute A, the processor may raise any type errors that would be raised if attribute B were not present.

  11. Each node in the resulting sequence is attached as a namespace, attribute, or child of the newly constructed element or document node. Conceptually this involves making a deep copy of the node; in practice, however, copying the node will only be necessary if the existing node can be referenced independently of the parent to which it is being attached. When copying an element or processing instruction node, its base URI property is changed to be the same as that of its new parent, unless it has an xml:base attribute (see [XML Base]) that overrides this. If the copied element has an xml:base attribute, its base URI is the value of that attribute, resolved (if it is relative) against the base URI of the new parent node.

    Except for the handling of base URI, the copying of a node follows the rules of the xsl:copy-of instruction with attributes copy-namespaces="yes" copy-accumulators="no" validation="preserve".

    Note:

    This has the consequence that the type annotation and the values of the nilled, is-id, and is-idrefs properties are retained. However, if the node under construction (the new parent of the node being copied) uses a validation mode other than preserve, this will be transient: the values will be recomputed when the new parent node is validated.

  12. If the newly constructed node is an element node, then namespace fixup is applied to this node, as described in 5.7.3 Namespace Fixup.

  13. If the newly constructed node is an element node, and if namespaces are inherited, then each namespace node of the newly constructed element (including any produced as a result of the namespace fixup process) is copied to each descendant element of the newly constructed element, unless that element or an intermediate element already has a namespace node with the same name (or absence of a name) or that descendant element or an intermediate element is in no namespace and the namespace node has no name.

Example: A Sequence Constructor for Complex Content

Consider the following stylesheet fragment:

<td>
  <xsl:attribute name="valign">top</xsl:attribute>
  <xsl:value-of select="@description"/>
</td>

This fragment consists of a literal result element td, containing a sequence constructor that consists of two instructions: xsl:attribute and xsl:value-of. The sequence constructor is evaluated to produce a sequence of two nodes: a parentless attribute node, and a parentless text node. The td instruction causes a td element to be created; the new attribute therefore becomes an attribute of the new td element, while the text node created by the xsl:value-of instruction becomes a child of the td element (unless it is zero-length, in which case it is discarded).

 

Example: Space Separators in Element Content

Consider the following stylesheet fragment:

<doc>
  <e><xsl:sequence select="1 to 5"/></e>
  <f>
    <xsl:for-each select="1 to 5">
      <xsl:value-of select="."/>
    </xsl:for-each>
  </f>
</doc>

This produces the output (when indented):

<doc>
  <e>1 2 3 4 5</e>
  <f>12345</f>
</doc>

The difference between the two cases is that for the e element, the sequence constructor generates a sequence of five atomic items, which are therefore separated by spaces. For the f element, the content is a sequence of five text nodes, which are concatenated without space separation.

It is important to be aware of the distinction between xsl:sequence, which returns the value of its select expression unchanged, and xsl:value-of, which constructs a text node.

5.7.3 Namespace Fixup

In a tree supplied to or constructed by an XSLT processor, the constraints relating to namespace nodes that are specified in [XDM 3.04.0]must be satisfied. For example:

  • If an element node has an expanded QName with a non-null namespace URI, then that element node must have at least one namespace node whose string value is the same as that namespace URI.

  • If an element node has an attribute node whose expanded QName has a non-null namespace URI, then the element must have at least one namespace node whose string value is the same as that namespace URI and whose name is non-empty.

  • Every element must have a namespace node whose expanded QName has local-part xml and whose string value is http://www.w3.org/XML/1998/namespace. The namespace prefix xmlmust not be associated with any other namespace URI, and the namespace URI http://www.w3.org/XML/1998/namespacemust not be associated with any other prefix.

  • A namespace node must not have the name xmlns or the string value http://www.w3.org/2000/xmlns/.

[Definition: 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 actual namespace nodes that are added to the tree by the namespace fixup process are implementation-dependent, provided firstly, that at the end of the process the above constraints must all be satisfied, and secondly, that a namespace node must not be added to the tree unless the namespace node is necessary either to satisfy these constraints, or to enable the tree to be serialized using the original namespace prefixes from the source document or stylesheet.

Namespace fixup must not result in an element having multiple namespace nodes with the same name.

Namespace fixup may, if necessary to resolve conflicts, change the namespace prefix contained in the QName value that holds the name of an element or attribute node. This includes the option to add or remove a prefix. However, namespace fixup must not change the prefix component contained in a value of type xs:QName or xs:NOTATION that forms the typed value of an element or attribute node.

Note:

Namespace fixup is not used to create namespace declarations for xs:QName or xs:NOTATION values appearing in the content of an element or attribute.

Where values acquire such types as the result of validation, namespace fixup does not come into play, because namespace fixup happens before validation: in this situation, it is the user’s responsibility to ensure that the element being validated has the required namespace nodes to enable validation to succeed.

Where existing elements are copied along with their existing type annotations (validation="preserve") the rules require that existing namespace nodes are also copied, so that any namespace-sensitive values remain valid.

Where existing attributes are copied along with their existing type annotations, the rules of the XDM data model require that a parentless attribute node cannot contain a namespace-sensitive typed value; this means that it is an error to copy an attribute using validation="preserve" if it contains namespace-sensitive content.

Namespace fixup is applied to every element that is constructed using a literal result element, or one of the instructions xsl:element, xsl:copy, or xsl:copy-of. An implementation is not required to perform namespace fixup for elements in any source document, that is, for a document in the initial match selection, documents loaded using the document, doc or collection function, documents supplied as the value of a stylesheet parameter, or documents returned by an extension function or extension instruction.

Note:

A source document (an input document, a document returned by the document, doc or collection functions, a document returned by an extension function or extension instruction, or a document supplied as a stylesheet parameter) is required to satisfy the constraints described in [XDM 3.04.0], including the constraints imposed by the namespace fixup process. The effect of supplying a pseudo-document that does not meet these constraints is implementation-dependent.

In an Infoset (see [XML Information Set]) created from a document conforming to [Namespaces in XML], it will always be true that if a parent element has an in-scope namespace with a non-empty namespace prefix, then its child elements will also have an in-scope namespace with the same namespace prefix, though possibly with a different namespace URI. This constraint is removed in [Namespaces in XML 1.1]. XSLT 4.0 supports the creation of result trees that do not satisfy this constraint: the namespace fixup process does not add a namespace node to an element merely because its parent node in the result tree has such a namespace node. However, the process of constructing the children of a new element, which is described in 5.7.1 Constructing Complex Content, does cause the namespaces of a parent element to be inherited by its children unless this is prevented using [xsl:]inherit-namespaces="no" on the instruction that creates the parent element.

Note:

This has implications on serialization, defined in [XSLT and XQuery Serialization][xslt-xquery-serialization-30]. It means that it is possible to create final result trees that cannot be faithfully serialized as XML 1.0 documents. When such a result tree is serialized as XML 1.0, namespace declarations written for the parent element will be inherited by its child elements as if the corresponding namespace nodes were present on the child element, except in the case of the default namespace, which can be undeclared using the construct xmlns="". When the same result tree is serialized as XML 1.1, however, it is possible to undeclare any namespace on the child element (for example, xmlns:foo="") to prevent this inheritance taking place.

5.8 URI References

[Definition: 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].] Note that this is a wider definition than that in [RFC3986]: in particular, it is designed to accommodate Internationalized Resource Identifiers (IRIs) as described in [RFC3987], and thus allows the use of non-ASCII characters without escaping.

URI References are used in XSLT with three main roles:

  • As namespace URIs

  • As collation URIs

  • As identifiers for resources such as stylesheet modules; these resources are typically accessible using a protocol such as HTTP. Examples of such identifiers are the URIs used in the href attributes of xsl:import, xsl:include, xsl:result-document, and xsl:package-location.

The rules for namespace URIs are given in [Namespaces in XML] and [Namespaces in XML 1.1]. Those specifications deprecate the use of relative URI references as namespace URIs.

The rules for collation URIs are given in [Functions and Operators 4.0] section Section 5.3.1 CollationsFO.

URI references used to identify external resources must conform to the same rules as the locator attribute (href) defined in section 5.4 of [XLink]. If the URI reference is relative, then it is resolved (unless otherwise specified) against the base URI of the containing element node, according to the rules of [RFC3986], after first escaping all characters that need to be escaped to make it a valid RFC3986 URI reference. (But a relative URI reference in the href attribute of xsl:result-document is resolved against the Base Output URI.)

Other URI references appearing in an XSLT stylesheet document, for example the system identifiers of external entities or the value of the xml:base attribute, must follow the rules in their respective specifications.

The base URI of an element node in the stylesheet is determined as defined in [XDM 4.0] section Section 5.27.5.2 base-uri Accessor DM30. Some implementations may allow the output of the static analysis phase of stylesheet processing (a “compiled stylesheet”) to be evaluated in a different location from that where static analysis took place. Furthermore, stylesheet authors may in such cases wish to avoid exposing the location of resources that are private to the development environment. If the base URI of an element in the stylesheet is defined by an absolute URI appearing in an xml:base attribute within the stylesheet, this value must be used as the static base URI. In other cases where processing depends on the static base URI of a stylesheet module, implementations may use different values for the static base URI during static analysis and during dynamic evaluation (for example, an implementation may use different base URIs for resolving xsl:import module references and for resolving a relative reference used as an argument to the doc function). In such cases an implementation must document how the static base URI is computed for each situation in which it is required.

6 Template Rules

Template rules define the processing that can be applied to items that match a particular pattern.

6.3 Patterns

In XSLT 4.0, patterns can match any kind of item: atomic items and function items as well as nodes.

A template rule identifies the items to which it applies by means of a pattern. As well as being used in template rules, patterns are used for numbering (see 12 Numbering), for grouping (see 14 Grouping), and for declaring keys (see 20.2 Keys).

[Definition: 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.]

There are three kinds of pattern: predicate patterns, type patterns, and node patterns:

  • [Definition: 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 predicate pattern .[P1][P2]... can be regarded as an abbreviation for the type pattern type(item())[P1][P2]....

    The detailed semantics are given in 6.3.2.1 Predicate Patterns. This construct can be used to match items of any kind (nodes, atomic items, and function items). For example, the pattern .[starts-with(., '$')] matches any string that starts with the character $, or a node whose atomized value starts with $. This example shows a predicate pattern with a single predicate, but the grammar allows any number of predicates (zero or more).

  • [Definition: A type pattern can be written as type(T) (where T is an ItemTypeXP followed by zero or more predicates in square brackets, and it matches any item of type T which each of the predicates evaluates to true.]

    The parameter T can also be a list of item types, separated by "|". For example, type(array(*) | map(*)) matches arrays and maps, while type(text() | comment()) matches text nodes and comment nodes.

    The most commonly used type patterns can be abbreviated. For example, match="type(record(F1, F2, *))" can be abbrevated to match="record(F1, F2, *)", and match="type(array(xs:string))" can be abbreviated to match="array(xs:string)". The main case where such abbreviation is not possible is with atomic items: match="type(xs:date)" cannot be abbreviated because a bare QName is interpreted as a node pattern, matching elements named xs:date. The pattern match="type(text() | comment())" has almost the same effect as match="text() | comment()", except that the rules for calculating a default priority are different.

  • [Definition: A node pattern uses a subset of the syntax for path expressions, and is defined to match a node if the corresponding path expression would select the node. Node patterns may also be formed by combining other patterns using union, intersection, and difference operators.]

    The syntax for node patterns (UnionExprP in the grammar: see 6.3.2 Syntax of Patterns) is a subset of the syntax for expressions. Node patterns are used only for matching nodes; an item other than a node will never match a node pattern. As explained in detail below, a node matches a node pattern if the node can be selected by deriving an equivalent expression, and evaluating this expression with respect to some possible context.

Note:

The specification uses the phrases an item matches a pattern and a pattern matches an item interchangeably. They are equivalent: an item matches a pattern if and only if the pattern matches the item.

6.3.2 Syntax of Patterns

[ERR XTSE0340] Where an attribute is defined to contain a pattern, it is a static error if the pattern does not match the production Pattern40.

The complete grammar for patterns is listed in E Pattern Syntax Summary. It uses the notation defined in [XPath 4.0] section Section A.1.1 NotationXP.

The lexical rules for patterns are the same as the lexical rules for XPath expressions, as defined in [XPath 4.0] section Section A.3 Lexical structureXP. Comments are permitted between tokens, using the syntax (: ... :). All other provisions of the XPath grammar apply where relevant, for example the rules for whitespace handling and extra-grammatical constraints.

Pattern40::=PredicatePattern | TypePattern | NodePattern
PredicatePattern::="." PredicateXP*
TypePattern::=(WrappedItemTest | AnyItemTestXP | FunctionTypeXP | MapTypeXP | ArrayTypeXP | RecordTypeXP | EnumerationTypeXP) PredicateXP*
NodePattern::=UnionExprP

Patterns fall into three groups:

  • A PredicatePattern matches items according to conditions that the item must satisfy: for example .[. castable as xs:integer] matches any value (it might be an atomic item, a node, or an array) that is castable as an integer.

  • A TypePattern matches items according to their type. For example type(xs:integer) matches an atomic item that is an instance of xs:integer, while record(longitude, latitude) matches a map that has exactly two entries, with keys "longitude" and "latitude"

  • A NodePattern matches nodes in a tree, typically by specifying a path that can be used to locate the nodes: for example order matches an element node named order, while billing-address/city matches an element named city whose parent node is an element named billing-address.

The following sections define the rules for each of these groups.

6.3.2.4 The Meaning of a Node Pattern

The meaning of a node pattern is defined formally as follows, where “if” is to be read as “if and only if”.

  1. A node matches a UnionExprPA union B (or equivalently, A | B) if it matches either A or B or both.

  2. A node matches an IntersectExceptExprPA intersect B if it matches both A and B.

  3. A node matches an IntersectExceptExprPA except B if it matches A and does not match B.

  4. A node matches a PathExprP under the following conditions:

    1. If the PathExprP consists in its entirety of a ParenthesizedExprP, then the node matches the ParenthesizedExprP if it matches the UnionExprP enclosed within the parentheses.

    2. Otherwise, the PathExprP pattern is converted to an expression, called the equivalent expression. The equivalent expression to a PathExprP is the XPath expression that takes the same lexical form as the PathExprP as written, with the following adjustment:

      If any PathExprP in the Pattern is a RelativePathExprP, then the first StepExprPPS of this RelativePathExprP is adjusted to allow it to match a parentless element, attribute, or namespace node. The adjustment depends on the axis used in this step, whether it appears explicitly or implicitly (according to the rules of [XPath 4.0] section Section 4.6.7 Abbreviated SyntaxXP), and is made as follows:

      1. If the NodeTest in PS is document-node() (optionally with arguments), and if no explicit axis is specified, then the axis in step PS is taken as self rather than child.

      2. If PS uses the child axis (explicitly or implicitly), and if the NodeTest in PS is not document-node() (optionally with arguments), then the axis in step PS is replaced by child-or-top, which is defined as follows. If the context node is a parentless element, comment, processing-instruction, or text node then the child-or-top axis selects the context node; otherwise it selects the children of the context node. It is a forwards axis whose principal node kind is element.

      3. If PS uses the attribute axis (explicitly or implicitly), then the axis in step PS is replaced by attribute-or-top, which is defined as follows. If the context node is an attribute node with no parent, then the attribute-or-top axis selects the context node; otherwise it selects the attributes of the context node. It is a forwards axis whose principal node kind is attribute.

      4. If PS uses the namespace axis (explicitly or implicitly), then the axis in step PS is replaced by namespace-or-top, which is defined as follows. If the context node is a namespace node with no parent, then the namespace-or-top axis selects the context node; otherwise it selects the namespace nodes of the context node. It is a forwards axis whose principal node kind is namespace.

      The axes child-or-top, attribute-or-top, and namespace-or-top are introduced only for definitional purposes. They cannot be used explicitly in a user-written pattern or expression.

      Note:

      The purpose of this adjustment is to ensure that a pattern such as person matches any element named person, even if it has no parent; and similarly, that the pattern @width matches any attribute named width, even a parentless attribute. The rule also ensures that a pattern using a NodeTest of the form document-node(...) matches a document node. The pattern node() will match any element, text node, comment, or processing instruction, whether or not it has a parent. For backwards compatibility reasons, the pattern node(), when used without an explicit axis, does not match document nodes, attribute nodes, or namespace nodes. The rules are also phrased to ensure that positional patterns of the form para[1] continue to count nodes relative to their parent, if they have one. To match any node at all, XSLT 4.0 allows the pattern .[. instance of node()] to be used.

    The meaning of the pattern is then defined in terms of the semantics of the equivalent expression, denoted below as EE.

    Specifically, an item N matches a PathExprP pattern P if the following applies, where EE is the equivalent expression to P:

    • N is a node, and the result of evaluating the expression root(.)//(EE) with a singleton focus based on N is a sequence that includes the node N.

If a pattern appears in an attribute of an element that is processed with XSLT 1.0 behavior (see 3.9 Backwards Compatible Processing), then the semantics of the pattern are defined on the basis that the equivalent XPath expression is evaluated with XPath 1.0 compatibility mode set to true.

Note:

This version of the specification includes an incompatible change to the semantics of patterns using the intersect and except operators. This change is made to eliminate cases where the behavior defined in XSLT 3.0 was counter-intuitive.

Consider the pattern para except appendix//para. In XSLT 4.0 this matches any para element that is not the descendant of an appendix element. In XSLT 3.0 it would match the para element in the XML tree shown below:

<appendix>
  <section>
     <para/>
  </section>
</appendix>

because there is an element $S (specifically, the section element), such that the expression $S//(para except appendix//para) selects this para element.

It is recommended that processors should report a compatibility warning when such constructs are encountered. The problem arises with patterns using intersect or except where one of the branches uses the descendant axis: it does not arise in simple cases like * except A, or @* except @code, where the branches only use the child or attribute axis.

The change does not affect the meaning of patterns that use the intersect or except operators nested within a path expression, for example a pattern such as A[.//C except B//C].

Example: The Semantics of Node Patterns

The node patternp matches any p element, because a p element will always be present in the result of evaluating the expressionroot(.)//(child-or-top::p). Similarly, / matches a document node, and only a document node, because the result of the expressionroot(.)//(/) returns the root node of the tree containing the context node if and only if it is a document node.

The node patternnode() matches all nodes selected by the expression root(.)//(child-or-top::node()), that is, all element, text, comment, and processing instruction nodes, whether or not they have a parent. It does not match attribute or namespace nodes because the expression does not select nodes using the attribute or namespace axes. It does not match document nodes because for backwards compatibility reasons the child-or-top axis does not match a document node.

Note:

The pattern type(node()) matches all nodes.

The node pattern$V matches all nodes selected by the expression root(.)//($V), that is, all nodes in the value of $V (which will typically be a global variable, though when the pattern is used in contexts such as the xsl:number or xsl:for-each-group instructions, it can also be a local variable).

The node patterndoc('product.xml')//product matches all nodes selected by the expression root(.)//(doc('product.xml')//product), that is, all product elements in the document whose URI is product.xml.

The node patternroot(.)/self::E matches an E element that is the root of a tree (that is, an E element with no parent node).

Although the semantics of node patterns are specified formally in terms of expression evaluation, it is possible to understand pattern matching using a different model. A node pattern such as book/chapter/section can be examined from right to left. A node will only match this pattern if it is a section element; and then, only if its parent is a chapter; and then, only if the parent of that chapter is a book. When the pattern uses the // operator, one can still read it from right to left, but this time testing the ancestors of a node rather than its parent. For example appendix//section matches every section element that has an ancestor appendix element.

The formal definition, however, is useful for understanding the meaning of a pattern such as para[1]. This matches any node selected by the expression root(.)//(child-or-top::para[1]): that is, any para element that is the first para child of its parent, or a para element that has no parent.

Note:

An implementation, of course, may use any algorithm it wishes for evaluating patterns, so long as the result corresponds with the formal definition above. An implementation that followed the formal definition by evaluating the equivalent expression and then testing the membership of a specific node in the result would probably be very inefficient.

Note:

Patterns using the intersect and except operators do not always have the intuitive meaning: in particular, it is not always the case that a node matches A except B if it matches A but does not match B.

For example, consider the pattern para except appendix//para. This expands to root(.)/descendant-or-self::node()/(child::para except child::appendix//para). Since for a given parent node, the results of child::para and child::appendix are disjoint, the right-hand operand of except has no effect.

The effect of matching all paragraphs except those within an appendix can be achieved using the pattern para except //appendix//para; alternatively, use para[not(ancestor::appendix)].

Simpler patterns such as @* except @code generally have the expected effect; the complications arise mainly when non-trivial relative paths are used.

6.8 Modes

[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.

6.8.5 Declaring the Result Type of a Mode

Changes in 4.0  

  1. The result type of a mode can be declared using an as attribute. The result type of all template rules in this mode must be consistent with this, as must the values returned by any built-in template rules for the mode.   [Issues 233 750 1382 PRs 751 1386]

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 Section 3.3.1 Subtypes of Sequence TypesXP.

  • 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 an 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.9 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].

9 Variables and Parameters

[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 3.04.0].]

9.4 Creating Implicit Document Nodes

A document node is created implicitly when evaluating an xsl:variable, xsl:param, or xsl:with-param element that has non-empty content and that has no as attribute. The value of the variable is this newly constructed document node. The content of the document node is formed from the result of evaluating the sequence constructor contained within the variable-binding element, as described in 5.7.1 Constructing Complex Content.

Note:

The construct:

<xsl:variable name="tree">
  <a/>
</xsl:variable>

can be regarded as a shorthand for:

<xsl:variable name="tree" as="document-node()">
  <xsl:document validation="preserve">
    <a/>
  </xsl:document>  
</xsl:variable>

The base URI of the document node is taken from the base URI of the variable binding element in the stylesheet. (See Section 5.2 base-uri Accessor DM30[XDM 4.0] insection [XDM 3.0]7.5.2 base-uri Accessor)

No document-level validation takes place (which means, for example, that there is no checking that ID values are unique). However, type annotations on nodes within the new tree are copied unchanged.

Note:

The base URI of other nodes in the tree is determined by the rules for constructing complex content (see 5.7.1 Constructing Complex Content). The effect of these rules is that the base URI of a node in the temporary tree is determined as if all the nodes in the temporary tree came from a single entity whose URI was the base URI of the variable-binding element. Thus, the base URI of the document node will be equal to the base URI of the variable-binding element, while an xml:base attribute within the temporary tree will change the base URI for its parent element and that element’s descendants, just as it would within a document constructed by parsing.

The document-uri and unparsed-entities properties of the new document node are set to empty.

A temporary tree is available for processing in exactly the same way as any source document. For example, its nodes are accessible using path expressions, and they can be processed using instructions such as xsl:apply-templates and xsl:for-each. Also, the key and id functions can be used to find nodes within a temporary tree, by supplying the document node at the root of the tree as an argument to the function or by making it the context node.

Example: Two-Phase Transformation

The following stylesheet uses a temporary tree as the intermediate result of a two-phase transformation, using different modes for the two phases (see 6.8 Modes). Typically, the template rules in module phase1.xsl will be declared with mode="phase1", while those in module phase2.xsl will be declared with mode="phase2":

<xsl:stylesheet
  version="3.0"
  xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

<xsl:import href="phase1.xsl"/>
<xsl:import href="phase2.xsl"/>

<xsl:variable name="intermediate">
  <xsl:apply-templates select="/" mode="phase1"/>
</xsl:variable>

<xsl:template match="/">
  <xsl:apply-templates select="$intermediate" mode="phase2"/>
</xsl:template>

</xsl:stylesheet>

Note:

The algorithm for matching nodes against template rules is exactly the same regardless which tree the nodes come from. If different template rules are to be used when processing different trees, then unless nodes from different trees can be distinguished by means of patterns, it is a good idea to use modes to ensure that each tree is processed using the appropriate set of template rules.

9.7 Static Expressions

[Definition: A static expression is an XPath expression whose value must be computed during static analysis of the stylesheet.]

Static expressions appear in a number of contexts, in particular:

There are no syntactic constraints on the XPath expression that can be used as a static expression. However, there are severe constraints on the information provided in its evaluation context. These constraints are designed to ensure that the expression can be evaluated at the earliest possible stage of stylesheet processing, without any dependency on information contained in the stylesheet itself or in any source document.

Specifically, the components of the static and dynamic context are defined by the following two tables:

Static Context Components for Static Expressions
ComponentValue
XPath 1.0 compatibility modefalse
Statically known namespacesthe applicable static namespaces for the containing element in the stylesheet
Default namespace for elements and typesdetermined by the xpath-default-namespace attribute if present (see 5.1.2 Unprefixed Lexical QNames in Expressions and Patterns); otherwise absent
Default function namespacethe standard function namespace.
In-scope schema typesThe type definitions that would be available in the absence of any xsl:import-schema declaration
In-scope element declarationsNone
In-scope attribute declarationsNone
In-scope variablesThe static variables visible within the containing package whose declarations occur prior to the element containing the static expression in stylesheet tree order. Stylesheet tree order is the order that results when all xsl:import and xsl:include declarations are replaced by the declarations in the imported or included stylesheet module. A static variable is not in scope within its own declaration, and it is in scope only within its declaring package, not in any using packages. If two static variables satisfying this rule have the same name and are both in scope, the one that appears most recently in stylesheet tree order is used; as a consequence of rules defined elsewhere this will always be consistent with the declaration having highest import precedence.
Context item static typeAbsent
In-scope named item typesNone
Statically known function definitionsThe functions defined in [Functions and Operators 4.0] in the fnmath, map, and array namespaces, together with:
  1. the functions element-available, function-available, type-available, available-system-properties, and system-property defined in this specification;

  2. functions that appear in both this specification and in [Functions and Operators 3.1][xpath-functions-31] (for example, the functions in the map namespaces, and a few others such as collation-key and json-to-xml);

  3. constructor functions for built-in types;

  4. the set of extension functions that are present in the static context of every XPath expression (other than a static expression) within the content of the element that contains the static expression.

Note that stylesheet functions are not included in the context, which means that the function function-available will return false in respect of such functions, and function-lookup will fail to find them. The effect of this rule is to ensure that function-available returns true in respect of functions that can be called within the static expression. It also has the effect that these extension functions will be recognized within the static expression itself; however, the fact that a function is available in this sense gives no guarantee that a call on the function will succeed.
Statically known collationsImplementation-defined
Default collationThe Unicode Codepoint Collation
Static Base URIThe base URI of the containing element in the stylesheet document (see [XDM 4.0] section Section 5.27.5.2 base-uri Accessor DM30)
Statically known documentsImplementation-defined
Statically known collectionsImplementation-defined
Statically known default collection typeImplementation-defined
Statically known decimal formatsA single unnamed decimal format equivalent to the decimal format that is created by an xsl:decimal-format declaration with no attributes.

 

Dynamic Context Components for Static Expressions
ComponentValue
Context item, position, and sizeAbsent
Variable valuesA value for every variable present in the in-scope variables. For static parameters where an external value is supplied: the externally supplied value of the parameter. In all other cases: the value of the variable as defined in 9.3 Values of Variables and Parameters.
Dynamically known function definitionsThe same as the statically known function definitions
Current dateTimeImplementation-defined
Implicit timezoneImplementation-defined
Executable Base URIThe same as the Static Base URI
Default collationThe Unicode Codepoint Collation
Default languageImplementation-defined
Default calendarImplementation-defined
Default placeImplementation-defined
Available documentsImplementation-defined
Available text resourcesImplementation-defined
Available collectionsImplementation-defined
Default collectionImplementation-defined
Available URI collectionsImplementation-defined
Default URI collectionImplementation-defined
Environment variablesImplementation-defined

Within a stylesheet module, all static expressions are evaluated in a single execution scopeFO. This need not be the same execution scope as that used for static expressions in other stylesheet modules, or as that used when evaluating XPath expressions appearing elsewhere in the stylesheet module. This means that a function such as current-date will return the same result when called in different [xsl:]use-when expressions within the same stylesheet module, but will not necessarily return the same result as the same call in an [xsl:]use-when expression within a different stylesheet module, or as a call on the same function executed during the transformation proper.

If a static error is present in a static expression, it is treated in the same way as any other static error in the stylesheet module. If a dynamic error occurs during evaluation of a static expression, it is treated as a static error in the analysis of the stylesheet, while retaining its original error code.

10 Callable Components

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.]

10.3 Stylesheet Functions

Changes in 4.0  

  1. 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]

[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.

10.3.2 Parameters

The xsl:param elements define the formal parameters to the function. In a static function call, these are referenced either positionally or by name. The rules for associating arguments in a static function call with parameter definitions in the function declaration are given in [XPath 4.0] section Section 4.5.1.2 Evaluating Static Function CallsXP.

[ERR XTSE0760] 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".

[ERR XTSE0761] 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".

The as attribute of the xsl:param element defines the required type of the parameter. The rules for converting the values of the actual arguments supplied in the function call to the types required by each xsl:param element, and the errors that can occur, are defined in [XPath 4.0]. The rules that apply are those for the case where XPath 1.0 compatibility mode is set to false.

If the as attribute is omitted, no conversion takes place and any value is accepted.

The default value for an optional parameter (one with required="no") will often be supplied using a simple literal or constant expression, for example <xsl:param name="married" as="xs:boolean" select="false()"/>, or <xsl:param name="options" as="map(*)" select="{}"/>. However, to allow greater flexibility, the default value can also be context-dependent. For example, <xsl:param name="node" as="node()" select="."/> declares a parameter whose default value is the context item from the dynamic context of the caller, while <xsl:param name="collation" as="xs:string" select="default-collation()"/> declares a parameter whose default value is the default collation from the dynamic context of the caller. The detailed rules are as follows. In these rules, the term caller means the function call or function reference that invokes the function being defined.

The static contextXP for the initializing expression of an optional parameter of an xsl:function declaration is the same as the static context for a static expression.

The dynamic contextXP for the initializing expression of an optional parameter is the same as the dynamic context for the evaluation of a static expression, with the following exceptions:

Note:

The effect of these rules is that the select expression for an optional parameter is evaluated in the same way as a static expression, except that it may contain context-dependent subexpressions such as ., position(), last(), static-base-uri(), and default-collation() to access the dynamic context of the caller. It may also contain expressions such as name() or @x = "abc" that have an implicit dependency on the dynamic context of the caller.

10.3.7 Determinism of Functions

Stylesheet functions have been designed to be largely deterministic: unless a stylesheet function calls some extension function which is itself nondeterministic, the function will return results that depend only on the supplied arguments. This property (coupled with the fact that the effect of calling extension functions is entirely implementation-dependent) enables a processor to implement various optimizations, such as removing invariant function calls from the body of a loop, or combining common subexpressions.

One exception to the intrinsic determinism of stylesheet functions arises because constructed nodes have distinct identity. This means that when a function that creates a new node is called, two calls on the function will return nodes that can be distinguished: for example, with such a function, f:make-node() is f:make-node() will return false.

Three classes of functions can be identified:

  1. DeterministicFO functions: as the term is defined in [Functions and Operators 3.1][xpath-functions-31], these offer a guarantee that when a function is called repeatedly with the same arguments, it returns the same results. A classic example is the doc function, which offers the guarantee that doc($X) is doc($X): that is, two calls supplying the same URI return the same node.

  2. Proactive functions: these offer the guarantee that each invocation of the function causes a single execution of the function body, or behaves exactly as if it did so. In particular this means that when the function creates new nodes, it creates new nodes on each invocation. By default, stylesheet functions are proactive.

  3. Elidable functions: these offer no guarantee of determinism, and no guarantee of proactive evaluation. If the function creates new nodes, then two calls on the function with the same arguments may or may not return the same nodes, at the implementation’s discretion. Examples of elidable functions include the [Functions and Operators 3.1][xpath-functions-31] functions analyze-string and json-to-xml.

The new-each-time attribute of xsl:function allows a stylesheet function to be assigned to one of these three categories. The value new-each-time="no" means the function is deterministic; the value new-each-time="yes" means it is proactive; and the value new-each-time="maybe" means it is elidable.

The definition of determinismFO requires a definition of what it means for a function to be called twice with “the same” arguments and to return “the same” result. This is defined in [Functions and Operators 3.1][xpath-functions-31], specifically by the definition of the term identicalFO.

Processors have considerable freedom to optimize execution of stylesheets, and of function calls in particular, but the strategies that are adopted must respect the specification as to whether functions are deterministic, proactive, or elidable. For example, consider a function call that appears within an xsl:for-each instruction, where the supplied arguments to the function do not depend on the context item or on any variables declared within the xsl:for-each instruction. A possible optimization is to execute the function call only once, rather than executing it repeatedly each time round the loop (this is sometimes called loop-lifting). This optimization is safe when the function is deterministic or elidable, but it requires great care if the function is proactive; it is permitted only if the processor is able to determine that the results of stylesheet execution are equivalent to the results that would be obtained if the optimization had not been performed. Declaring a function call to be elidable (by writing new-each-time="maybe") makes it more likely that an implementation will be able to apply this optimization, as well as other optimizations such as caching or memoization.

11 Creating Nodes

This section describes instructions that directly create new nodes.

11.1 Literal Result Elements

[Definition: 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.2 Extension Instructions) is classified as a literal result element.] A literal result element is evaluated to construct a new element node with the same expanded QName (that is, the same namespace URI, local name, and namespace prefix). The result of evaluating a literal result element is a node sequence containing one element, the newly constructed element node.

The content of the element is a sequence constructor (see 5.7 Sequence Constructors). The sequence obtained by evaluating this sequence constructor, after prepending any attribute nodes produced as described in 11.1.2 Attribute Nodes for Literal Result Elements and namespace nodes produced as described in 11.1.3 Namespace Nodes for Literal Result Elements, is used to construct the content of the element, following the rules in 5.7.1 Constructing Complex Content

The base URI of the new element is copied from the base URI of the literal result element in the stylesheet, unless the content of the new element includes an xml:base attribute, in which case the base URI of the new element is the value of that attribute, resolved (if it is a relative URI reference) against the base URI of the literal result element in the stylesheet. (Note, however, that this is only relevant when creating a parentless element. When the literal result element is copied to form a child of an element or document node, the base URI of the new copy is taken from that of its new parent.)

11.1.3 Namespace Nodes for Literal Result Elements

The created element node will have a copy of the namespace nodes that were present on the element node in the stylesheet tree with the exception of any namespace node whose string value is designated as an excluded namespace. Special considerations apply to aliased namespaces: see 11.1.4 Namespace Aliasing.

The following namespaces are designated as excluded namespaces:

  • The XSLT namespace URI (http://www.w3.org/1999/XSL/Transform)

  • A namespace URI declared as an extension namespace (see 24.2 Extension Instructions)

  • A namespace URI designated by using an [xsl:]exclude-result-prefixes attribute either on the literal result element itself or on an ancestor element. The attribute must be in the XSLT namespace only if its parent element is not in the XSLT namespace.

    The value of the attribute is either #all, or a whitespace-separated list of tokens, each of which is either a namespace prefix or #default. The namespace bound to each of the prefixes is designated as an excluded namespace.

    [ERR XTSE0808] 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.

    Note:

    The prefix must be declared in a native namespace binding, not in a fixed namespace binding.

    The default namespace of the parent element of the [xsl:]exclude-result-prefixes attribute (see Section 6.2 Element Nodes [XDM 4.0] DM30section 7.4.2 Element nodes) may be designated as an excluded namespace by including #default in the list of namespace prefixes.

    [ERR XTSE0809] 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.

    The value #all indicates that all namespaces that are in scope for the stylesheet element that is the parent of the [xsl:]exclude-result-prefixes attribute are designated as excluded namespaces.

    The designation of a namespace as an excluded namespace is effective within the subtree of the stylesheet module rooted at the element bearing the [xsl:]exclude-result-prefixes attribute; a subtree rooted at an xsl:stylesheet element does not include any stylesheet modules imported or included by children of that xsl:stylesheet element.

The excluded namespaces, as described above, only affect namespace nodes copied from the stylesheet when processing a literal result element. There is no guarantee that an excluded namespace will not appear on the result tree for some other reason. Namespace nodes are also written to the result tree as part of the process of namespace fixup (see 5.7.3 Namespace Fixup), or as the result of instructions such as xsl:copy and xsl:element.

Note:

When a stylesheet uses a namespace declaration only for the purposes of addressing a source tree, specifying the prefix in the [xsl:]exclude-result-prefixes attribute will avoid superfluous namespace declarations in the serialized result tree. The attribute is also useful to prevent namespaces used solely for the naming of stylesheet functions or extension functions from appearing in the serialized result tree.

In XSLT 4.0, a simpler approach is to declare such namespaces in a fixed-namespaces attribute on the xsl:stylesheet element: see 3.7.1 The fixed-namespaces Attribute. Namespace prefixes declared in that way are not eligible to be used in the names of literal result elements and their attributes, and they are not copied into the result tree.

Example: Excluding Namespaces from the Result Tree

Consider the following stylesheet:

<xsl:stylesheet version="1.0"
  xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
  xmlns:a="a.uri"
  xmlns:b="b.uri"
  exclude-result-prefixes="#all">
  
<xsl:template match="/">
  <foo xmlns:c="c.uri" xmlns:d="d.uri" xmlns:a2="a.uri" 
       xsl:exclude-result-prefixes="c"/>
</xsl:template>

</xsl:stylesheet>

The result of this stylesheet will be:

<foo xmlns:d="d.uri"/>

The namespaces a.uri and b.uri are excluded by virtue of the exclude-result-prefixes attribute on the xsl:stylesheet element, and the namespace c.uri is excluded by virtue of the xsl:exclude-result-prefixes attribute on the foo element. The setting #all does not affect the namespace d.uri because d.uri is not an in-scope namespace for the xsl:stylesheet element. The element in the result tree does not have a namespace node corresponding to xmlns:a2="a.uri" because the effect of exclude-result-prefixes is to designate the namespace URI a.uri as an excluded namespace, irrespective of how many prefixes are bound to this namespace URI.

If the stylesheet is changed so that the literal result element has an attribute b:bar="3", then the element in the result tree will typically have a namespace declaration xmlns:b="b.uri" (the processor may choose a different namespace prefix if this is necessary to avoid conflicts). The exclude-result-prefixes attribute makes b.uri an excluded namespace, so the namespace node is not automatically copied from the stylesheet, but the presence of an attribute whose name is in the namespace b.uri forces the namespace fixup process (see 5.7.3 Namespace Fixup) to introduce a namespace node for this namespace.

A literal result element may have an optional xsl:inherit-namespaces attribute, with the value yes or no. The default value is yes. If the value is set to yes, or is omitted, then the namespace nodes created for the newly constructed element are copied to the children and descendants of the newly constructed element, as described in 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 1.1, xmlns:p="") appearing on the child elements when they are serialized.

11.2 Creating Element Nodes Using xsl:element

<!-- Category: instruction -->
<xsl:element
  name = { qname }
  namespace? = { uri }
  inherit-namespaces? = boolean〔'yes'〕
  use-attribute-sets? = eqnames〔''〕
  type? = eqname
  validation? = "strict" | "lax" | "preserve" | "strip" >
  <!-- Content: sequence-constructor -->
</xsl:element>

The xsl:element instruction allows an element to be created with a computed name. The expanded QName of the element to be created is specified by a requiredname attribute and an optional namespace attribute.

The result of evaluating the xsl:element instruction, in usual circumstances, is the newly constructed element node.

11.2.2 The Name of the Constructed Element Node

The name attribute is interpreted as an attribute value template, whose effective valuemust be a lexical QName.

[ERR XTDE0820] It is a dynamic error if the effective value of the name attribute is not a lexical QName.

[ERR XTDE0830] 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.

Note:

If a fixed-namespaces attribute is present on the containing xsl:stylesheet or xsl:package element, then the prefix must be declared in that attribute, not in a native namespace binding.

If the namespace attribute is not present then the lexical QName is expanded into an expanded QName using the namespace declarations in effect for the xsl:element element, including any default namespace declaration.

If the namespace attribute is present, then it too is interpreted as an attribute value template. The effective valuemust be in the lexical space of the xs:anyURI type. If the string is zero-length, then the expanded QName of the element has a null namespace URI. Otherwise, the string is used as the namespace URI of the expanded QName of the element to be created. The local part of the lexical QName specified by the name attribute is used as the local part of the expanded QName of the element to be created.

[ERR XTDE0835] It is a dynamic error if the effective value of the namespace attribute is not in the lexical space of the xs:anyURI datatype or if it is the string http://www.w3.org/2000/xmlns/.

Note:

The XDM data model requires the name of a node to be an instance of xs:QName, and XML Schema defines the namespace part of an xs:QName to be an instance of xs:anyURI. However, the schema specification, and the specifications that it refers to, give implementations some flexibility in how strictly they enforce these constraints.

The prefix of the lexical QName specified in the name attribute (or the absence of a prefix) is copied to the prefix part of the expanded QName representing the name of the new element node. In the event of a conflict a prefix may subsequently be added, changed, or removed during the namespace fixup process (see 5.7.3 Namespace Fixup). The term conflict here means any violation of the constraints defined in [XDM 3.04.0], for example the use of the same prefix to refer to two different namespaces in the element and in one of its attributes, the use of the prefix xml to refer to a namespace other than the XML namespace, or any use of the prefix xmlns.

11.3 Creating Attribute Nodes Using xsl:attribute

<!-- Category: instruction -->
<xsl:attribute
  name = { qname }
  namespace? = { uri }
  select? = expression
  separator? = { string }
  type? = eqname
  validation? = "strict" | "lax" | "preserve" | "strip" >
  <!-- Content: sequence-constructor -->
</xsl:attribute>

The xsl:attribute element can be used to add attributes to result elements whether created by literal result elements in the stylesheet or by instructions such as xsl:element or xsl:copy. The expanded QName of the attribute to be created is specified by a requiredname attribute and an optional namespace attribute. Except in error cases, the result of evaluating an xsl:attribute instruction is the newly constructed attribute node.

The string value of the new attribute node may be defined either by using the select attribute, or by the sequence constructor that forms the content of the xsl:attribute element. 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 string value of the new attribute node will be a zero-length string. The way in which the value is constructed is specified in 5.7.2 Constructing Simple Content.

[ERR XTSE0840] It is a static error if the select attribute of the xsl:attribute element is present unless the element has empty content.

If the separator attribute is present, then the effective value of this attribute is used to separate adjacent items in the result sequence, as described in 5.7.2 Constructing Simple Content. In the absence of this attribute, the default separator is U+0020 (SPACE) when the content is specified using the select attribute, or a zero-length string when the content is specified using a sequence constructor.

The name attribute is interpreted as an attribute value template, whose effective valuemust be a lexical QName.

[ERR XTDE0850] It is a dynamic error if the effective value of the name attribute is not a lexical QName.

[ERR XTDE0855] 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.

[ERR XTDE0860] 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.

Note:

If a fixed-namespaces attribute is present on the containing xsl:stylesheet or xsl:package element, then the prefix must be declared in that attribute, not in a native namespace binding.

If the namespace attribute is not present, then the lexical QName is expanded into an expanded QName using the namespace declarations in effect for the xsl:attribute element, not including any default namespace declaration.

If the namespace attribute is present, then it too is interpreted as an attribute value template. The effective valuemust be in the lexical space of the xs:anyURI type. If the string is zero-length, then the expanded QName of the attribute has a null namespace URI. Otherwise, the string is used as the namespace URI of the expanded QName of the attribute to be created. The local part of the lexical QName specified by the name attribute is used as the local part of the expanded QName of the attribute to be created.

[ERR XTDE0865] It is a dynamic error if the effective value of the namespace attribute is not in the lexical space of the xs:anyURI datatype or if it is the string http://www.w3.org/2000/xmlns/.

Note:

The same considerations apply as for elements: [see ERR XTDE0835] in 11.2 Creating Element Nodes Using xsl:element.

The prefix of the lexical QName specified in the name attribute (or the absence of a prefix) is copied to the prefix part of the expanded QName representing the name of the new attribute node. In the event of a conflict this prefix may subsequently be added, changed, or removed during the namespace fixup process (see 5.7.3 Namespace Fixup). If the attribute is in a non-null namespace and no prefix is specified, then the namespace fixup process will invent a prefix. The term conflict here means any violation of the constraints defined in [XDM 3.04.0], for example the use of the same prefix to refer to two different namespaces in the element and in one of its attributes, the use of the prefix xml to refer to a namespace other than the XML namespace, or any use of the prefix xmlns.

If the name of a constructed attribute is xml:id, the processor must perform attribute value normalization by effectively applying the normalize-space function to the value of the attribute, and the resulting attribute node must be given the is-id property. This applies whether the attribute is constructed using the xsl:attribute instruction or whether it is constructed using an attribute of a literal result element. This does not imply any constraints on the value of the attribute, or on its uniqueness, and it does not affect the type annotation of the attribute, unless the containing document is validated.

Note:

The effect of setting the is-id property is that the parent element can be located within the containing document by use of the id function. In effect, XSLT when constructing a document performs some of the functions of an xml:id processor, as defined in [xml:id]; the other aspects of xml:id processing are performed during validation.

Example: Creating a List-Valued Attribute

The following instruction creates the attribute colors="red green blue":

<xsl:attribute name="colors" select="'red', 'green', 'blue'"/>

 

Example: Namespaces are not Attributes

It is not an error to write:

<xsl:attribute name="xmlns:xsl" 
   namespace="file://some.namespace"
   select="'http://www.w3.org/1999/XSL/Transform'"/>

However, this will not result in the namespace declaration xmlns:xsl="http://www.w3.org/1999/XSL/Transform" being output. Instead, it will produce an attribute node with local name xsl, and with a system-allocated namespace prefix mapped to the namespace URI file://some.namespace. This is because the namespace fixup process is not allowed to use xmlns as the name of a namespace node.

As described in 5.7.1 Constructing Complex Content, in a sequence that is used to construct the content of an element, any attribute nodes must appear in the sequence before any element, text, comment, or processing instruction nodes. Where the sequence contains two or more attribute nodes with the same expanded QName, the one that comes last is the only one that takes effect.

Note:

If a collection of attributes is generated repeatedly, this can be done conveniently by using named attribute sets: see 10.2 Named Attribute Sets

12 Numbering

<!-- Category: instruction -->
<xsl:number
  value? = expression
  select? = expression
  level? = "single" | "multiple" | "any"〔'single'〕
  count? = pattern
  from? = pattern
  format? = { string }〔'1'〕
  lang? = { language }
  letter-value? = { "alphabetic" | "traditional" }
  ordinal? = { string }〔'no'〕
  start-at? = { string }
  grouping-separator? = { char }
  grouping-size? = { integer } />

The xsl:number instruction is used to create a formatted number. The result of the instruction is a newly constructed text node containing the formatted number as its string value.

[Definition: 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 place marker to be formatted can either be supplied directly, in the value attribute, or it can be computed based on the position of a selected node within the tree that contains it.

[ERR XTSE0975] 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.

Note:

The facilities described in this section are specifically designed to enable the calculation and formatting of section numbers, paragraph numbers, and the like. For formatting of other numeric quantities, the format-number function may be more suitable.

Furthermore, formatting of integers where there is no requirement to calculate the position of a node in the document can now be accomplished using the format-integer function, which borrows many concepts from the xsl:number specification.

12.2 Formatting a Supplied Number

The place marker to be formatted may be specified by an expression. The value attribute contains the expression. The value of this expression is atomized using the procedure defined in [XPath 3.0][xpath-30], and each value $V in the atomized sequence is then converted to the integer value returned by the XPath expression xs:integer(round(number($V))). If the start-at attribute is present, this sequence is then re-based as described in 12.1 The start-at Attribute. The resulting sequence of integers is used as the place marker to be formatted.

If the instruction is processed with XSLT 1.0 behavior, then:

  • All items in the atomized sequence after the first are discarded;

  • If the atomized sequence is empty, it is replaced by a sequence containing the xs:double value NaN as its only item;

  • If any value in the sequence cannot be converted to an integer (this includes the case where the sequence contains a NaN value) then the string NaN is inserted into the formatted result string in its proper position. The error described in the following paragraph does not apply in this case.

[ERR XTDE0980] 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).

Note:

The value zero does not arise when numbering nodes in a source document, but it can arise in other numbering sequences. It is permitted specifically because the rules of the xsl:number instruction are also invoked by functions such as format-time: the minutes and seconds component of a time value can legitimately be zero.

The resulting sequence is formatted as a string using the effective values of the attributes specified in 12.4 Number to String Conversion Attributes; each of these attributes is interpreted as an attribute value template. After conversion, the xsl:number element constructs a new text node containing the resulting string, and returns this node.

Example: Numbering a Sorted List

The following example numbers a sorted list:

<xsl:template match="items">
  <xsl:for-each select="item">
    <xsl:sort select="."/>
    <p>
      <xsl:number value="position()" format="1. "/>
      <xsl:value-of select="."/>
    </p>
  </xsl:for-each>
</xsl:template>

13 Sorting

[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.

13.1 The xsl:sort Element

<xsl:sort
  select? = expression
  lang? = { language }
  order? = { "ascending" | "descending" }〔'ascending'〕
  collation? = { uri }
  stable? = { boolean }〔'yes'〕
  case-order? = { "upper-first" | "lower-first" }
  data-type? = { "text" | "number" | eqname } >
  <!-- Content: sequence-constructor -->
</xsl:sort>

The xsl:sort element defines a sort key component. A sort key component specifies how a sort key value is to be computed for each item in the sequence being sorted, and also how two sort key values are to be compared.

The value of a sort key component is determined either by its select attribute or by the contained sequence constructor. If neither is present, the default is select=".", which has the effect of sorting on the actual value of the item if it is an atomic item, or on the typed-value of the item if it is a node. If a select attribute is present, its value must be an XPath expression.

[ERR XTSE1015] It is a static error if an xsl:sort element with a select attribute has non-empty content.

Those attributes of the xsl:sort elements whose values are attribute value templates are evaluated using the same focus as is used to evaluate the select attribute of the containing instruction (specifically, xsl:apply-templates, xsl:for-each, xsl:for-each-group, or xsl:perform-sort).

The stable attribute is permitted only on the first xsl:sort element within a sort key specification.

[ERR XTSE1017] 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.

[Definition: 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.]

13.1.3 Sorting Using Collations

The rules given in this section apply when comparing values whose type is xs:string or a type derived by restriction from xs:string, or whose type is xs:anyURI or a type derived by restriction from xs:anyURI.

[Definition: 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.] A collation is identified by a URI, but the manner in which this URI is associated with an actual rule or algorithm is largely implementation-defined.

For more information about collations, see [Functions and Operators 4.0] section Section 5.3 Comparison of stringsFO in [Functions and Operators 4.0]. Some specifications, for example [UNICODE TR10], use the term “collation” to describe rules that can be tailored or parameterized for various purposes. In this specification, a collation URI refers to a collation in which all such parameters have already been fixed. Therefore, if a collation URI is specified, other attributes such as case-order and lang are ignored.

Every implementation must recognize the collation URI http://www.w3.org/2005/xpath-functions/collation/codepoint, which provides the ability to compare strings based on the Unicode codepoint values of the characters in the string.

Furthermore, every implementation must recognize collation URIs representing tailorings of the Unicode Collation Algorithm (UCA), as described in 13.4 The Unicode Collation Algorithm. Although this form of collation URI must be recognized, implementations are not required to support every possible tailoring.

If the xsl:sort element has a collation attribute, then the strings are compared according to the rules for the named collation: that is, they are compared using the XPath function call compare($a, $b, $collation).

If the effective value of the collation attribute of xsl:sort is a relative URI, then it is resolved against the base URI of the xsl:sort element.

[ERR XTDE1035] 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.

Note:

It is entirely for the implementation to determine whether it recognizes a particular collation URI. For example, if the implementation allows collation URIs to contain parameters in the query part of the URI, it is the implementation that determines whether a URI containing an unknown or invalid parameter is or is not a recognized collation URI. The fact that this situation is described as an error thus does not prevent an implementation applying a fallback collation if it chooses to do so.

The lang and case-order attributes are ignored if a collation attribute is present. But in the absence of a collation attribute, these attributes provide input to an implementation-defined algorithm to locate a suitable collation:

  • The lang attribute indicates that a collation suitable for a particular natural language should be used. The effective value of the attribute must either be a string in the value space of xs:language, or a zero-length string. Supplying the zero-length string has the same effect as omitting the attribute. If a language is requested that is not supported, the processor may use a fallback language identified by removing successive hyphen-separated suffixes from the supplied value until a supported language code is obtained; failing this, the processor behaves as if the lang attribute were omitted.

    Note:

    The fallback algorithm described above is identical to the rules in RFC4647 Basic Filtering used in BCP 47, and is specified in [RFC4647] in greater detail.

  • The case-order attribute indicates whether the desired collation should sort upper-case letters before lower-case or vice versa. The effective value of the attribute must be either lower-first (indicating that lower-case letters precede upper-case letters in the collating sequence) or upper-first (indicating that upper-case letters precede lower-case).

    When lower-first is requested, the returned collation should have the property that when two strings differ only in the case of one or more characters, then a string in which the first differing character is lower-case should precede a string in which the corresponding character is title-case, which should in turn precede a string in which the corresponding character is upper-case. When upper-first is requested, the returned collation should have the property that when two strings differ only in the case of one or more characters, then a string in which the first differing character is upper-case should precede a string in which the corresponding character is title-case, which should in turn precede a string in which the corresponding character is lower-case.

    So, for example, if lang="en", then A a B b are sorted with case-order="upper-first" and a A b B are sorted with case-order="lower-first".

    As a further example, if lower-first is requested, then a sorted sequence might be “MacAndrew, macintosh, macIntosh, Macintosh, MacIntosh, macintoshes, Macintoshes, McIntosh”. If upper-first is requested, the same sequence would sort as “MacAndrew, MacIntosh, Macintosh, macIntosh, macintosh, MacIntoshes, macintoshes, McIntosh”.

If none of the collation, lang, or case-order attributes is present, the collation is chosen in an implementation-defined way. It is not required that the default collation for sorting should be the same as the default collation used when evaluating XPath expressions, as described in 5.3.1 Initializing the Static Context and 3.7.2 The default-collation Attribute.

Note:

It is usually appropriate, when sorting, to use a strong collation, that is, one that takes account of secondary differences (accents) and tertiary differences (case) between strings that are otherwise equal. A weak collation, which ignores such differences, may be more suitable when comparing strings for equality.

Useful background information on international sorting is provided in [UNICODE TR10]. The case-order attribute may be interpreted as described in section 6.6 of [UNICODE TR10].

The collation, case-order, and lang attributes are ignored when no string comparisons are performed during the sorting process; this includes the cases where (a) the sequences to be sorted are empty, (b) the sort keys are of a non-string type such as xs:integer, or (c) data-type="number" is specified. In these cases, an implementation may raise errors in the value of these attributes, but is not required to do so. As always, an implementation may issue warnings. [XSLT 3.0 Erratum E45, bug 30386]

15 Merging

Changes in 4.0  

  1. Composite merge keys are now allowed.   [Issue 1684 PR 1689 9 January 2025]

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.

Example: Merging All the Files in a Collection

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).

 

Example: Merging Two Heterogeneous Files

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.

15.1 Terminology for Merging

[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 sequenceDM30DM 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 an 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.]

16 Splitting

Sometimes it is convenient to be able to compute multiple results during a single scan of the input data. For example, a transformation may wish to rename selected elements, and also to output a count of how many elements have been renamed. Traditionally in a functional language this means computing two separate functions of the input sequence, which (in the absence of sophisticated optimization) will result in the input being scanned twice. This is inconsistent with streaming, where the input is only available to be scanned once, and it can also lead to poor performance in non-streaming applications.

To meet this requirement, XSLT 3.0 introduces the instruction xsl:fork. The content of this instruction is a restricted form of sequence constructor, and in a formal sense the effect of the instruction is simply to return the result of evaluating the sequence constructor. However, the presence of the instruction affects the analysis of streamability (see 19 Streamability). In particular, when xsl:fork is used in a context where streaming is required, each independent instruction within the sequence constructor must be streamable, but the analysis assumes that these instructions can all be evaluated during a single pass of the streamed input document.

Note:

The semantics of the instruction require a number of result sequences to be computed during a single pass of the input. A processor may interpret this as a request to use multiple threads. However, implementations using a single thread are feasible, and this instruction is not intended primarily as a means for stylesheet authors to express their intentions with regard to multi-threaded execution.

Note:

Because multiple results are computed during a single pass of the input, and then concatenated into a single sequence, this instruction will generally involve some buffering of results. The amount of memory used should not exceed that needed to hold the results of the instruction. However, within this principle, implementations may adopt a variety of strategies for evaluation; for example, there may be cases where buffering of the input is more efficient than buffering of output.

Generally, stylesheet authors indicate that buffering of input is the preferred strategy by using the copy-of or snapshot functions, and indicate that buffering of output is preferred by using xsl:fork. However, conformant processors are not constrained in their choice of evaluation strategies.

The content model of the xsl:fork instruction (given that an XSLT 3.0 processor ignores xsl:fallback) takes two possible forms:

  1. A sequence of xsl:sequence instructions

  2. A single xsl:for-each-group instruction. This will normally use the group-by attribute, because in all other cases the containing xsl:fork instruction has no useful effect.

The first form is appropriate when splitting a single input stream into a fixed number of output streams, known statically: for example, one output stream for credit transactions, a second for debit transactions. The second form is appropriate when the number of output streams depends on the data: for example, one output stream for each distinct city name found in the input data.

The following section describes the xsl:fork instruction more formally.

16.2 Examples of Splitting with Streamed Data

This section gives examples of how splitting using xsl:fork can be used to enable streaming of input documents in cases where several results need to be computed during a single pass over the input data.

Example: Splitting a Transaction File into Credits and Debits

Consider a transaction file that contains a sequence of debits and credits:

<transactions>
  <transaction value="5.60"/>
  <transaction value="11.20"/>
  <transaction value="-3.40"/>
  <transaction value="8.90"/>
  <transaction value="-1.99"/>
</transactions>

where the requirement is to split this into two separate files containing credits and debits respectively.

This can be achieved in guaranteed-streamable code as follows:

<xsl:source-document streamable="yes" href="transactions.xml">
  <xsl:fork>
    <xsl:sequence>
      <xsl:result-document href="credits.xml">
        <credits>
          <xsl:for-each select="transactions/transaction[@value &gt;= 0]">
            <xsl:copy-of select="."/>
          </xsl:for-each>
        </credits>
      </xsl:result-document>
    </xsl:sequence>
    <xsl:sequence>
      <xsl:result-document href="debits.xml">
        <debits>
          <xsl:for-each select="transactions/transaction[@value &lt; 0]">
            <xsl:copy-of select="."/>
          </xsl:for-each>
        </debits>
      </xsl:result-document>
    </xsl:sequence>  
  </xsl:fork>
</xsl:source-document>

In the absence of the xsl:fork instruction, this would not be streamable, because the sequence constructor includes two consuming instructions. With the addition of the xsl:fork instruction, however, each xsl:result-document instruction is allowed to make a downwards selection.

One possible implementation model for this is as follows: a single thread reads the source document, and sends parsing events such as start-element and end-element to two other threads, each of which is writing one of the two result documents. Each of these implements the downwards-selecting path expression using a process that waits until the next transaction start-element event is received; when this event is received, the process examines the @value attribute to determine whether or not this transaction is to be copied; if it is, then all events until the matching transaction end-element event are copied to the serializer for the result document; otherwise, these events are discarded.

 

Example: Splitting a Transaction File by Customer Account

Consider a transaction file that contains a sequence of debits and credits:

<transactions>
  <transaction value="5.60" account="01826370"/>
  <transaction value="11.20" account="92741838"/>
  <transaction value="-3.40" account="01826370"/>
  <transaction value="8.90" account="92741838"/>
  <transaction value="-1.99" account="43861562"/>
</transactions>

where the requirement is to split this into a number of separate files, one for each account number found in the input.

This can be achieved in guaranteed-streamable code as follows:

<xsl:source-document streamable="yes" href="transactions.xml">
  <xsl:fork>
    <xsl:for-each-group select="transactions/transaction" group-by="@account">
      <xsl:result-document href="account{current-grouping-key()}.xml">
        <transactions account="{current-grouping-key()}">
          <xsl:copy-of select="current-group()"/>
        </transactions>
      </xsl:result-document>
    </xsl:for-each-group>
  </xsl:fork>
</xsl:source-document>

In the absence of the xsl:fork instruction, this would not be streamable, because in the general case the output of xsl:for-each-group with a group-by attribute needs to be buffered. (The streamability rules do not recognize an xsl:for-each-group whose body comprises an xsl:result-document instruction as a special case.) With the addition of the xsl:fork instruction, however, the code becomes guaranteed streamable.

One possible implementation model for this is as follows: the processor opens a new serializer each time a new account number is encountered in the input, and writes the <transactions> start tag to the serializer. When a transaction element is encountered in the input, it is copied to the relevant serializer, according to the value of the account attribute. At the end of the input, a <transactions> end tag is written to each of the serializers, and each output file is closed.

In the more general case, where the body of the xsl:for-each-group instruction contributes output to the principal result document, the output generated by processing each group needs to be buffered in memory. The requirement to use xsl:fork exists so that this use of (potentially unbounded) memory has to be a conscious decision by the stylesheet author.

 

Example: Arithmetic using Multiple Child Elements as Operands

The rules for streamability do not allow two instructions in a sequence constructor to both read child or descendant elements of the context node, which makes it tricky to perform a calculation in which multiple child elements act as operands. This restriction can be avoided by using xsl:fork, as shown below, where each of the two branches of the xsl:fork instruction selects children of the context node.

<xsl:template match="order" mode="a-streamable-mode">                  
  <xsl:variable name="price-and-discount" as="xs:decimal+">
    <xsl:fork>
      <xsl:sequence select="xs:decimal(price)"/>
      <xsl:sequence select="xs:decimal(discount)"/>
    </xsl:fork>
  </xsl:variable>
  <xsl:value-of select="$price-and-discount[1] - $price-and-discount[2]"/>
  </xsl:template>

A possible implementation strategy here is for events from the XML parser to be sent to two separate agents (perhaps but not necessarily running in different threads), one of which computes xs:decimal(price) and the other xs:decimal(discount); on completion the results computed by the two agents are appended to the sequence that forms the value of the variable.

With this strategy, the processor would require sufficient memory to hold the results of evaluating each branch of the fork. If these results (unlike this example) are large, this could defeat the purpose of streaming by requiring large amounts of memory; nevertheless, this code is treated as streamable.

Note:

An alternative solution to this requirement is to use map constructors: see [XPath 4.0] section Section 4.13.1.1 Map ConstructorsXP.

 

Example: Deleting Elements, and Counting Deletions

In this example the input is a narrative document containing note elements at any level of nesting. The requirement is to output a copy of the input document in which (a) the note elements have been removed, and (b) a footnote is added at the end indicating how many note elements have been deleted.

<xsl:mode on-no-match="shallow-copy" streamable="yes"/>

<xsl:template match="note"/>

<xsl:template match="/*">
  <xsl:fork>
    <xsl:sequence>
      <xsl:apply-templates/>
    </xsl:sequence>
    <xsl:sequence>
      <footnote>
        <p>Removed <xsl:value-of select="count(.//note)"/> 
                 note elements.</p>
      </footnote>
    </xsl:sequence>  
  </xsl:fork>
</xsl:template>

The xsl:fork instruction contains two independent branches. These can therefore be evaluated in the same pass over the input data. The first branch (the xsl:apply-templates instruction) causes everything except the note elements to be copied to the result; the second instruction (the literal result element footnote) outputs a count of the number of descendant note elements.

Note that although the processing makes a single pass over the input stream, there is some buffering of results required, because the results of the instructions within the xsl:fork instruction need to be concatenated. In this case an intelligent implementation might be able to restrict the buffered data to a single integer.

In a formal sense, however, the result is exactly the same as if the xsl:fork element were not there.

An alternative way of solving this example problem would be to count the number of note elements using an accumulator: see 18.2 Accumulators.

17 Regular Expressions

The function library for XPath 3.0 defines several functions that make use of regular expressions:

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 two constructs are not precisely equivalent; for example, xsl:analyze-string allows a regular expression that matches a zero-length string while the analyze-string function does not. The xsl:analyze-string instruction (via the use of regex-group) provides information about the value of captured substrings; the analyze-string function additionally provides information about the position of the captured substrings within the original string.

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 Section 6.1 Regular expression syntaxFO), which is itself based on the syntax defined in [XML Schema Part 2].

17.1 The xsl:analyze-string Instruction

Changes in 4.0  

  1. 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]

  2. The rules have been adjusted to allow for new capabilities in regular expressions, such as zero-width assertions.   [ PR 1856]

<!-- 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) and a regular expression (the effective value of the regex attribute).

If the result of evaluating the select expression is an 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 Section 6.2 FlagsFO).

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.

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:

  1. A single xsl:matching-substring instruction, followed by zero or more xsl:fallback instructions

  2. A single xsl:non-matching-substring instruction, followed by zero or more xsl:fallback instructions

  3. 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 XSLT 2.0 or 3.0 processor, 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.

Conceptually, the processor uses the fn:analyze-string instruction to construct an fn:analyze-string-result element containing a sequence of fn:match and fn:non-match children. It then processes this sequence of children: for each fn:match child, it evaluates the xsl:matching-substring element, and for each fn:non-match child, it evaluates the xsl:non-matching-substring element.

Each of these elements has either a select attribute or a contained sequence constructor. If the element is absent, the effect is the same as if it were present with empty content. In processing each matching or non-matching segmentFO, the string-value of the segment will be the context item (as a value of type xs:string); the position of the segment within the sequence of matching and non-matching segments will be the context position; and the number of matching and non-matching segments will be the context size.

18 Streaming

XSLT 3.0 introduces a number of constructs that are specifically designed to enable streamed applications to be written, but which are also useful in their own right; it also includes some features that are very specialized to streaming.

18.1 The xsl:source-document Instruction

<!-- Category: instruction -->
<xsl:source-document
  href = { uri }
  streamable? = boolean〔'no'〕
  use-accumulators? = tokens〔''〕
  validation? = "strict" | "lax" | "preserve" | "strip"
  type? = eqname >
  <!-- Content: sequence-constructor -->
</xsl:source-document>

The xsl:source-document instruction reads a source document whose URI is supplied, and processes the content of the document by evaluating the contained sequence constructor. The streamable attribute (default "no") allows streamed processing to be requested.

For example, if a document represents a book holding a sequence of chapters, then the following code can be used to split the book into multiple XML files, one per chapter, without allocating memory to hold the entire book in memory at one time:

<xsl:source-document streamable="yes" href="book.xml">
  <xsl:for-each select="book">             
    <xsl:for-each select="chapter">
      <xsl:result-document href="chapter{position()}.xml">
        <xsl:copy-of select="."/>
      </xsl:result-document>
    </xsl:for-each>
  </xsl:for-each>  
</xsl:source-document>

Note:

In earlier drafts of this specification the xsl:source-document element was named xsl:stream. The instruction has been generalised to handle both streamed and unstreamed input.

The document to be read is determined by the effective value of the href attribute (which is defined as an attribute value template). This must be a valid URI reference. If it is an absolute URI reference, it is used as is; if it is a relative URI reference, it is made absolute by resolving it against the base URI of the xsl:source-document element. The process of obtaining a document node given a URI is the same as for the doc function. However, unlike the doc function, the xsl:source-document instruction offers no guarantee that the resulting document will be stable (that is, that multiple calls specifying the same URI will return the same document).

Specifically, if an xsl:source-document instruction is evaluated several times (or if different xsl:source-document instructions are evaluated) with the same URI (after making it absolute) as the value of the href attribute, it is implementation-dependent whether the same nodes or different nodes are returned on each occasion; it is also possible that the actual document content will be different.

Note:

A different node will necessarily be returned if there are differences in attributes such as validation, type, streamable, or use-accumulators, or if the calls are in different packages with variations in the rules for whitespace stripping or stripping of type annotations.

The result of the xsl:source-document instruction is the same as the result of the following (non-streaming) process:

  1. The source document is read from the supplied URI and parsed to form a tree of nodes in the XDM data model.

  2. The contained sequence constructor is evaluated with the root node of this tree as the context item, and with the context position and context size set to one; and the resulting sequence is returned as the result of the xsl:source-document instruction.

The xsl:source-document instruction is guaranteed-streamable if both the following conditions are satisfied:

  1. It is declared-streamable, by specifying streamable="yes".

  2. the contained sequence constructor is grounded, as assessed using the streamability analysis in 19 Streamability. The consequences of being or not being guaranteed streamable depend on the processor conformance level, and are explained in 19.10 Streamability Guarantees.

The use-accumulators attribute defines the set of accumulators that are applicable to the document, as explained in 18.2.2 Applicability of Accumulators.

Note:

The following notes apply specifically to streamed processing.

The rules for guaranteed streamability ensure that the sequence constructor (and therefore the xsl:source-document instruction) cannot return any nodes from the streamed document. For example, it cannot contain the instruction <xsl:sequence select="//chapter"/>. If nodes from this document are to be returned, they must first be copied, for example by using the xsl:copy-of instruction or by calling the copy-of or snapshot functions.

Because the xsl:source-document instruction cannot (if it satisfies the rules for guaranteed streamability) return nodes from the streamed document, any nodes it does return will be conventional (unstreamed) nodes that can be processed without restriction. For example, if xsl:source-document is invoked within a stylesheet functionf:firstChapter, and the sequence constructor consists of the instruction <xsl:copy-of select="//chapter"/>, then the calling code can manipulate the resulting chapter elements as ordinary trees rooted at parentless element nodes.

If the sequence constructor in an xsl:source-document instruction were to return nodes from the document for which streaming has been requested, the instruction would not be guaranteed streamable. Processors which support the streaming feature would then not be required to process it in a streaming manner, and this specification imposes no restrictions on the processing of the nodes returned. (The ability of a streaming processor to handle such stylesheets in a streaming manner might, of course, depend on how the nodes returned are processed, but those details are out of scope for this specification.)

18.1.3 fn:stream-available

Summary

Determines, as far as possible, whether a document is available for streamed processing using xsl:source-document.

Signature
fn:stream-available(
$urias xs:string?
) as xs:boolean
Properties

This function is nondeterministicFO, context-dependentFO, and focus-independentFO. It depends on available documents.

Rules

The intent of the stream-available function is to allow a stylesheet author to determine, before calling xsl:source-document with streamable="yes" and with a particular URI as the value of its href attribute, whether a document is available at that location for streamed processing.

If the $uri argument is an empty sequence then the function returns false.

If the function returns true then the caller can conclude that the following conditions are true:

  1. The supplied URI is valid;

  2. A resource can be retrieved at that URI;

  3. An XML representation of the resource can be delivered, which is well-formed at least to the extent that some initial sequence of octets can be decoded into characters and matched against the production:

    prolog (EmptyElemTag | STag )

    as defined in the XML 1.0 or XML 1.1 Recommendation.

    Note:

    That is, the XML is well-formed at least as far as the end of the first element start tag; to establish this, a parser will typically retrieve any external entities referenced in the Doctype declaration or DTD.

If the function returns false, the caller can conclude that either one of the above conditions is not satisfied, or the processor detected some other condition that would prevent a call on xsl:source-document with streamable="yes" executing successfully.

Like xsl:source-document itself, the function is not deterministic, which means that multiple calls during the execution of a stylesheet will not necessarily return the same result. The caller cannot make any inferences about the point in time at which the input conditions for stream-available are present, and in particular there is no guarantee that because stream-available returns true, xsl:source-document will necessarily succeed.

The value of the $uri argument must be a URI in the form of a string. If it is a relative URI, it is resolved relative to the static base URI of the function call.

Error Conditions

If the URI is invalid, such that a call on doc-available would raise an error, then stream-available raises the same error: [ERR FODC0005] FO30FO40.

19 Streamability

This section contains rules that can be used to determine properties of constructs in the stylesheet — specifically, the posture and sweep of a construct — which enable the streamability of the stylesheet to be assessed.

These properties are used to determine the streamability of:

In each case, the conditions for constructs to be guaranteed-streamable are defined in terms of these properties. The result of this analysis in turn (see 19.10 Streamability Guarantees) imposes rules on how the constructs are handled by processors that implement the streaming feature. The analysis has no effect on the behavior of processors that do not implement this feature.

The analysis is relevant to constructs such as streamable template rules and the xsl:source-document instruction that process a single streamed input document. The xsl:merge instruction, which processes multiple streamed inputs, has its own rules.

The rules in this section operate on the expression tree (more properly, construct tree) that is typically output by the XSLT and XPath parser. For the most part, the rules depend only on identifying the syntactic constructs that are present.

The rules in this section generally consider each component in the stylesheet (and in the case of template rules, each template rule) in isolation. The exception is that where a component contains references to other components (such as global variables, functions, or named templates), then information from the signature of the referenced component is sometimes used. This is invariably information that cannot be changed if a component is overridden in a different package. The analysis thus requires as a pre-condition that function calls and calls on named templates have been resolved to the extent that the corresponding function/template signature is known.

The detailed way in which the construct tree is derived from the lexical form of the stylesheet is not described in this specification. There are many ways in which the tree can be optimized without affecting the result of the rules in this section: for example, a sequence constructor containing a single instruction can be replaced by that instruction, and a parenthesized expression can be replaced by its content.

[Definition: The term construct refers to the union of the following: a sequence constructor, an instruction, an attribute set, a value template, an expression, or a pattern.]

These constructs are classified into construct kinds: in particular, instructions are classified according to the name of the XSLT instruction, and expressions are classified according to the most specific production in the XPath grammar that the expression satisfies. (This means, for example, that 2+2 is classified as an AdditiveExpr, rather than say as a UnionExpr; although it also satisfies the production rule for UnionExpr, AdditiveExpr is more specific.)

[Definition: For every construct kind, there is a set of zero or more operand roles.] For example, an AdditiveExpr has two operand roles, referred to as the left-hand operand and the right-hand operand, while an IfExpr has three, referred to as the condition, the then-clause, and the else-clause. A function call with three arguments has three operand roles, called the first, second, and third arguments. The names of the operand roles for each construct kind are not formally listed, but should be clear from the context.

[Definition: In an actual instance of a construct, there will be a number of operands. Each operand is itself a construct; the construct tree can be defined as the transitive relation between constructs and their operands.] Each operand is associated with exactly one of the operand roles for the construct type. There may be operand roles where the operand is optional (for example, the separator attribute of the xsl:value-of instruction), and there may be operand roles that can be occupied by multiple operands (for example, the xsl:when/@test condition in xsl:choose, or the arguments of the concat function).

Operand roles have a number of properties used in the analysis:

Note:

There is one known case where this definition makes an operand higher-order even though it is only evaluated once: specifically, the sequence constructor contained in the body of an xsl:copy instruction that has a select attribute. See 19.8.4.12 Streamability of xsl:copy for further details.

[Definition: For some construct kinds, one or more operand roles may be defined to form a choice operand group. This concept is used where it is known that operands are mutually exclusive (for example the then and else clauses in a conditional expression).]

[Definition: The combined posture of a choice operand group is determined by the postures of the operands in the group (the operand postures), and is the first of the following that applies:

  1. If any of the operand postures is roaming, then the combined posture is roaming.

  2. If all of the operand postures are grounded, then the combined posture is grounded.

  3. If one or more of the operand postures is climbing and the remainder (if any) are grounded, then the combined posture is climbing.

  4. If one or more of the operand postures is striding and the remainder (if any) are grounded, then the combined posture is striding.

  5. If one or more of the operand postures is crawling and each of the remainder (if any) is either striding or grounded, then the combined posture is crawling.

  6. Otherwise (for example, if the group includes both an operand with climbing posture and one with crawling posture), the combined posture is roaming.

]

[Definition: The type-determined usage of an operand is as follows: if the required type (ignoring occurrence indicator) is fn(*) or a subtype thereof, then inspection; if the required type (ignoring occurrence indicator) is an atomic or union type, then absorption; otherwise navigation.]

[Definition: The type-adjusted posture and sweep of a construct C, with respect to a type T, are the posture and sweep established by applying the general streamability rules to a construct D whose single operand is the construct C, where the operand usage of C in D is the type-determined usage based on the required type T.]

Note:

In effect, the type-adjusted posture and sweep are the posture and sweep of the implicit expression formed to apply the coercion rules to the argument of a function or template call, or to the result of a function or template, given knowledge of the required type. For example, an expression such as discount in the function call abs(discount), which would otherwise be striding and consuming, becomes grounded and consuming because of the implicit atomization triggered by the coercion rules.

The process of determining whether a construct is streamable reduces to determining properties of the constructs in the construct tree. The properties in question (which are described in greater detail in subsequent sections) are:

  1. The static type of the construct. When the construct is evaluated, its value will always be an instance of this type. The value is a U-type; although type inferencing is capable of determining information about the cardinality as well as the item type, the streamability analysis makes no use of this.

  2. The context item type: that is, the static type of the context item potentially used as input to the construct. When the construct is evaluated, the context item used to evaluate the construct (if it is used at all) will be an instance of this type.

  3. [Definition: The posture of the expression. This captures information about the way in which the streamed input document is positioned on return from evaluating the construct. The posture takes one of the values climbing, striding, crawling, roaming, or grounded.] The meanings of these terms are explained in 19.4 Determining the Posture of a Construct.

  4. [Definition: The context posture. This captures information about how the context item used as input to the construct is positioned relative to the streamed input. The context posture of a construct C is the posture of the expression whose value sets the focus for the evaluation of C.] Rules for determining the context posture of any construct are given in 19.5 Determining the Context Posture.

  5. The sweep of the construct. The sweep of a construct gives information about whether and how the evaluation of the construct changes the current position in a streamed input document. The possible values are motionless, consuming, and free-ranging. These terms are explained in 19.6 The Sweep of a Construct.

The values of these properties for a top-level construct such as the body of a template rule determine whether the construct is streamable.

The values of these properties are not independent. For example, if the static type is atomic, then the posture will always be grounded; if the sweep is free-ranging, then the posture will always be roaming.

The posture and sweep of a construct, as defined above, are calculated in relation to a particular streamed input document. If there is more than one streamed input document, then a construct that is motionless with respect to one streamed input might be consuming with respect to another. In practice, though, the streamability analysis is only ever concerned with one particular streamed input at a time; constructs are analyzed in relation to the innermost containing xsl:template, xsl:source-document, xsl:accumulator, or xsl:merge-source element, and this container implicitly defines the streamed input document that is relevant. The streamed input document affecting a construct is always the document that contains the context item for evaluation of that construct.

19.1 Determining the Static Type of a Construct

Changes in 4.0  

  1. The static typing rules have been updated to take account of new constructs in XPath 4.0.   [Issue 675 PR 2011 18 May 2025]

[Definition: The static type of a construct is such that all values produced by evaluating the construct will conform to that type. The static type of a construct comprises a U-type and a cardinality. A cardinality is a range of integers (from min to max).]

[Definition: A U-type is a set of fundamental item types.]

[Definition: There are 28 fundamental item types: the 7 node kinds defined in [XDM 3.04.0] (element, attribute, etc.), the 19 primitive atomic types defined in [XML Schema Part 2], plus the types fn(*) and xs:untypedAtomic. The fundamental item types are disjoint, and every item is an instance of exactly one of them.]

More specifically, the fundamental item types are:

  • document-node(), element(), attribute(), text(), comment(), processing-instruction(), namespace-node();

  • xs:boolean, xs:double, xs:decimal, xs:float, xs:string, xs:dateTime, xs:date, xs:time, xs:gYear, xs:gYearMonth, xs:gMonth, xs:gMonthDay, xs:gDay, xs:anyURI, xs:QName, xs:NOTATION, xs:base64Binary, xs:hexBinary, xs:duration

  • fn(*)

  • xs:untypedAtomic

A value V (in general, a sequence) is an instance of a U-typeU if every item in V is an instance of one of the fundamental item types in U. For example, the sequence (23, "Paris") is an instance of the U-type U{xs:string, xs:decimal, xs:date} because both items in the sequence belong to item types in this U-type.

Note:

It is a consequence of this rule that the empty sequence, (), is an instance of every U-type.

A U-type is represented in this specification using the notation U{t1, t2, t3, ...} where t1, t2, t3, ... are the names of the fundamental item types making up the U-type. The item types are represented using the syntax of the ItemTypeXP production in XPath, for example comment() or xs:date.

Note:

This means that the order of t1, t2, t3, ... has no significance: U{A, B} is the same U-type as U{B, A}.

The smallest U-type is denoted U{}. This is not an empty type; like every other U-type, it has the empty sequence () as an instance. For convenience, the universal U-type is represented as U{*}; the U-type corresponding to the set of 7 node kinds is written U{N}, and the U-type corresponding to all atomic items (that is, the 19 primitive atomic types plus xs:untypedAtomic) is written U{A}.

Because a U-type is a set, the operations of union, intersection, and difference are defined over U-types, and the result is always a U-type. If one U-type U is a subset of another U-type V, then U is said to be a subtype of V, and V is said to be a supertype of U.

In some cases the inference of a static type depends on the declared types of variables or functions. Since declared types use the SequenceType syntax, there is therefore a mapping defined from SequenceTypes to U-types. The mapping is as follows:

  • The SequenceTypeempty-sequence() maps to U{}

  • For every other SequenceType, the mapping depends only on the item type and ignores the occurrence indicator. The mapping from item types is as follows:

    • item() maps to U{*}

    • A choice item type (A | B | C) maps to the union of the U-types corresponding to A, B, and C.

    • AnyKindTest (node()) maps to U{N}

    • DocumentTest maps to U{document-node()}

    • ElementTest and SchemaElementTest map to U{element()}

    • AttributeTest and SchemaAttributeTest map to U{attribute()}

    • TextTest maps to U{text()}

    • CommentTest maps to U{comment()}

    • PITest maps to U{processing-instruction()}

    • NamespaceNodeTest maps to U{namespace-node()}

    • FunctionType, MapType, and ArrayType and RecordType map to U{fn(*)}

    • The QName xs:error maps to U{}

    • A QName Q representing an atomic type that is a fundamental item type maps to U{Q}

    • A QName Q representing an atomic type derived from a fundamental item type F maps to U{F}

    • A QName Q representing a pure union type maps to a U-type containing the fundamental item types present in the transitive membership of the union, or from which the transitive members of the union are derived.

Although all constructs have a static type, the streamability analysis only needs to know the static type of XPath expressions, so the rules here are largely confined to that case. For patterns, the static type is deemed to be U{xs:boolean}, reflecting the fact that a pattern is essentially a function that can be applied to items to deliver a true or false (matching or non-matching) result. For constructs other than expressions and patterns, the static type for the purpose of streamability analysis is taken as U{*}.

The rules given here are deliberately simple. Implementations may well be able to compute a more precise static type, but this will rarely be useful for streamability analysis. The item type for each kind of XPath expression is determined by the rules below. The columns are interpreted as follows:

  • The name in the first column is the name of a production in the XPath grammar.

  • In the second column, the Proforma uses an informal notation used both to provide a reminder of the syntax of the construct in question, and to attach labels to its operand roles so that they can be referred to in the text of the third column.

  • The third column gives the static type of the expression, either as a U-type, or as a formula for computing the U-type. In these formulae, T(E) means the U-type of expression E, U1|U2 means the union of U-types U1 and U2, and U1 intersect U2 means the intersection of U-types U1 and U2.

  • The fourth column gives the cardinality of the result, either as an explicit range, or as a formula. For example (0, 1) indicates a cardinality range from zero to one inclusive. N represents unbounded cardinality. The notation C(E) represents the cardinality of expression E.

    The sum of two cardinalities C + D is the range (Cmin+Dmin, Cmax+Dmax).

    The product of two cardinalities C * D is the range (Cmin*Dmin, Cmax*Dmax).

    The maximum of two cardinalities max(C, D) is the range (min(Cmin, Dmin), max(Cmax, Dmax)).

Inferring a Static Type for XPath 3.0 Expressions
ConstructProformaStatic Item TypeCardinality
ExprE,FT(E) | T(F)C(E) + C(F)
ForExprfor $x in S return ET(E)C(S) * C(E)
LetExprlet $x := S return ET(E)C(E)
QuantifiedExprsome|every $x in S satisfies CU{xs:boolean}(1,1)
IfExprif (C) then A else BT(A) | T(B)max(C(A), C(B))
if (C) { A }T(A)max(C(A), (0,0))
OtherwiseExprA otherwise BT(A) | T(B)max(C(A), C(B))
OrExprE or FU{xs:boolean}(1,1)
AndExprE and FU{xs:boolean}(1,1)
ComparisonExprE = F; E eq F; E is FU{xs:boolean}(0,1)
StringConcatExprE || FU{xs:string}(1,1)
RangeExprE to FU{xs:decimal}(0,N)
AdditiveExprE + FU{A}. But if the expression is a predicate (that is, if it appears between square brackets in a filter expression or axis step), then U{xs:decimal, xs:double, xs:float}(0,1)
MultiplicativeExprE * FU{A}. But if the expression is a predicate (that is, if it appears between square brackets in a filter expression or axis step), then U{xs:decimal, xs:double, xs:float}(0,1)
UnionExprA | BT(A) | T(B)C(A) + C(B)
IntersectExceptExprA intersect BT(A) intersect T(B)C(A) * (0,1)
E except FT(A)C(A) * (0,1)
InstanceOfExprE instance of TU{xs:boolean}(1,1)
TreatExprE treat as TThe U-type corresponding to the SequenceType TThe cardinality of the SequenceType T
CastableExprE castable as TU{xs:boolean}(1,1)
CastExprE cast as Tif T is an atomic or pure union type, the corresponding U-type. Otherwise, for example if T is a list type, U{A}.if T is an atomic or pure union type, (0,1). Otherwise, for example if T is a list type, (0,N).
UnaryExpr-NU{xs:decimal, xs:double, xs:float}C(N)
SimpleMapExprA ! BT(B)C(A) * C(B)
PathExpr/U{document-node()}(1,1)
/PT(P)(0,N)
//PT(P)(0,N)
RelativePathExprP/Q; P//QT(Q)(0,N)
AxisStepE[P]T(E): see 19.1.1 Static Type of an Axis Step(0,N)
ForwardStep, ReverseStepAxis::NodeTestSee 19.1.1 Static Type of an Axis Step(0,N)
PostfixExprFilterExpr E[P]the static type of EIf P is numeric with max cardinality 1, then (0,1). Otherwise C(E) * (0,1)
FilterExprAM E?[P]T(E)C(E) * (0,1)
Dynamic Function Call F(X, Y)U{*}, unless ancillary information is available about the function signature of F: see below.The cardinality of the return type of F.
Literal"pH", 93.7, #xml:spaceU{xs:string}, U{xs:decimal}, U{xs:double}, or U{xs:QName} depending on the form of the literal(1,1)
StringTemplate`{$x}{$y}`U{xs:string}(1,1)
VarRef$VThe declared type of the variable if declared, otherwise the item type of the expression to which the variable is bound.The declared cardinality of the variable if declared, otherwise the cardinality of the expression to which the variable is bound, or (1,1) in the case of a variable declared in a ForExpr or QuantifiedExpr.
ParenthesizedExpr(E)T(E)C(E)
()U{} (a type whose only instance is the empty sequence)(0,0)
ContextValueRef.the context item type: see belowthe context cardinality: see below
FunctionCallF(X, Y)In general: the U-type corresponding to the declared result type of function F. But:
  • If one or more of the arguments to the function have operand usage transmission, then the intersection of the U-type corresponding to the declared result type with the union of the static types of the arguments having usage transmission. (For example, the static type of the function call head(//text()) is U{text()}.)

  • Special rules apply to the current function: see 19.1.2 Static Type of a Call to current.

TODO
Partial Function ApplicationF(X, ?), $F(X, ?)U{fn(*)}TODO
NamedFunctionRefF#nU{fn(*)}(1,1)
InlineFunctionExprfn(P) {E}U{fn(*)}(1,1)
MapConstructor{ "A": E, "B": F }U{fn(*)}(1,1)
Postfix Lookup (Shallow)E ? KIf the type of E is a map type map(K, V) or an array type array(V), then the U-type corresponding to the item type of V; otherwise U{*}. An implementation may be able to determine a more precise type when the type of E is a record type.(0,N)
Unary Lookup (Shallow)? KIf the context item type is a map type map(K, V) or an array type array(V), then the U-type corresponding to the item type of V; otherwise U{*}. An implementation may be able to determine a more precise type when the context item type is a record type.(0,N)
Deep Lookup?? K, E ?? KU{*}(0,N)
PipelineExprA -> BT(B)C(B)
ArrowExprX => F(Y, Z), X =!> F(Y, Z)The static type of the equivalent static or dynamic function call F(X, Y, Z)The cardinality of the equivalent static or dynamic function call F(X, Y, Z)
SquareArrayConstructor[ X, Y, ... ]U{fn(*)}(1,1)
CurlyArrayConstructorarray {X, Y, ... }U{fn(*)}(1,1)

Where the static type of an expression is U{fn(*)}, it is useful to retain additional information: specifically, the signature of the function. This may be regarded as information ancillary to the U-type of the expression; it does not play any role in operations such as testing whether one U-type is a subtype of another, or forming the union of two U-types. This ancillary information is available for a NamedFunctionRef, for an InlineFunctionExpr, for a MapConstructor, for a FunctionCall whose static type is U{fn(*)}, and for a VarRef if the variable is bound to any of the forgoing, or if it has a declared type corresponding to U{fn(*)}.

Note:

The special case type inference used for an AdditiveExpr or MultiplicativeExpr appearing as a predicate is possible because if an arithmetic operation within a predicate produces any other result, for example an xs:duration or xs:dateTime, this would cause a type error (on the grounds that an xs:duration or xs:dateTime has no effective boolean value), and static type inference only needs to consider the type of non-error results. The benefit of this special rule is that filter expressions such as /descendant::section[$i + 1] can be recognized as returning a singleton, and therefore as being striding, even if the type of $i is unknown.

19.8 Classifying Constructs

This section defines the properties of every kind of construct that may appear in a stylesheet. It identifies the operand roles and their usage, and it gives the rules that define the posture and sweep of the construct. In cases where the general streamability rules apply, there is still an entry for the construct in order to define its operands and their usages, since this information is needed by the general rules.

The following sections describe this categorization for each kind of construct:

19.8.8 Classifying Expressions

XPath expressions are classified using the rules in this section.

In the analysis that follows, expressions are classified according to the most specific production rule that they match for which there is an entry in this section. A production P is considered more specific than a production Q (QP) if every expression that matches P also matches Q. For example:

  • The expression 3 satisfies the productions NumericLiteral, Literal, and ArithmeticExpression; the most specific of these for which there is an entry in this section is Literal.

  • The expression text() (appearing as an expression) is a TextTest, and therefore a KindTest, which is itself a NodeTest, and therefore an AxisStep with a defaulted ForwardAxis. The most specific of these for which there is an entry in this section is AxisStep. Although the expression is also a RelativePathExpr, that production is less specific than AxisStep so its rules do not apply.

  • The expression section/title is a RelativePathExpr, for which there is an entry in this section. Although the expression is also a PathExpr, that production is less specific than RelativePathExpr so its rules do not apply.

The production rules for different kinds of expression are listed (with their names and numbers) in the order in which they appear in Appendix A.1 of the XPath 3.0 specification; rules are also given for new constructs introduced by XPath 3.1. Where two numbers are given, they are the production rule numbers in XPath 3.0 and XPath 3.1 respectively; where there is a single number, it is the production rule number in XPath 3.1.

Many expressions can be analyzed using the general streamability rules. These are indicated in the table below by means of a simple proforma in which the operand roles are represented by a short code (A = absorption, I = inspection, T = transmission, N = navigation). For example the proforma A + A indicates that for an arithmetic expression, both operands have operand usageabsorption, while I or I indicates that for an or expression, both operands have operand usageinspection. For expressions where further explanation is needed, the table contains a link to the relevant section.

Operand Roles for XPath Expressions
ConstructProforma or Reference to Detailed RulesFurther Information
ExprT, T
ForExprSee 19.8.8.1 Streamability of for Expressions
LetExprlet $var := N return TBinding of variables to streamed nodes is not allowed.
QuantifiedExprSee 19.8.8.2 Streamability of Quantified Expressions
IfExprif (I) then T else TThe then-clause and else-clause form a choice operand group with usage transmission
OrExprI or I
AndExprI and I
StringConcatExprA || A
RangeExprA to A
AdditiveExprA + A, A - A
MultiplicativeExprA * A, A div A, etc.
UnionExprSee 19.8.8.4 Streamability of union, intersect, and except Expressions
IntersectExceptExprSee 19.8.8.4 Streamability of union, intersect, and except Expressions
InstanceOfExprSee 19.8.8.5 Streamability of instance of Expressions
TreatExprSee 19.8.8.6 Streamability of treat as Expressions
CastableExprA castable as TYPE
CastExprA cast as TYPE
UnaryExpr+A, -A
GeneralCompA = A, A < A, A != A, etc.
ValueCompA eq A, A lt A, A ne A, etc.
NodeCompI is I, I << I, I >> ISee Note 1 below
SimpleMapExprSee 19.8.8.7 Streamability of Simple Mapping Expressions
PathExprSee 19.8.8.8 Streamability of Path Expressions
RelativePathExprSee 19.8.8.8 Streamability of Path Expressions
AxisStepSee 19.8.8.9 Streamability of Axis Steps
ForwardStep, ReverseStepSee 19.8.8.9 Streamability of Axis Steps
PostfixExpr: Filter ExpressionSee 19.8.8.10 Streamability of Filter Expressions
PostfixExpr: Dynamic Function CallSee 19.8.8.11 Streamability of Dynamic Function Calls
LiteralThere are no operands, so the construct is grounded and motionless
VarRefSee 19.8.8.12 Streamability of Variable References
ParenthesizedExpr(T)
()There are no operands, so the construct is grounded and motionless
ContextItemExprSee 19.8.8.13 Streamability of the Context Item Expression
FunctionCallSee 19.8.8.14 Streamability of Static Function Calls
NamedFunctionRefSee 19.8.8.15 Streamability of Named Function References
InlineFunctionExprSee 19.8.8.16 Streamability of Inline Function Declarations
MapConstructorSee 19.8.8.17 Streamability of Map Constructors
Lookup (Postfix and Unary)See 19.8.8.18 Streamability of Lookup Expressions
ArrowExprSee 19.8.8.14 Streamability of Static Function Calls and 19.8.8.11 Streamability of Dynamic Function Calls: the rules for X => F(Y, Z) are the same as the rules for F(X, Y, Z)
SquareArrayConstructor[ N, N, ... ]
CurlyArrayConstructorarray { N, N, ... }

Note:

  1. The operators is, <<, and >> apply to streamed nodes just as to any other nodes, though there are few practical situations where they will be useful. A streamed document conforms to the rules of the XDM data model, and its nodes are therefore distinct and ordered. They follow the usual rules, for example that a parent node precedes its children in document order. Expressions such as .. is parent::X or ancestor::x[1] << ancestor::y[1] are therefore perfectly meaningful. The usefulness of the operators is limited by the fact that variables cannot be bound to nodes in a streamed document. It is permitted, though perhaps not useful, for one of the operands to be consuming: one can write . << child::x, and the resulting expression is (by applying the general rules) consuming and grounded.

    The restriction that variables cannot be bound to streamed nodes prevents writing of expressions such as let $x := . return descendant::x[ancestor::y[1] is $x]. As a workaround, the intended effect can be achieved by comparing node identity using the generate-id function: let $x := generate-id(.) return descendant::x[generate-id(ancestor::y[1]) = $x]

19.8.8.17 Streamability of Map Constructors

The posture and sweep of a map constructor (see [XPath 4.0] section Section 4.13.1.1 Map ConstructorsXP) are the same as the posture and sweep of the equivalent xsl:map instruction. The equivalent xsl:map instruction is formed by creating a sequence of xsl:map-entry instructions, one for each key/value pair in the map expression, where the key expression becomes the value of xsl:map-entry/@key, and the value expression becomes the value of xsl:map-entry/@select; this sequence of xsl:map-entry instructions is then wrapped in an xsl:map parent instruction.

For example, the map constructor { 'red': false(), 'green': true() } translates to the instruction:

<xsl:map>
  <xsl:map-entry key="'red'" select="false()"/>
  <xsl:map-entry key="'green'" select="true()"/>
</xsl:map>

The rules for the streamability of xsl:map appear in 19.8.4.23 Streamability of xsl:map.

See also 21.2 Maps and Streaming.

20 Additional Functions

Changes in 4.0  

  1. 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]

This section describes XSLT-specific additions to the XPath function library. Some of these additional functions also make use of information specified by declarations in the stylesheet; this section also describes these declarations.

20.1 fn:document

Summary

Provides access to XML documents identified by a URI.

Signature
fn:document(
$uri-sequenceas item()*,
$base-nodeas node()?:= ()
) as node()*
Properties

The one-argument form of this function is deterministicFO, focus-independentFO, and context-dependentFO. It depends on static base URI.

The two-argument form of this function is deterministicFO, focus-independentFO, and context-independentFO.

Rules

The document function allows access to XML documents identified by a URI.

The first argument contains a sequence of URI references. The second argument, if present, is a node whose base URI is used to resolve any relative URI references contained in the first argument.

A sequence of absolute URI references is obtained as follows.

  • For an item in $uri-sequence that is an instance of xs:string, xs:anyURI, or xs:untypedAtomic, the value is cast to xs:anyURI. If the resulting URI reference is an absolute URI reference then it is used as is. If it is a relative URI reference, then it is resolved as follows:

    1. If $base-node is supplied (that is, if the argument is present and non-empty), then it is resolved against the base URI of $base-node.

    2. Otherwise it is resolved against the static base URI from the static context of the expression containing the call to the document function. In cases where the source code of the stylesheet is available at execution time, this will typically be the location of the relevant stylesheet module.

  • For an item in $uri-sequence that is a node, the node is atomized. The result must be a sequence whose items are all instances of xs:string, xs:anyURI, or xs:untypedAtomic. Each of these values is cast to xs:anyURI, and if the resulting URI reference is an absolute URI reference then it is used as is. If it is a relative URI reference, then it is resolved against the base URI of $base-node if supplied, or against the base URI of the node that contained it otherwise.

  • A relative URI is resolved against a base URI using the rules of the resolve-uri function. A dynamic error occurs (see below) if no base URI is available.

  • If $uri-sequence (after atomizing any nodes) contains an item other than an atomic item of type xs:string, xs:anyURI, or xs:untypedAtomic then a type error is raised [ERR XPTY0004] XP40.

Each of these absolute URI references is then processed as follows. Any fragment identifier that is present in the URI reference is removed, and the resulting absolute URI is cast to a string and then passed to the doc function defined in [Functions and Operators 3.04.0]. This returns a document node. If an error occurs during evaluation of the doc function, the processor may either raise this error in the normal way, or may recover by ignoring the failure, in which case the failing URI will not contribute any nodes to the result of the document function.

If the URI reference contained no fragment identifier, then this document node is included in the sequence of nodes returned by the document function.

If the URI reference contained a fragment identifier, then the fragment identifier is interpreted according to the rules for the media type of the resource representation identified by the URI, and is used to select zero or more nodes that are descendant-or-self nodes of the returned document node. As described in 2.3 Initiating a Transformation, the media type is available as part of the evaluation context for a transformation.

The sequence of nodes returned by the function is in document order, with no duplicates. This order has no necessary relationship to the order in which URIs were supplied in the $uri-sequence argument.

Error Conditions

[ERR XTDE1160] When a URI reference 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).

A processor may provide an option which, if selected, causes the processor instead of raising this error, to ignore the fragment identifier and return the document node.

The set of media types recognized by a processor is implementation-defined.

[ERR XTDE1162] When a URI reference 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.

Notes

One effect of these rules is that in an interpreted environment where the source code of the stylesheet is available and its base URI is known, then unless XML entities or xml:base are used, the expression document("") refers to the document node of the containing stylesheet module (the definitive rules are in [RFC3986]). The XML resource containing the stylesheet module is then processed exactly as if it were any other XML document, for example there is no special recognition of xsl:text elements, and no special treatment of comments and processing instructions.

The XPath rules for function calling ensure that it is a type error if the supplied value of the second argument is anything other than a single node. If XPath 1.0 compatibility mode is enabled, then a sequence of nodes may be supplied, and the first node in the sequence will be used.

20.4 Miscellaneous Additional Functions

20.4.2 fn:unparsed-entity-uri

Summary

Returns the URI (system identifier) of an unparsed entity

Signature
fn:unparsed-entity-uri(
$entity-nameas xs:string,
$docas node():= .
) as xs:anyURI
Properties

This function is deterministicFO, focus-dependentFO, and context-dependentFO.

Rules

Calling the single-argument form of this function has the same effect as calling the two-argument form with the context item as the second argument.

The two-argument unparsed-entity-uri function returns the URI of the unparsed entity whose name is given by the value of the $entity-name argument, in the document containing the node supplied as the value of the $doc argument. It returns the zero-length xs:anyURI if there is no such entity. This function maps to the dm:unparsed-entity-system-id accessor defined in [XDM 3.04.0].

Error Conditions

[ERR XTDE1370] 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.

The following errors may be raised when $node is omitted:

Notes

The XDM accessor dm:unparsed-entity-system-id is defined to return an absolute URI, obtained by resolving the system identifier as written against the base URI of the document. If no base URI is available for the document, the unparsed-entity-uri function should return the system identifier as written, without any attempt to make it absolute.

XML permits more than one unparsed entity declaration with the same name to appear, and says that the first declaration is the one that should be used. This rule should be respected during construction of the data model; the data model instance should not contain more than one unparsed entity with the same name.

20.4.3 fn:unparsed-entity-public-id

Summary

Returns the public identifier of an unparsed entity

Signature
fn:unparsed-entity-public-id(
$entity-nameas xs:string,
$docas node():= .
) as xs:string
Properties

This function is deterministicFO, focus-dependentFO, and context-dependentFO.

Rules

Calling the single-argument form of this function has the same effect as calling the two-argument form with the context item as the second argument.

The two-argument unparsed-entity-public-id function returns the public identifier of the unparsed entity whose name is given by the value of the $entity-name argument, in the document containing the node supplied as the value of the $doc argument. It returns the zero-length string if there is no such entity, or if the entity has no public identifier. This function maps to the dm:unparsed-entity-public-id accessor defined in [XDM 3.04.0].

Error Conditions

[ERR XTDE1380] 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.

The following errors may be raised when $node is omitted:

Notes

XML permits more than one unparsed entity declaration with the same name to appear, and says that the first declaration is the one that should be used. This rule should be respected during construction of the data model; the data model instance should not contain more than one unparsed entity with the same name.

20.4.5 fn:available-system-properties

Summary

Returns a list of system property names that are suitable for passing to the system-property function, as a sequence of QNames.

Signature
fn:available-system-properties() as xs:QName*
Properties

This function is deterministicFO, context-independentFO, and focus-independentFO.

Rules

The function returns a sequence of QNames, being the names of the system properties recognized by the processor, in some implementation-dependent order.

The prefix part of a returned QName is implementation-dependent.

The function is deterministicFO30FO: that is, the set of available system properties does not vary during the course of a transformation.

Notes

The function returns a list of QNames, containing no duplicates.

The QNames in this list are suitable for passing to the system-property function.

21 Maps

Maps are defined in the XDM Data Model: see [XDM 4.0] section Section 8.2 Map ItemsDM.

22 Arrays

Arrays are defined in the XDM Data Model: see [XDM 4.0] section Section 8.3 Array ItemsDM.

25 Transformation Results

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

25.1 Creating Secondary Results

Changes in 4.0  

  1. 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]

  2. 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 ]

<!-- 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 }
  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):

  1. The raw result may be delivered as is.

  2. The raw result may be used to construct a final result tree by invoking the process of sequence normalizationSER30SE.

  3. The raw result may be serialized to a sequence of octets (which may then, optionally, be saved to a persistent storage location).

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 normalizationSER30SE. 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. [XSLT 3.0 Erratum E14, bug 30208].

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 an 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 Section 3.1 Setting Serialization Parameters by Means of a Data Model Instance Parameter DocumentSER30, 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-markcdata-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.4 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 normalizationSER30SE. 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.

Example: Multiple Result Documents

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>

25.4 Validation

Changes in 4.0  

  1. The rules concerning the compatibility of schemas imported by different packages have been clarified. It is now explicitly stated that instructions that trigger validation must use the imported schema of the package in which validation is invoked. This differs from the current practice of some XSLT 3.0 processors, which may use (for example) a schema formed from the union of the imported schemas in all packages.   [Issue 451 PR 635 24 October 2023]

  2. The rules concerning the interpretation of xsi:schemaLocation and xsi:noNamespaceSchemaLocation attributes have been tightened up.   [Issue 729 PR 1254 8 June 2024]

  3. The rules concerning the interpretation of xsi:schemaLocation and xsi:noNamespaceSchemaLocation attributes have been tightened up.   [Issue 729 PR 1254 8 June 2024]

  4. In order to reduce duplication between the XSLT and XQuery specifications, description of the validation process has been moved to the Functions and Operators specification.   [Issue 2029 PR 2030 28 May 2025]

It is possible to control the type annotation applied to individual element and attribute nodes as they are constructed. This is done using the type and validation attributes of the xsl:element, xsl:attribute, xsl:copy, xsl:copy-of, xsl:document, and xsl:result-document instructions, or the xsl:type and xsl:validation attributes of a literal result element. The same attributes are used on xsl:source-document and xsl:merge-source to control validation of input documents.

The [xsl:]type attribute is used to request validation of an element or attribute against a specific simple or complex type defined in a schema. The [xsl:]validation attribute is used to request validation against the global element or attribute declaration whose name matches the name of the element or attribute being validated.

The [xsl:]type and [xsl:]validation attributes are mutually exclusive. Both are optional, but if one is present then the other must be omitted. If both attributes are omitted, the effect is the same as specifying the validation attribute with the value specified in the [xsl:]default-validation attribute of the innermost containing element having such an attribute; if this is not specified, the effect is the same as specifying validation="strip".

The [xsl:]default-validation attribute defines the default value of the validation attribute of all xsl:element, xsl:attribute, xsl:copy, xsl:copy-of, xsl:document, and xsl:result-document instructions, and of the xsl:validation attribute of all literal result elements, appearing as descendants of the element on which the attribute appears, unless there is an inner element that defines a different default. This default does not extend to included or imported stylesheet modules or used packages. If the attribute is omitted, the default is strip. The permitted values are preserve and strip.

The default-validation attribute on the outermost element of the principal stylesheet module of the top-level package also determines the validation applied to the implicit final result tree created in the absence of an xsl:result-document instruction. [XSLT 3.0 Erratum E15, bug 30211].

The [xsl:]default-validation attribute has no effect on the xsl:source-document and xsl:merge-source elements, which perform no validation unless explicitly requested.

[ERR XTSE1505] 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.

Validation always uses the in-scope schema definitionsXP from the static context of the instruction that invokes validation. The relevant schema may be selected using the [xsl:]schema-role attribute of the instruction itself, or of a containing element. See also 3.15.1 Multiple Schemas.

Note:

A stylesheet might take as its primary input a document conforming to schema X, and produce as its primary output a document conforming to schema Y. To be sure that the output is indeed valid against schema Y, the safest course of action is to evaluate an xsl:result-document instruction using an [xsl:]schema-role attribute that selects schema Y and nothing else. Otherwise, if the validation occurs within a module that imports both X and Y, the outcome of validation might differ because of the differences between the two schemas.

The detailed rules for validation vary depending on the kind of node being validated. The rules for element and attribute nodes are given in 25.4.1 Validating Constructed Elements and Attributes, while those for document nodes are given in 25.4.2 Validating Document Nodes.

25.4.1 Validating Constructed Elements and Attributes

25.4.1.1 Validation using the [xsl:]validation Attribute

The [xsl:]validation attribute defines the validation action to be taken. It determines not only the type annotation of the node that is constructed by the relevant instruction itself, but also the type annotations of all element and attribute nodes that have the constructed node as an ancestor. Conceptually, the validation requested for a child element or attribute node is applied before the validation requested for its parent element. For example, if the instruction that constructs a child element specifies validation="strict", this will cause the child element to be checked against an element declaration, but if the instruction that constructs its parent element specifies validation="strip", then the final effect will be that the child node is annotated as xs:untyped.

In the paragraphs below, the term contained nodes means the elements and attributes that have the newly constructed node as an ancestor.

  1. The value strip indicates that the new node and each of the contained nodes will have the type annotationxs:untyped if it is an element, or xs:untypedAtomic if it is an attribute. Any previous type annotation present on a contained element or attribute node (for example, a type annotation that is present on an element copied from a source document) is also replaced by xs:untyped or xs:untypedAtomic as appropriate. The typed value of the node is changed to be the same as its string value, as an instance of xs:untypedAtomic. In the case of elements the nilled property is set to false. The values of the is-id and is-idrefs properties are unchanged. Schema validation is not invoked.

  2. The value preserve indicates that nodes that are copied will retain their type annotations, but nodes whose content is newly constructed will be annotated as xs:anyType in the case of elements, or xs:untypedAtomic in the case of attributes. Schema validation is not invoked. The detailed effect depends on the instruction:

    1. In the case of xsl:element and literal result elements, the new element has a type annotation of xs:anyType, and the type annotations of contained nodes are retained unchanged.

      The nilled, is-id and is-idrefs properties on the new element are set to false.

    2. In the case of xsl:attribute, the effect is exactly the same as specifying validation="strip": that is, the new attribute will have the type annotation xs:untypedAtomic.

      The is-id and is-idrefs properties on the new attribute are set to false.

    3. In the case of xsl:copy-of, all the nodes that are copied will retain their type annotations unchanged. The values of their nilled, is-id and is-idrefs properties are also unchanged.

    4. In the case of xsl:copy, the effect depends on the kind of node being copied.

      1. Where the node being copied is an attribute, the copied attribute will retain its type annotation and the values of its is-id and is-idrefs properties.

      2. Where the node being copied is an element, the copied element will have a type annotation of xs:anyType (because this instruction does not copy the content of the element, it would be wrong to assume that the type is unchanged); but any contained nodes will have their type annotations retained in the same way as with xsl:element. The values of the nilled, is-id, and is-idrefs properties are handled in the same way as xsl:element.

  3. The value strict indicates that schema validation is carried out according to the process described in [Functions and Operators 4.0] section Section 15.1.4 XSD validationFO. The operand node is the node being constructed, and the effective schema is the in-scope schema definitions in the static context of the containing instruction. The effect of constructing a node with [xsl:]validation="strict" is equivalent to constructing an untyped node N, and then validating it using the expression;

    fn:xsd-validator({'validation-mode':'strict'})(N) ->
        if (?is-valid) then ?typed-node else error()

    More details on the error conditions appear below.

  4. The value lax indicates that lax validation is carried out according to the process described in [Functions and Operators 4.0] section Section 15.1.4 XSD validationFO. The operand node is the node being constructed, and the effective schema is the in-scope schema definitions in the static context of the containing instruction. The effect of constructing a node with [xsl:]validation="lax" is equivalent to constructing an untyped node N, and then validating it using the expression;

    fn:xsd-validator({'validation-mode':'lax'})(N) ->
        if (?is-valid) then ?typed-node else error()

    More details on the error conditions appear below.

Note:

The effect of these rules is that when validation succeeds, the validate expression returns a copy of the operand node, augmented with type annotations and expanded default values. When validation fails (more accurately, when the outcome of validity assessment is that the operand node is found to be invalid), the expression raises a dynamic error.

Note:

If an element that is being validated has an xsi:type attribute, then the value of the xsi:type attribute will be taken into account when performing the validation. However, the presence of an xsi:type attribute will not of itself cause an element to be validated: if validation against a named type is required, as distinct from validation against a top-level element declaration, then it must be requested using the XSLT [xsl:]type attribute on the instruction that invokes the validation, as described in section 25.4.1.2 Validation using the [xsl:]type Attribute

For reasons of backwards compatibility, the error conditions raised by XSLT validation have their own error codes:

25.4.1.2 Validation using the [xsl:]type Attribute

The [xsl:]type attribute takes as its value an EQNameXP. If it is a lexical QName with no prefix, it is expanded using the default namespace for types. This must be the name of a type definition included in the in-scope schema components for the stylesheet.

If the [xsl:]type attribute is present, then the newly constructed element or attribute is validated against the type definition identified by this attribute. Schema validation is carried out according to the process described in [Functions and Operators 4.0] section Section 15.1.4 XSD validationFO. The operand node is the node being constructed, and the effective schema is the in-scope schema definitions in the static context of the containing instruction. The effect is equivalent to constructing an untyped node N, and then validating it using the expression, where T is the QName obtained by expanding the value of the [xsl:]type attribute:

fn:xsd-validator(N, {'type':T})(N) ->
    if (?is-valid) then ?typed-node else error()

For reasons of backwards compatibility, the error conditions raised by XSLT validation have their own error codes:

  • If the element or attribute is not considered valid, as defined above, the transformation fails [see ERR XTTE1540].

  • If an element node is validated against the type xs:untyped, the effect is the same as specifying validation="strip": that is, the elements and attributes in the subtree rooted at the target element are copied with a type annotation of xs:untyped or xs:untypedAtomic respectively.

  • If an element or attribute node is validated against the type xs:untypedAtomic, the effect is the same as specifying [xsl:]type="xs:string" except that when validation succeeds, the returned element or attribute has a type annotation of xs:untypedAtomic. Validation fails in the case of an element with element children.

  • [ERR XTSE1520] 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. [XSLT 3.0 Erratum E20, bug 30234]

  • [ERR XTSE1530] It is a static error if the value of the type attribute of an xsl:attribute instruction refers to a complex type definition.

  • [ERR XTTE1535] 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.

  • [ERR XTTE1540] 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.

    Note:

    Like other type errors, this error may be raised statically if it can be detected statically. For example, the instruction <xsl:attribute name="dob" type="xs:date">1999-02-29</xsl:attribute> may result in a static error being raised. If the error is not raised statically, it will be raised when the instruction is evaluated.

26 Serialization

A processormay output a final result tree as a sequence of octets, although it is not required to be able to do so (see 27 Conformance). This process is described as serialization. Stylesheet authors can use xsl:output declarations to specify how they wish result trees to be serialized. If a processor serializes a final result tree, it must do so as specified by these declarations.

The rules governing the output of the serializer are defined in [XSLT and XQuery Serialization][xslt-xquery-serialization-30]. The serialization is controlled using a number of serialization parameters. The values of these serialization parameters may be set within the stylesheet, using the xsl:output, xsl:result-document, and xsl:character-map declarations.

26.1 The xsl:output declaration

Changes in 4.0  

  1. 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]

<!-- Category: declaration -->
<xsl:output
  name? = eqname
  method? = "xml" | "html" | "xhtml" | "text" | "json" | "adaptive" | eqname
  allow-duplicate-names? = boolean
  build-tree? = boolean
  byte-order-mark? = 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
  version? = nmtoken />

The xsl:output declaration is optional; if used, it must always appear as a top-level element within a stylesheet module.

A stylesheet may contain multiple xsl:output declarations and may include or import stylesheet modules that also contain xsl:output declarations. The name of an xsl:output declaration is the value of its name attribute, if any.

[Definition: 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.]

An output definition is scoped to a package. If this is a library package the output definition applies only to xsl:result-document instructions within the same package. If it is the top-level package, the output definition applies to xsl:result-document instructions within the same package and also to the implicit final result tree.

A stylesheet always includes an unnamed output definition; in the absence of an unnamed xsl:output declaration, the unnamed output definition is equivalent to the one that would be used if the stylesheet contained an xsl:output declaration having no attributes.

A named output definition is used when its name matches the format attribute used in an xsl:result-document element. The unnamed output definition is used when an xsl:result-document element omits the format attribute. It is also used when serializing the principal result. .

All the xsl:output elements making up an output definition are effectively merged. For those attributes whose values are namespace-sensitive, the merging is done after lexical QNames have been converted into expanded QNames. For the cdata-section-elements and suppress-indentation attributes, the output definition uses the union of the values from all the constituent xsl:output declarations. For the use-character-maps attribute, the output definition uses the concatenation of the sequences of expanded QNames values from all the constituent xsl:output declarations, taking them in order of increasing import precedence, or where several have the same import precedence, in declaration order. For other attributes, the output definition uses the value of that attribute from the xsl:output declaration with the highest import precedence.

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 Section 3.1 Setting Serialization Parameters by Means of a Data Model Instance Parameter DocumentSER30, and the parameters are interpreted as described in that specification.

If present, the URI supplied in the parameter-document attribute is dereferenced, after resolution against the base URI of the xsl:output element if it is a relative reference. The parameter document should be read during static analysis of the stylesheet. A serialization error occurs if the result of dereferencing the URI is ill-formed or invalid; but if no document can be found at the specified location, the attribute should be ignored.

A serialization parameter specified in the parameter-document takes precedence over a value supplied directly in the output declaration, 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.

[ERR XTSE1560] 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.

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 normalization. Conversely, if the result is serialized, then the decision whether or not to construct a tree depends on the choice of serialization method, and the 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. [XSLT 3.0 Erratum E14, bug 30208].

Note:

The default for build-tree may differ for user-defined serialization methods or for serialization methods introduced in future versions of this specification.

26.2 Serialization parameters

Changes in 4.0  

  1. The default value for the indent parameter is now defined to be no for all output methods other than html and xhtml.   [Issue 1548  9 November 2024]

If none of the xsl:output declarations within an output definition specifies a value for a particular attribute, then the corresponding serialization parameter takes a default value. The default value depends on the chosen output method.

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.

An implementation may allow the attributes of the xsl:output declaration to be overridden, or the default values to be changed, using the API that controls the transformation.

The location to which final result trees are serialized (whether in filestore or elsewhere) is implementation-defined (which in practice may mean that it is controlled using an implementation-defined API). However, these locations must satisfy the constraint that when two final result trees are both created (implicitly or explicitly) using relative URI references in the href attribute of the xsl:result-document instruction, then these relative URI references may be used to construct references from one tree to the other, and such references must remain valid when both result trees are serialized.

The method attribute on the xsl:output element identifies the overall method that is to be used for outputting the final result tree.

[ERR XTSE1570] The value must (if present) be a valid EQName. If it is a lexical QName in no namespace, then it identifies a method specified in [XSLT and XQuery Serialization][xslt-xquery-serialization-30] and must be one of xml, html, xhtml, text, json, or adaptive. If it is a lexical QName with a prefix, then the lexical QName is expanded into an expanded QName as described in 5.1.1 Qualified Names. An expanded QName with a non-absent namespace identifies an implementation-defined output method whose the behavior is not specified by this document.

The default for the method attribute depends on the contents of the tree being serialized, and is chosen as follows. If the document node of the final result tree has an element child, and any text nodes preceding the first element child of the document node of the result tree contain only whitespace characters, then:

  • If the expanded QName of this first element child has local part html (in lower case), and namespace URI http://www.w3.org/1999/xhtml, then the default output method is normally xhtml. However, if the effective version of the outermost element of the principal stylesheet module in the top-level package has the value 1.0, and if the result tree is generated implicitly (rather than by an explicit xsl:result-document instruction), then the default output method in this situation is xml.

  • If the expanded QName of this first element child has local part html (in any combination of upper and lower case) and a null namespace URI, then the default output method is html.

In all other cases, the default output method is xml.

The default output method is used if the selected output definition does not include a method attribute.

The other attributes on xsl:output provide parameters for the output method. The following attributes are allowed:

  • The value of the encoding attribute provides the value of the encoding parameter to the serialization method. The default value is implementation-defined, but in the case of the xml and xhtml methods it must be either UTF-8 or UTF-16.

  • The byte-order-mark attribute defines whether a byte order mark is written at the start of the file. If the value yes is specified, a byte order mark is written; if no is specified, no byte order mark is written. The default value depends on the encoding used. If the encoding is UTF-16, the default is yes; for UTF-8 it is implementation-defined, and for all other encodings it is no. The value of the byte order mark indicates whether high order bytes are written before or after low order bytes; the actual byte order used is implementation-dependent, unless it is defined by the selected encoding.

  • The cdata-section-elements attribute is a whitespace-separated list of QNames. The default value is an empty list. After expansion of these names using the applicable static namespaces for the xsl:output declaration in which they appear, this list of names provides the value of the cdata-section-elements parameter to the serialization method. In the case of an unprefixed name, the default namespace (that is, the namespace declared using xmlns="uri") is used.

    Note:

    This differs from the rule for most other QNames used in a stylesheet. The reason is that these names refer to elements in the result document, and therefore follow the same convention as the name of a literal result element or the name attribute of xsl:element.

  • The value of the doctype-system attribute provides the value of the doctype-system parameter to the serialization method. If the attribute is absent or has a zero-length string as its value, then the serialization parameter is not set (is “absent”).

  • The value of the doctype-public attribute provides the value of the doctype-public parameter to the serialization method. If the attribute is absent or has a zero-length string as its value, then the serialization parameter is not set (is “absent”).

    The value of doctype-public must conform to the rules for a PubidLiteralXML (see [XML 1.0]).

  • The value of the escape-solidus attribute provides the value of the escape-solidus parameter to the serialization method. The default value is yes.

  • The value of the escape-uri-attributes attribute provides the value of the escape-uri-attributes parameter to the serialization method. The default value is yes.

  • The value of the html-version attribute provides the value of the html-version parameter to the serialization method. The set of permitted values, and the default value, are implementation-defined. A serialization error will be raised if the requested version is not supported by the implementation.

    Note:

    This serialization parameter is new in version 3.0. If it is absent, the html output method uses the value of the version parameter in its place. For XHTML serialization, the html-version parameter indicates the version of XHTML to be used, while the version parameter indicates the version of XML.

  • The value of the include-content-type attribute provides the value of the include-content-type parameter to the serialization method. The default value is yes.

  • The value of the indent attribute provides the value of the indent parameter to the serialization method. The default value is yes in the case of the html and xhtml output methods, no in the case of all other output methods.

  • The value of the item-separator attribute provides the value of the item-separator parameter to the serialization method. The value of the serialization parameter can be any string (including a zero-length string), or absent. To set the parameter to absent, the item-separator attribute can either be omitted, or set to the special value item-separator="#absent"; it is not possible to set the value of the serialization parameter to the literal 7-character string "#absent".

    Note:

    The item-separator attribute has no effect if the sequence being serialized contains only one item. [XSLT 3.0 Erratum E14, bug 30208].

  • The value of the json-lines attribute determines whether the JSON output method should output multiple JSON values in json-lines format (one value per line). The default value is no.

  • The value of the json-node-output-method attribute determines how any nodes appearing within maps or arrays are serialized by the json output method. The default value is xml. The syntax and semantics of the value follow the same rules as the method attribute.

  • The value of the media-type attribute provides the value of the media-type parameter to the serialization method. The default value is text/xml in the case of the xml output method, text/html in the case of the html and xhtml output methods, and text/plain in the case of the text output method. The default for the json output method is application/json; the default for the adaptive output method is implementation-defined. [XSLT 3.0 Erratum E26, bug 30245].

  • The value of the normalization-form attribute provides the value of the normalization-form parameter to the serialization method. A value that is an NMTOKEN other than one of those enumerated for the normalization-form attribute specifies an implementation-defined normalization form; the behavior in this case is not specified by this document. The default value is none.

  • The value of the omit-xml-declaration attribute provides the value of the omit-xml-declaration parameter to the serialization method. The default value is no.

  • The value of the standalone attribute provides the value of the standalone parameter to the serialization method. The default value is omit; this means that no standalone attribute is to be included in the XML declaration.

  • The suppress-indentation attribute is a whitespace-separated list of QNames. The default value is an empty list. After expansion of these names using the applicable static namespaces for the xsl:output declaration in which they appear, this list of names provides the value of the suppress-indentation parameter to the serialization method. In the case of an unprefixed name, the default namespace (that is, the namespace declared using xmlns="uri") is used.

    Note:

    This differs from the rule for most other QNames used in a stylesheet. The reason is that these names refer to elements in the result document, and therefore follow the same convention as the name of a literal result element or the name attribute of xsl:element.

  • The value of the undeclare-prefixes attribute provides the value of the undeclare-prefixes parameter to the serialization method. The default value is no.

  • The use-character-maps attribute provides a list of named character maps that are used in conjunction with this output definition. The way this attribute is used is described in 26.3 Character Maps. The default value is an empty list.

  • The value of the version attribute provides the value of the version parameter to the serialization method. The set of permitted values, and the default value, are implementation-defined. A serialization error will be raised if the requested version is not supported by the implementation.

If the processor performs serialization, then it must raise any serialization errors that occur. These have the same effect as dynamic errors: that is, the processor must raise the error and must not finish as if the transformation had been successful.

26.3 Character Maps

[Definition: 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.] The effect of character maps is defined in [XSLT and XQuery Serialization][xslt-xquery-serialization-30].

The character map that is supplied as a parameter to the serializer is determined from the xsl:character-map elements referenced from the xsl:output declaration for the selected output definition.

The xsl:character-map element is a declaration that may appear as a child of the xsl:stylesheet element.

<!-- Category: declaration -->
<xsl:character-map
  name = eqname
  use-character-maps? = eqnames >
  <!-- Content: (xsl:output-character*) -->
</xsl:character-map>

The xsl:character-map declaration declares a character map with a name and a set of character mappings. The character mappings are specified by means of xsl:output-character elements contained either directly within the xsl:character-map element, or in further character maps referenced in the use-character-maps attribute.

The requiredname attribute provides a name for the character map. When a character map is used by an output definition or another character map, the character map with the highest import precedence is used.

The name of a character map is local to the package in which its declaration appears; it may be referenced only from within the same package.

[ERR XTSE1580] 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.

The optional use-character-maps attribute lists the names of further character maps that are included into this character map.

[ERR XTSE1590] 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.

[ERR XTSE1600] It is a static error if a character map references itself, directly or indirectly, via a name in the use-character-maps attribute.

It is not an error if the same character map is referenced more than once, directly or indirectly.

For every xsl:character-map declaration in a package, other than one that is overridden by another of higher import precedence, the static context of the package includes a named character map derived from the xsl:character-map declaration. The name of the named character map is the QName formed by expanding the value of the name attribute, and the content is a map of type map{xs:string, xs:string} that maps characters (represented as xs:string instances of length 1) to their replacement strings.

Recursive expansion of character maps using use-character-maps attributes may produce several mappings for the same character. In this situation, the last character mapping takes precedence. To establish the ordering, the following rules are used:

  • Within a single xsl:character-map element, the characters defined in character maps referenced in the use-character-maps attribute are considered before the characters defined in the child xsl:output-character elements.

  • The character maps referenced in a single use-character-maps attribute are considered in the order in which they are listed in that attribute. The expansion is depth-first: each referenced character map is fully expanded before the next one is considered.

  • Two xsl:output-character elements appearing as children of the same xsl:character-map element are considered in document order.

The xsl:output-character element is defined as follows:

<xsl:output-character
  character = char
  string = string />

The character map that is passed as a parameter to the serializer contains a mapping for the character specified in the character attribute to the string specified in the string attribute.

Character mapping is not applied to characters for which output escaping has been disabled as described in 26.5 Disabling Output Escaping.

If a character is mapped, then it is not subjected to XML or HTML escaping.

Example: Using Character Maps to Generate Non-XML Output

Character maps can be useful when producing serialized output in a format that resembles, but is not strictly conformant to, HTML or XML. For example, when the output is a JSP page, there might be a need to generate the output:

<jsp:setProperty name="user" property="id" value='<%= "id" + idValue %>'/>

Although this output is not well-formed XML or HTML, it is valid in Java Server Pages. This can be achieved by allocating three Unicode characters (which are not needed for any other purpose) to represent the strings <%, %>, and ", for example:

<xsl:character-map name="jsp">
  <xsl:output-character character="«" string="&lt;%"/>   
  <xsl:output-character character="»" string="%&gt;"/>
  <xsl:output-character character="§" string='"'/>
</xsl:character-map>

When this character map is referenced in the xsl:output declaration, the required output can be produced by writing the following in the stylesheet:

<jsp:setProperty name="user" property="id" value='«= §id§ + idValue »'/>

This works on the assumption that when an apostrophe or quotation mark is generated as part of an attribute value by the use of character maps, the serializer will (where possible) use the other choice of delimiter around the attribute value.

 

Example: Constructing a Composite Character Map

The following example illustrates a composite character map constructed in a modular fashion:

<xsl:output name="htmlDoc" use-character-maps="htmlDoc"/>

<xsl:character-map name="htmlDoc"
  use-character-maps="html-chars doc-entities windows-format"/>
  
<xsl:character-map name="html-chars"
  use-character-maps="latin1 ..."/>

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

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

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

  <!-- tabs as three spaces -->
  <xsl:output-character character="&#x9;" string="   "/>

  <!-- images for special characters -->
  <xsl:output-character character="&#xF001;"
    string="&lt;img src='special1.gif' /&gt;"/>
  <xsl:output-character character="&#xF002;"
    string="&lt;img src='special2.gif' /&gt;"/>
  ...
</xsl:character-map>

Note:

When character maps are used, there is no guarantee that the serialized output will be well-formed XML (or HTML). Furthermore, the fact that the result tree was validated against a schema gives no guarantee that the serialized output will still be valid against the same schema. Conversely, it is possible to use character maps to produce schema-valid output from a result tree that would fail validation.

Note:

The value of the string attribute must be a literal string; this means it must consist entirely of characters that are valid in XML 1.0 or XML 1.1, depending on the version of XML used for the containing stylesheet module. The string can however be expressed as a shadow attribute (see 3.13.4 Shadow Attributes), and this allows it to be defined using a static expression. For example, the character U+2398 (NEXT PAGE, ) might be mapped to the control character U+000C (FORM FEED) by writing <xsl:output-character char="&#x2398;" _string="{char(0x0C)}"/>. This depends on the processor allowing the form-feed character to appear in strings: the data model allows this, but processors are not required to support it: see [XDM 4.0] section Section 4.1.5 XML and XSD VersionsDM.

26.5 Disabling Output Escaping

Normally, when using the XML, HTML, or XHTML output method, the serializer will escape special characters such as & and < when outputting text nodes. This ensures that the output is well-formed. However, it is sometimes convenient to be able to produce output that is almost, but not quite well-formed XML; for example, the output may include ill-formed sections which are intended to be transformed into well-formed XML by a subsequent non-XML-aware process. For this reason, XSLT defines a mechanism for disabling output escaping.

This feature is deprecated.

This is an optional feature: it is not required that an XSLT processor that implements the serialization option should offer the ability to disable output escaping, and there is no conformance level that requires this feature.

This feature requires the serializer (described in [XSLT and XQuery Serialization][xslt-xquery-serialization-30]) to be extended as follows. Conceptually, the final result tree provides an additional boolean property disable-escaping associated with every character in a text node. When this property is set, the normal action of the serializer to escape special characters such as & and < is suppressed.

An xsl:value-of or xsl:text element may have a disable-output-escaping attribute; the allowed values are yes or no. The default is no; if the value is yes, then every character in the text node generated by evaluating the xsl:value-of or xsl:text element should have the disable-escaping property set.

Example: Disable Output Escaping

For example,

<xsl:text disable-output-escaping="yes">&lt;</xsl:text>

should generate the single character <.

If output escaping is disabled for an xsl:value-of or xsl:text instruction evaluated when temporary output state is in effect, the request to disable output escaping is ignored.

Similarly, if an xsl:value-of or xsl:text instruction specifies that output escaping is to be disabled when writing to a final result tree that is not being serialized, the request to disable output escaping is ignored.

Note:

Furthermore, a request to disable output escaping has no effect when the newly constructed text node is used to form the value of an attribute, comment, processing instruction, or namespace node. This is because the rules for constructing such nodes (see 5.7.2 Constructing Simple Content) cause the text node to be atomized, and the process of atomizing a text node takes no account of the disable-escaping property.

If output escaping is disabled for text within an element that would normally be output using a CDATA section, because the element is listed in the cdata-section-elements, then the relevant text will not be included in a CDATA section. In effect, CDATA is treated as an alternative escaping mechanism, which is disabled by the disable-output-escaping option.

Example: Interaction of Output Escaping and CDATA

For example, if <xsl:output cdata-section-elements="title"/> is specified, then the following instructions:

<title>
  <xsl:text disable-output-escaping="yes">This is not &lt;hr/&gt; 
                                          good coding practice</xsl:text>
</title>

should generate the output:

<title><![CDATA[This is not ]]><hr/><![CDATA[ good coding practice]]></title>

The disable-output-escaping attribute may be used with the html output method as well as with the xml output method. The text output method ignores the disable-output-escaping attribute, since this method does not perform any output escaping.

A processor will only be able to disable output escaping if it controls how the final result tree is output. This might not always be the case. For example, the result tree might be used as a source tree for another XSLT transformation instead of being output. It is implementation-defined whether (and under what circumstances) disabling output escaping is supported. If disabling output escaping is not supported, any request to disable output escaping is ignored.

If output escaping is disabled for a character that is not representable in the encoding that the processor is using for output, the request to disable output escaping is ignored in respect of that character.

Since disabling output escaping might not work with all implementations and can result in XML that is not well-formed, it should be used only when there is no alternative.

Note:

When disable-output-escaping is used, there is no guarantee that the serialized output will be well-formed XML (or HTML). Furthermore, the fact that the result tree was validated against a schema gives no guarantee that the serialized output will still be valid against the same schema. Conversely, it is possible to use disable-output-escaping to produce schema-valid output from a result tree that would fail validation.

Note:

The facility to define character maps for use during serialization, as described in 26.3 Character Maps, has been produced as an alternative mechanism that can be used in many situations where disabling of output escaping was previously necessary, without the same difficulties.

27 Conformance

Changes in 4.0 

  1. The higher-order-function feature no longer exists; higher-order functions are now a core part of XSLT, no longer an optional extra.   [Issue 205 PR 326 1 February 2023]

A processor that claims conformance with this specification must satisfy the conformance requirements for a basic XSLT processor and for each of the optional features with which it claims conformance.

The following optional features are defined:

  1. The schema-awareness feature, defined in 27.2 Schema-Awareness Conformance Feature

  2. The serialization feature, defined in 27.3 Serialization Feature

  3. The backwards compatibility feature, defined in 27.4 Compatibility Features

  4. The streaming feature, defined in 27.5 Streaming Feature.

  5. The dynamic evaluation feature, defined in 27.6 Dynamic Evaluation Feature.

A processor that does not claim conformance with an optional feature must satisfy the requirements for processors that do not implement that feature.

An XSLT processor takes as its inputs a stylesheet and zero or more XDM trees conforming to the data model defined in [XDM 3.04.0]. It is not required that the processor supports any particular method of constructing XDM trees, but conformance can only be tested if it provides a mechanism that enables XDM trees representing the stylesheet and primary source document to be constructed and supplied as input to the processor.

The output of the XSLT processor consists of zero or more final result trees. It is not required that the processor supports any particular method of accessing a final result tree, but if it does not support the serialization feature, conformance can only be tested if it provides some alternative mechanism that enables access to the results of the transformation.

Certain facilities in this specification are described as producing implementation-defined results. A claim that asserts conformance with this specification must be accompanied by documentation stating the effect of each implementation-defined feature. For convenience, a non-normative checklist of implementation-defined features is provided at F Checklist of Implementation-Defined Features.

A conforming processormust raise any static error occurring in the stylesheet, or in any XPath expression, except where specified otherwise either for individual error conditions or under the general provisions for forwards compatible behavior (see 3.10 Forwards Compatible Processing). After raising such an error, the processor may continue for the purpose of raising additional errors, but must terminate abnormally without performing any transformation.

When a dynamic error occurs during the course of a transformation, and is not caught using xsl:catch, the processor must raise it and must eventually terminate abnormally.

Some errors, notably type errors, may be treated as static errors or dynamic errors at the discretion of the processor.

A conforming processor may impose limits on the processing resources consumed by the processing of a stylesheet.

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.

Some of the optional features are defined in such a way that if the feature is not provided, the data model is constrained to exclude certain kinds of item. For example:

[ERR XTDE1665] 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.

Note:

It is not necessarily possible to trigger this error. A processor that does not provide an optional feature might not define or recognize any representation of the items that are disallowed. The error code is provided for use in cases where a processor is able to interoperate with other software that does not have the same constraints — for example, where a package compiled with a non-schema-aware processor is able to invoke functions in a package that was compiled with a schema-aware processor. Even in that case, processors have the option of filtering or converting the input so that it meets the relevant constraints: for example, a non-schema-aware processor when presented with a schema-validated document in the form of a PSVI might simply ignore the properties it does not understand.

The dynamic error is optional: for example a processor might report no error if the offending item is not actually used.

The phrase input to the processor is deliberately wide: it includes (inter alia) the global context item, items present in the initial match selection, items passed as stylesheet parameters, items returned by functions such as document, doc, and collection, items returned by extension functions and extension instructions, items supplied in function or template parameters or results across package boundaries, and nodes reachable from any of the above by axis navigation.

27.3 Serialization Feature

[Definition: 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.] It must respect all the attributes of the xsl:output and xsl:character-map declarations, and must provide all four output methods, xml, xhtml, html, and text. Where the specification uses words such as must and required, then it must serialize the result tree in precisely the way described; in other cases it may use an alternative, equivalent representation.

A processor may claim conformance with the serialization feature whether or not it supports the setting disable-output-escaping="yes" on xsl:text, or xsl:value-of.

A processor that does not claim conformance with the serialization feature must not raise an error merely because the stylesheet contains xsl:output or xsl:character-map declarations, or serialization attributes on the xsl:result-document instruction. Such a processor may check that these declarations and attributes have valid values, but is not required to do so. Apart from optional validation, these declarations should be ignored.

Note:

A processor that does not claim conformance with the serialization feature may offer alternative serialization capabilities, and these may make use of the serialization parameters defined on xsl:output and/or xsl:result-document. Such a processor may implement selected parts of the serialization capabilities defined in this specification. For example, it may implement selected output methods, or selected serialization properties. It may implement sequence normalization using the item-separator property even if it has no other serialization capabilities. [XSLT 3.0 Erratum E14, bug 30208].

If the processor claims conformance with the serialization feature then it must fully implement the serialize function defined in [Functions and Operators 4.0], and must not raise error [ERR FODC0010] FO40 as the result of such a call.

If the processor does not claim conformance with the serialization feature, then it may raise error [ERR FODC0010] FO40 in respect of some or all calls on the serialize function; it must not return a result from a call on this function unless the result is conformant with the specification, given the parameters actually supplied.

A processor that claims conformance with the Serialization Feature must satisfy the mandatory requirements of [XSLT and XQuery Serialization][xslt-xquery-serialization-30]. It must provide a mode of operation which conforms to the 3.0 version of that specification. It may also provide a mode of operation which conforms to a later version of that specification; in such cases the detail of how XSLT 3.0 interacts with new features introduced by such a version (for example, support for new serialization properties) is implementation-defined.

A References

A.1 Normative References

XDM 3.04.0
XQuery and XPath Data Model (XDM) 3.0, Norman Walsh, Anders Berglund, John Snelson, Editors. World Wide Web Consortium, 08 April 2014. This version is https://www.w3.org/TR/2014/REC-xpath-datamodel-30-20140408/. The latest version is available at https://www.w3.org/TR/xpath-datamodel-30/.
XDM 3.1
XQuery and XPath Data Model (XDM) 3.1, Norman Walsh, John Snelson, Andrew Coleman, Editors. World Wide Web Consortium, 21 March 2017. This version is https://www.w3.org/TR/2017/REC-xpath-datamodel-31-20170321/. The latest version is available at https://www.w3.org/TR/xpath-datamodel-31/.
XDM 4.0
XQuery and XPath Data Model (XDM) 4.0, XSLT Extensions Community Group, World Wide Web Consortium.
Functions and Operators 3.04.0
XQuery and XPath Functions and Operators 3.0, Michael Kay, Editor. World Wide Web Consortium, 08 April 2014. This version is https://www.w3.org/TR/2014/REC-xpath-functions-30-20140408/. The latest version is available at https://www.w3.org/TR/xpath-functions-30/.
Functions and Operators 3.1
XQuery and XPath Functions and Operators 3.1, Michael Kay, Editor. World Wide Web Consortium, 21 March 2017. This version is https://www.w3.org/TR/2017/REC-xpath-functions-31-20170321/. The latest version is available at https://www.w3.org/TR/xpath-functions-31/.
Functions and Operators 4.0
CITATION: T.B.D.
XML Information Set
XML Information Set (Second Edition), John Cowan and Richard Tobin, Editors. World Wide Web Consortium, 04 Feb 2004. This version is http://www.w3.org/TR/2004/REC-xml-infoset-20040204. The latest version is available at http://www.w3.org/TR/xml-infoset.
ISO 15924
ISO (International Organization for Standardization) Information and documentation — Codes for the representation of names of scripts ISO 15924:2004, January 2004. See https://www.iso.org/obp/ui/#!iso:std:iso:15924:ed-1:v1:en.
ISO 15924 Register
Unicode Consortium. Codes for the representation of names of scripts — Alphabetical list of four-letter script codes. See http://www.unicode.org/iso15924/iso15924-codes.html. Retrieved February 2013; continually updated.
ISO 21320
ISO (International Organization for Standardization) Information technology — Document Container File, Part 1: Core ISO 21320-1:2015, October 2015. See https://www.iso.org/obp/ui/#iso:std:iso-iec:21320:-1:ed-1:v1:en.
XSLT and XQuery Serialization
XSLT and XQuery Serialization 3.0, Henry Zongaro, Andrew Coleman, Michael Sperberg-McQueen, Editors. World Wide Web Consortium, 08 April 2014. This version is https://www.w3.org/TR/2014/REC-xslt-xquery-serialization-30-20140408/. The latest version is available at https://www.w3.org/TR/xslt-xquery-serialization-30/.
XSLT and XQuery Serialization 3.1
XSLT and XQuery Serialization 3.1, Andrew Coleman and Michael Sperberg-McQueen, Editors. World Wide Web Consortium, 21 March 2017. This version is https://www.w3.org/TR/2017/REC-xslt-xquery-serialization-31-20170321/. The latest version is available at https://www.w3.org/TR/xslt-xquery-serialization-31/.
XSLT and XQuery Serialization 4.0
Serialization 4.0
XSLT and XQuery Serialization 4.0, XSLT Extensions Community Group, World Wide Web Consortium.
RFC 7595
IETF. Guidelines and Registration Procedures for URI Schemes. June 2015. See http://www.ietf.org/rfc/rfc7595.txt
RFC 7159
IETF. The JavaScript Object Notation (JSON) Data Interchange Format. March 2014. See http://www.ietf.org/rfc/rfc7159.txt
UNICODE
Unicode Consortium. The Unicode Standard as updated from time to time by the publication of new versions. See http://www.unicode.org/standard/versions/ for the latest version and additional information on versions of the standard and of the Unicode Character Database. The version of Unicode to be used is implementation-defined, but implementations are recommended to use the latest Unicode version.
UNICODE TR10
Unicode Consortium. Unicode Technical Standard #10. Unicode Collation Algorithm. Unicode Technical Report. See http://www.unicode.org/reports/tr10/.
UNICODE TR35
Unicode Consortium. Unicode Technical Standard #35. Unicode Locale Data Markup Language. Unicode Technical Report. See http://www.unicode.org/reports/tr35/.
XML 1.0
World Wide Web Consortium. Extensible Markup Language (XML) 1.0. W3C Recommendation. See http://www.w3.org/TR/REC-xml/. The edition of XML 1.0 must be no earlier than the Third Edition; the edition used is implementation-defined, but we recommend that implementations use the latest version.
XML 1.1
Extensible Markup Language (XML) 1.1 (Second Edition), Tim Bray, Jean Paoli, Michael Sperberg-McQueen, et. al., Editors. World Wide Web Consortium, 16 Aug 2006. This version is http://www.w3.org/TR/2006/REC-xml11-20060816. The latest version is available at http://www.w3.org/TR/xml11/.
XML Base
XML Base (Second Edition), Jonathan Marsh and Richard Tobin, Editors. World Wide Web Consortium, 28 Jan 2009. This version is http://www.w3.org/TR/2009/REC-xmlbase-20090128/. The latest version is available at http://www.w3.org/TR/xmlbase/.
xml:id
xml:id Version 1.0, Jonathan Marsh, Daniel Veillard, and Norman Walsh, Editors. World Wide Web Consortium, 09 Sep 2005. This version is http://www.w3.org/TR/2005/REC-xml-id-20050909/. The latest version is available at http://www.w3.org/TR/xml-id/.
Namespaces in XML
Namespaces in XML 1.0 (Third Edition), Tim Bray, Dave Hollander, Andrew Layman, et. al., Editors. World Wide Web Consortium, 08 Dec 2009. This version is http://www.w3.org/TR/2009/REC-xml-names-20091208/. The latest version is available at http://www.w3.org/TR/xml-names/.
Namespaces in XML 1.1
Namespaces in XML 1.1 (Second Edition), Tim Bray, Dave Hollander, Andrew Layman, and Richard Tobin, Editors. World Wide Web Consortium, 16 Aug 2006. This version is http://www.w3.org/TR/2006/REC-xml-names11-20060816. The latest version is available at http://www.w3.org/TR/xml-names11/.
XML Schema Part 1
XML Schema Part 1: Structures Second Edition, Henry Thompson, David Beech, Murray Maloney, and Noah Mendelsohn, Editors. World Wide Web Consortium, 28 Oct 2004. This version is http://www.w3.org/TR/2004/REC-xmlschema-1-20041028/. The latest version is available at http://www.w3.org/TR/xmlschema-1/.
XML Schema Part 2
XML Schema Part 2: Datatypes Second Edition, Paul V. Biron and Ashok Malhotra, Editors. World Wide Web Consortium, 28 Oct 2004. This version is http://www.w3.org/TR/2004/REC-xmlschema-2-20041028/. The latest version is available at http://www.w3.org/TR/xmlschema-2/.
XML Schema 1.1 Part 1
W3C XML Schema Definition Language (XSD) 1.1 Part 1: Structures, Sandy Gao, Michael Sperberg-McQueen, Henry Thompson, et. al., Editors. World Wide Web Consortium, 05 Apr 2012. This version is http://www.w3.org/TR/2012/REC-xmlschema11-1-20120405/. The latest version is available at http://www.w3.org/TR/xmlschema11-1/.
XML Schema 1.1 Part 2
W3C XML Schema Definition Language (XSD) 1.1 Part 2: Datatypes, David Peterson, Sandy Gao, Ashok Malhotra, et. al., Editors. World Wide Web Consortium, 05 Apr 2012. This version is http://www.w3.org/TR/2012/REC-xmlschema11-2-20120405/. The latest version is available at http://www.w3.org/TR/xmlschema11-2/.
XPath 3.04.0
XML Path Language (XPath) 3.0, Jonathan Robie, Don Chamberlin, Michael Dyck, John Snelson, Editors. World Wide Web Consortium, 08 April 2014. This version is https://www.w3.org/TR/2014/REC-xpath-30-20140408/. The latest version is available at https://www.w3.org/TR/xpath-30/.
XPath 3.1
XML Path Language (XPath) 3.1, Jonathan Robie, Michael Dyck and Josh Spiegel, Editors. World Wide Web Consortium, 21 March 2017. This version is https://www.w3.org/TR/2017/REC-xpath-31-20170321/. The latest version is available at https://www.w3.org/TR/xpath-31/.
XPath 4.0
CITATION: T.B.D.
XSLT Media Type
World Wide Web Consortium. Registration of MIME Media Type application/xslt+xml. In Appendix B.1 of the XSLT 2.0 specification.

B Glossary (Non-Normative)

absent

A component of the context that has no value is said to be absent.

absorption

An operand usage of absorption indicates that the construct reads the subtree(s) rooted at a supplied node(s).

accumulator

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.

accumulator function

The functions accumulator-before and accumulator-after are referred to as the accumulator functions.

alias

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.

applicable

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.

applicable static namespaces

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.

arity range

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.

atomize

The term atomization is defined in [XPath 4.0] section Section 2.5.3 AtomizationXP. 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 3.04.0]. Arrays (see 22 Arrays) are atomized by atomizing their members, recursively.

attribute set

An attribute set is defined as a set of xsl:attribute-set declarations in the same package that share the same expanded QName.

attribute set invocation

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.

attribute value template

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

backwards compatible behavior

An element is processed with backwards compatible behavior if its effective version is less than 4.0.

base output URI

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.

basic XSLT processor

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.

character map

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.

choice operand group

For some construct kinds, one or more operand roles may be defined to form a choice operand group. This concept is used where it is known that operands are mutually exclusive (for example the then and else clauses in a conditional expression).

circularity

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.

climbing

Climbing: indicates that streamed nodes returned by the construct are reached by navigating the parent, ancestor[-or-self], attribute, and/or namespace axes from the node at the current streaming position.

coercion rules

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.

collation

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.

combined merge key value

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.

combined posture

The combined posture of a choice operand group is determined by the postures of the operands in the group (the operand postures), and is the first of the following that applies:

  1. If any of the operand postures is roaming, then the combined posture is roaming.

  2. If all of the operand postures are grounded, then the combined posture is grounded.

  3. If one or more of the operand postures is climbing and the remainder (if any) are grounded, then the combined posture is climbing.

  4. If one or more of the operand postures is striding and the remainder (if any) are grounded, then the combined posture is striding.

  5. If one or more of the operand postures is crawling and each of the remainder (if any) is either striding or grounded, then the combined posture is crawling.

  6. Otherwise (for example, if the group includes both an operand with climbing posture and one with crawling posture), the combined posture is roaming.

compatible

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.

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.

construct

The term construct refers to the union of the following: a sequence constructor, an instruction, an attribute set, a value template, an expression, or a pattern.

consuming

A consuming construct is any construct deemed consuming by the rules in this section (19 Streamability).

containing package

A component declaration results in multiple components, one in the package in which the declaration appears, and potentially one in each package that uses the declaring package, directly or indirectly, subject to the visibility of the component. Each of these multiple components has the same 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.

context item

The context item is the item currently being processed. An item (see [XDM 3.04.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.

context item type

For every expression, it is possible to establish by static analysis, information about the item type of the context item for evaluation of that expression. This is called the context item type of the expression.

context node

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.

context position

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.

context posture

The context posture. This captures information about how the context item used as input to the construct is positioned relative to the streamed input. The context posture of a construct C is the posture of the expression whose value sets the focus for the evaluation of C.

context size

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).

controlled operand

Within a focus-changing construct there are one or more operands that are evaluated with a focus determined by the controlling operand (or in some cases such as xsl:on-completion, with an absentfocus); these are referred to as controlled operands.

controlling operand

Within a focus-changing construct there is in many cases one operand whose value determines the focus for evaluating other operands; this is referred to as the controlling operand.

crawling

Crawling: typically indicates that streamed nodes returned by a construct are reached by navigating the descendant[-or-self] axis.

current captured groups

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.

current group

The current group is the group itself, as a sequence of items

current grouping key

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.

current merge 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.

current merge key

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.

current mode

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.

current output URI

The current output URI is the URI associated with the principal result or secondary result that is currently being written.

current template rule

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.

decimal format

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.

declaration

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.7.4 User-defined Data Elements)

declaration order

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.

declared-streamable

The above constructs (template rules belonging to a mode declared with streamable="yes"; and xsl:source-document, xsl:attribute-set, xsl:function, xsl:merge-source, and xsl:accumulator elements specifying streamable="yes") are said to be declared-streamable.

declaring package

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.

default collation

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.

default mode

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.

default priority

If no priority attribute is specified on an xsl:template element, a default priority is computed, based on the syntax of the pattern supplied in the match attribute.

defining element

A string in the form of a lexical QName may occur as the value of an attribute node in a stylesheet module, or within an XPath 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.

deprecated

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.

dynamic error

An error that is not capable of detection until a source document is being transformed is referred to as a dynamic error.

dynamic evaluation feature

A processor that claims conformance with the dynamic evaluation featuremust evaluate the xsl:evaluate function as described in this specification.

eclipsed

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.

effective value

The effective value of an attribute or text node in the stylesheet is the value after any required expansion or normalization.

effective version

The effective version of an element in a stylesheet module or package manifest is the decimal value of the [xsl:]version attribute (see 3.4 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.

embedded stylesheet module

A stylesheet module whose outermost element is the child of a non-XSLT element in a host document is referred to as an embedded stylesheet module. See 3.12 Embedded Stylesheet Modules.

enclosing mode

A mode declared by an xsl:mode declaration that has one or more contained xsl:template declarations is referred to as an enclosing mode.

EQName

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.

expanded QName

An expanded QName is a value in the value space of the xs:QName datatype as defined in the XDM data model (see [XDM 3.04.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.

explicit default

An explicit default for a parameter is indicated by the presence of either a select attribute or a non-empty sequence constructor.

explicitly mandatory

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.

expression

Within this specification, the term XPath expression, or simply expression, means a string that matches the production ExprXP defined in [XPath 4.0].

extension attribute

An element from the XSLT namespace may have any attribute not from the XSLT namespace, provided that the expanded QName (see [XPath 4.0]) of the attribute has a non-null namespace URI. These attributes are referred to as extension attributes.

extension function

An extension function is a named function introduced to the static or dynamic context by mechanisms outside the scope of this specification.

extension instruction

An extension instruction is an element within a sequence constructor that is in a namespace (not the XSLT namespace) designated as an extension namespace.

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.

final output state

The first of the two output states is called final output state. This state applies when instructions are writing to a final result tree.

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.

fixed namespace bindings

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.

focus

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.

focus-changing construct

A focus-changing construct is a construct that has one or more operands that are evaluated with a different focus from the parent construct.

focus-setting container

The focus-setting container of a construct C is the innermost focus-changing constructF (if one exists) such that C is directly or indirectly contained in a controlled operand of F. If there is no such construct F, then the focus-setting container is the containing declaration, for example an xsl:function or xsl:template element.

forwards compatible behavior

An element is processed with forwards compatible behavior if its effective version is greater than 4.0.

free-ranging

A free-ranging construct is any construct deemed free-ranging by the rules in this section (19 Streamability).

function definition

The term function definition is defined in [XPath 4.0] section Section 2.2.1 Static ContextXP. 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]

function parameter

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.

fundamental item type

There are 28 fundamental item types: the 7 node kinds defined in [XDM 3.04.0] (element, attribute, etc.), the 19 primitive atomic types defined in [XML Schema Part 2], plus the types fn(*) and xs:untypedAtomic. The fundamental item types are disjoint, and every item is an instance of exactly one of them.

general streamability rules

Many constructs share the same streamability rules. These rules, referred to as the general streamability rules, are defined here.

global context item

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

global variable

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.

grounded

Grounded: indicates that the value returned by the construct does not contain nodes from the streamed input document

group

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.

grouping key

If either of 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.

guaranteed-streamable

A guaranteed-streamable construct is a construct that is declared to be streamable and that follows the particular rules for that construct to make streaming possible, as defined by the analysis in this specification.

higher-order operand

Whether or not the operand is higher-order. For this purpose an operand O of a construct C is higher-order if the semantics of C potentially require O to be evaluated more than once during a single evaluation of C.

high priority package location

A xsl:package-location without the attribute is-priority, or with is-priority set to true is a high priority package location.

homonymous

Two components are said to be homonymous if they have the same symbolic identifier.

identical (types)

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 Section 3.3.1 Subtypes of Sequence TypesXP.

immediate result

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.

implementation

A specific product that performs the functions of an XSLT processor is referred to as an implementation.

implementation-defined

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.

implementation-dependent

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.

implicit default

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.

implicitly mandatory

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.

import precedence

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.

import tree

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.

initial function

A stylesheet may be evaluated by calling a named stylesheet function, referred to as the initial function.

initial item

For each group, the item within the group that is first in population order is known as the initial item of the group.

initial match selection

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.

initial mode

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.

initial named template

A stylesheet may be evaluated by selecting a named template to be evaluated; this is referred to as the initial named template.

initial sequence

The sequence to be sorted is referred to as the initial sequence.

initial setting

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

in-scope schema component

The schema components that may be referenced by name in a package are referred to as the in-scope schema components.

inspection

An operand usage of inspection indicates that the construct accesses properties of a supplied node that are available without reading its subtree.

instruction

An instruction is either an XSLT instruction or an extension instruction.

invocation construct

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.

key

A key is defined as a set of xsl:key declarations in the same package that share the same name.

key specifier

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.

lexical QName

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.

library package

Every package within a stylesheet, other than the top-level package, is referred to as a library package.

literal namespace URI

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.

literal result element

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.2 Extension Instructions) is classified as a literal result element.

local variable

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.

low priority package location

A xsl:package-location with is-priority set to false is a low priority package location.

match type

The match type of a pattern is the most specific U-type that is known to match all items that the pattern can match.

merge activation

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.

merge input sequence

A merge input sequence is an arbitrary sequenceDM30DM of items which is already sorted according to the merge key specification for the corresponding merge source definition.

merge key component

A merge key component specifies one component of a merge key specification; it corresponds to a single xsl:merge-key element in the stylesheet.

merge key specification

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.

merge key value

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.

merge source 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.

mode

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.

mode 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.

motionless

A motionless construct is any construct deemed motionless by the rules in this section (19 Streamability).

named template

Templates can be invoked by name. An xsl:template element with a name attribute defines a named template.

namespace fixup

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.

native namespace bindings

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 3.04.0].

navigation

An operand usage of navigation indicates that the construct may navigate freely from the supplied node to other nodes in the same tree, in a way that is not constrained by the streamability rules.

node pattern

A node pattern uses a subset of the syntax for path expressions, and is defined to match a node if the corresponding path expression would select the node. Node patterns may also be formed by combining other patterns using union, intersection, and difference operators.

non-contextual function call

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 calls[TERMDEF dt-dynamic-function-invocation IN XP40]dynamic function invocationsXP, (that is calls to function items as permitted by XPath 3.0). 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.

non-positional predicate

A predicate is a non-positional predicate if it satisfies both of the following conditions:

  1. The predicate does not contain a function call or named function reference to any of the following functions, unless that call or reference occurs within a nested predicate:

    1. position

    2. last

    3. function-lookup.

    Note:

    The exception for nested predicates is there to ensure that patterns such as match="p[@code = $status[last()]] are not disqualified.

  2. The expression immediately contained in the predicate is a non-numeric expression. An expression is non-numeric if the intersection of its static type (see 19.1 Determining the Static Type of a Construct) with U{xs:decimal, xs:double, xs:float} is U{}.

non-schema-aware processor

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.

operand

In an actual instance of a construct, there will be a number of operands. Each operand is itself a construct; the construct tree can be defined as the transitive relation between constructs and their operands.

operand role

For every construct kind, there is a set of zero or more operand roles.

operand usage

The operand usage. This gives information, in the case where the operand value contains nodes, about how those nodes are used. The operand usage takes one of the values absorption, inspection, transmission, or navigation.

order of first appearance

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.

output definition

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.

output state

Each instruction in the stylesheet is evaluated in one of two possible output states: final output state or temporary output state.

override

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.

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.

package manifest

The content of the xsl:package element is referred to as the package manifest

parameter

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.

pattern

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.

picture string

The picture string is the string supplied as the second argument of the format-number function.

place marker

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.

population

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.

population order

The population is treated as a sequence; the order of items in this sequence is referred to as population order.

portion

The integer literals and the optional NamePart within the version number are referred to as the portions of the version number.

posture

The posture of the expression. This captures information about the way in which the streamed input document is positioned on return from evaluating the construct. The posture takes one of the values climbing, striding, crawling, roaming, or grounded.

potentially consuming

An operand is potentially consuming if at least one of the following conditions applies:

  1. The operand’s adjusted sweepS′ is consuming.

  2. The operand usage is transmission and the operand is not grounded.

predicate pattern

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.

principal result

A principal result: this can be any sequence of items (as defined in [XDM 3.04.0]).

principal stylesheet module

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.11.2 Stylesheet Inclusion and 3.11.3 Stylesheet Import.

priority

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.7 Default Priority for Template Rules.

priority package location

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.

processing order

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.

processor

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.

raw result

The result of invoking the selected component, after any required conversion to the declared result type of the component, is referred to as the raw result.

reference binding

The process of identifying the component to which a symbolic reference applies (possibly chosen from several homonymous alternatives) is called reference binding.

required type

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.

reserved namespace

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.

result tree

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.

roaming

Roaming: indicates that the nodes returned by an expression could be anywhere in the tree, which inevitably means that the construct cannot be evaluated using streaming.

scanning expression

A RelativePathExpr is a scanning expression if and only if it is syntactically equivalent to some motionlesspattern.

schema-aware XSLT processor

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.

schema component

Type definitions and element and attribute declarations are referred to collectively as schema components.

schema instance namespace

The schema instance namespacehttp://www.w3.org/2001/XMLSchema-instance, with conventional prefix xsi, is used as defined in [XML Schema Part 1]

schema namespace

The schema namespacehttp://www.w3.org/2001/XMLSchema, with conventional prefix xs, is used as defined in [XML Schema Part 1]

secondary result

Zero or more secondary results: each secondary result can be any sequence of items (as defined in [XDM 3.04.0]).

sequence constructor

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.

SequenceType

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].

serialization

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.

serialization error

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.

serialization feature

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.

shadows

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.

simplified stylesheet

A simplified stylesheet, which is a subtree rooted at a literal result element, as described in 3.8 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.8 Simplified Stylesheet Modules.

singleton focus

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).

snapshot

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.

sorted sequence

The sequence after sorting as defined by the xsl:sort elements is referred to as the sorted sequence.

sort key component

Within a sort key specification, each xsl:sort element defines one sort key component.

sort key specification

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.

sort key value

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.

source tree

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.

stable

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.

standard attributes

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.

standard error 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.

standard function namespace

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.

standard stylesheet module

A standard stylesheet module, which is a subtree rooted at an xsl:stylesheet or xsl:transform element.

static error

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.

static expression

A static expression is an XPath expression whose value must be computed during static analysis of the stylesheet.

static parameter

A static variable declared using an xsl:param element is referred to as a static parameter.

static type

The static type of a construct is such that all values produced by evaluating the construct will conform to that type. The static type of a construct comprises a U-type and a cardinality. A cardinality is a range of integers (from min to max).

static variable

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.

streamability category

Stylesheet functions belong to one of a number of streamability categories: the choice of category characterizes the way in which the function handles streamed input.

streamable mode

A streamable mode is a mode that is declared in an xsl:mode declaration with the attribute streamable="yes".

streamed document

A streamed document is a source tree that is processed using streaming, that is, without constructing a complete tree of nodes in memory.

streamed node

A streamed node is a node in a streamed document.

streaming

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.

streaming feature

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-streamable according to this specification.

streaming parameter

The first parameter of a declared-streamablestylesheet function is referred to as a streaming parameter.

striding

Striding: indicates that the result of a construct contains a sequence of streamed nodes, in document order, that are peers in the sense that none of them is an ancestor or descendant of any other.

string value

The term string value is defined in [XDM 4.0] section Section 5.137.5.12 string-value Accessor DM30. 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.

stylesheet

A stylesheet consists of one or more packages: specifically, one top-level package and zero or more library packages.

stylesheet function

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).

stylesheet level

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.

stylesheet module

A package consists of one or more stylesheet modules, each one forming all or part of an XML document.

stylesheet parameter

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.

supplied value

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.

sweep

Every construct has a sweep, which is a measure of the extent to which the current position in the input stream moves during the evaluation of the expression. The sweep is one of: motionless, consuming, or free-ranging .

symbolic identifier

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.

symbolic reference

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.

tail position

An instructionJ is in a tail position within a sequence constructorSC if it satisfies one of the following conditions:

target expression

The string that results from evaluating the expression in the xpath attribute is referred to as the target expression.

target namespace URI

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.

template

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.

template parameter

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.

template rule

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.

temporary output state

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.

temporary tree

The term temporary tree means any tree that is neither a source tree nor a final result tree.

text value template

In a text node that is designated as a text value template, expressions can be used by surrounding each expression with curly brackets ({}).

top-level

An element occurring as a child of an xsl:package, xsl:stylesheet, xsl:transform, or xsl:override element is called a top-level element.

top-level package

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.5.2 Dependencies between Packages.

transmission

An operand usage of transmission indicates that the construct will (potentially) return a supplied node as part of its result to the calling construct (that is, to its parent in the construct tree).

traversal

A traversal of a tree is a sequence of traversal events.

traversal-event

a traversal event (shortened to event in this section) is a pair comprising a phase (start or end) and a node.

tree

The term tree is used (as in [XDM 3.04.0]) to refer to the aggregate consisting of a parentless node together with all its descendant nodes, plus all their attributes and namespaces.

tunnel parameter

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.

type-adjusted posture and sweep

The type-adjusted posture and sweep of a construct C, with respect to a type T, are the posture and sweep established by applying the general streamability rules to a construct D whose single operand is the construct C, where the operand usage of C in D is the type-determined usage based on the required type T.

type annotation

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 Section 5.147.5.13 type-name Accessor DM30.

type-determined usage

The type-determined usage of an operand is as follows: if the required type (ignoring occurrence indicator) is fn(*) or a subtype thereof, then inspection; if the required type (ignoring occurrence indicator) is an atomic or union type, then absorption; otherwise navigation.

typed value

The term typed value is defined in [XDM 4.0] section Section 5.157.5.14 typed-value Accessor DM30. 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.

type error

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.

type pattern

A type pattern can be written as type(T) (where T is an ItemTypeXP followed by zero or more predicates in square brackets, and it matches any item of type T which each of the predicates evaluates to true.

unnamed mode

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.

URI Reference

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].

use

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.

user-defined data element

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.

U-type

A U-type is a set of fundamental item types.

vacuous

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 an empty sequence or a sequence consisting entirely of vacuous items.

value

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 3.04.0].

value template

Collectively, attribute value templates and text value templates are referred to as value templates.

variable

The xsl:variable element declares a variable, which may be a global variable or a local variable.

variable-binding element

The two elements xsl:variable and xsl:param are referred to as variable-binding elements.

visibility

The visibility of a component is one of: private, public, abstract, final, or hidden.

whitespace text node

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) ).

XML namespace

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.

XPath 1.0 compatibility mode

The term XPath 1.0 compatibility mode is defined in [XPath 4.0] section Section 2.2.1 Static ContextXP. 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.

XSLT 1.0 behavior

An element in the stylesheet is processed with XSLT 1.0 behavior if its effective version is equal to 1.0.

XSLT 1.0 compatibility feature

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.9 Backwards Compatible Processing.

XSLT 2.0 behavior

An element is processed with XSLT 2.0 behavior if its effective version is equal to 2.0.

XSLT 3.0 behavior

An element is processed with XSLT 3.0 behavior if its effective version is equal to 3.0.

XSLT element

An XSLT element is an element in the XSLT namespace whose syntax and semantics are defined in this specification.

XSLT instruction

An XSLT instruction is an XSLT element whose syntax summary in this specification contains the annotation <!-- category: instruction -->.

XSLT namespace

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.

D Summary of Error Conditions (Non-Normative)

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

ERR XTSE0010

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.

ERR XTSE0020

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.

ERR XTSE0080

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.

ERR XTSE0085

It is a static error to use a reserved namespace in the name of any 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.

ERR XTSE0090

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.

ERR XTSE0110

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].

ERR XTSE0120

An xsl:stylesheet, xsl:transform, or xsl:package element must not have any text node children.

ERR XTSE0122

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.

ERR XTSE0125

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.

ERR XTSE0130

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.

ERR XTSE0165

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.

ERR XTSE0170

An xsl:include element must be a top-level element.

ERR XTSE0190

An xsl:import element must be a top-level element.

ERR XTSE0210

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.

ERR XTSE0215

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.

ERR XTSE0220

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.

ERR XTSE0260

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.

ERR XTSE0265

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.

ERR XTSE0270

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).

ERR XTSE0280

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.

ERR XTSE0340

Where an attribute is defined to contain a pattern, it is a static error if the pattern does not match the production Pattern40.

ERR XTSE0350

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.

ERR XTSE0370

It is a static error if an unescaped right curly bracket occurs in a fixed part of a value template.

ERR XTSE0500

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.

ERR XTSE0530

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.

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.

ERR XTSE0550

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.

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.

ERR XTSE0620

It is a static error if a variable-binding element has a select attribute and has non-empty content.

ERR XTSE0630

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.

ERR XTSE0650

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.5.4.5 Binding References to Components.

ERR XTSE0660

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.

ERR XTSE0670

It is a static error if two or more sibling xsl:with-param elements have name attributes that represent the same expanded QName.

ERR XTSE0680

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.

ERR XTSE0690

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.)

ERR XTSE0710

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.

ERR XTSE0730

If an xsl:attribute set element specifies streamable="yes" then every attribute set referenced in its use-attribute-sets attribute (if present) must also specify streamable="yes".

ERR XTSE0740

It is a static error if a stylesheet function has a name that is in no namespace.

ERR XTSE0760

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".

ERR XTSE0761

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".

ERR XTSE0769

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.

ERR XTSE0770

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.

ERR XTSE0805

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.

ERR XTSE0808

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.

ERR XTSE0809

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.

ERR XTSE0810

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.

ERR XTSE0812

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.

ERR XTSE0840

It is a static error if the select attribute of the xsl:attribute element is present unless the element has empty content.

ERR XTSE0870

It is a static error if the select attribute of the xsl:value-of element is present when the content of the element is non-empty.

ERR XTSE0880

It is a static error if the select attribute of the xsl:processing-instruction element is present unless the element has empty content.

ERR XTSE0910

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.

ERR XTSE0940

It is a static error if the select attribute of the xsl:comment element is present unless the element has empty content.

ERR XTSE0975

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.

ERR XTSE1015

It is a static error if an xsl:sort element with a select attribute has non-empty content.

ERR XTSE1017

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.

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.

ERR XTSE1060

It is a static error if the current-group function is used within a pattern.

ERR XTSE1070

It is a static error if the current-grouping-key function is used within a pattern.

ERR XTSE1080

These five attributes [the group-by, group-adjacent, group-starting-with, group-ending-with, and split-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.

ERR XTSE1090

It is a static error to specify the collation attribute or the composite attribute if neither the group-by attribute nor group-adjacent attribute is specified.

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.

ERR XTSE1205

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.

ERR XTSE1210

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.

ERR XTSE1220

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.

ERR XTSE1222

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.

ERR XTSE1290

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.

ERR XTSE1295

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.

ERR XTSE1300

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.

ERR XTSE1430

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.

ERR XTSE1505

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.

ERR XTSE1520

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. [XSLT 3.0 Erratum E20, bug 30234]

ERR XTSE1530

It is a static error if the value of the type attribute of an xsl:attribute instruction refers to a complex type definition

ERR XTSE1560

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.

ERR XTSE1570

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 [XSLT and XQuery Serialization][xslt-xquery-serialization-30] and must be one of xml, html, xhtml, text, json, or adaptive.

ERR XTSE1580

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.

ERR XTSE1590

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.

ERR XTSE1600

It is a static error if a character map references itself, directly or indirectly, via a name in the use-character-maps attribute.

ERR XTSE1650

A non-schema-aware processormust raise a static error if a package includes an xsl:import-schema declaration.

ERR XTSE1660

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)").

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 XTSE3000

It is a static error if after evaluating each xsl:package-location declaration and implementation-defined package location, no priority package location is found.

ERR XTSE3002

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.

ERR XTSE3003

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.

ERR XTSE3004

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.

ERR XTSE3005

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.

ERR XTSE3008

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.

ERR XTSE3010

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.)

ERR XTSE3020

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.

ERR XTSE3022

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.

ERR XTSE3025

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.

ERR XTSE3030

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.

ERR XTSE3032

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.

ERR XTSE3040

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.

ERR XTSE3050

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.

ERR XTSE3051

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.

ERR XTSE3055

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.

ERR XTSE3058

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.

ERR XTSE3060

It is a static error if the component referenced by an xsl:override declaration has visibility other than public or abstract

ERR XTSE3070

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.

ERR XTSE3075

It is a static error to use the component reference xsl:original when the overridden component has visibility="abstract".

ERR XTSE3080

It is a static error if a top-level package (as distinct from a library package) contains components whose visibility is abstract.

ERR XTSE3085

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.

ERR XTSE3087

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

ERR XTSE3088

It is a static error if the as attribute is present [on the xsl:context-item element] when use="absent" is specified.

ERR XTSE3089

It is a static error if the as attribute is present [on the xsl:global-context-item element] when use="absent" is specified.

ERR XTSE3105

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.

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.

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.

ERR XTSE3150

It is a static error if the select attribute of the xsl:catch element is present unless the element has empty content.

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.

ERR XTSE3190

It is a static error if two sibling xsl:merge-source elements have the same name.

ERR XTSE3195

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. [XSLT 3.0 Erratum E40, bugs 30265 and 30378].

ERR XTSE3200

It is a static error if an xsl:merge-key element with a select attribute has non-empty content.

ERR XTSE3300

It is a static error 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-streamable accumulator visible in the containing package.

ERR XTSE3350

It is a static error 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.

ERR XTSE3355

It is a static error for a an xsl:accumulator-rule element to specify capture="yes" unless it also specifies phase="end".

ERR XTSE3430

It is a static error if a package contains a construct that is declared to be streamable but which is not guaranteed-streamable, unless the user has indicated that the processor is to handle this situation by processing the stylesheet without streaming or by making use of processor extensions to the streamability rules where available.

ERR XTSE3440

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.

ERR XTSE3450

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.

ERR XTSE3460

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.)

ERR XTSE3470

It is a static error if the current-merge-group function is used within a pattern.

ERR XTSE3500

It is a static error if the current-merge-key-array or current-merge-key function is used within a pattern.

ERR XTSE3520

It is a static error if a parameter to xsl:iterate is implicitly mandatory.

ERR XTSE4005

It is a static error if an xsl:mode declaration with one or more xsl:template children has no name attribute.

ERR XTSE4010

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.

ERR XTSE4015

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.

ERR XTSE4020

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.

ERR XTSE4025

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.

ERR XTSE4030

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.

ERR XTSE4035

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.

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 Section 3.3.1 Subtypes of Sequence TypesXP.

ERR XTSE4045

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.

ERR XTSE4050

It is a static error if the names of the fields in an xsl:record-type declaration are not distinct.

ERR XTSE4051

It is a static error if an xsl:field element has a default attribute unless it specifies required="no".

Type errors

ERR XTDE0450

It is a type error if the result sequence contains a function item.

ERR XTTE0505

It is a type error if the result of evaluating the sequence constructor cannot be coerced to the required type.

ERR XTTE0510

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.

ERR XTTE0570

It is a type error if the supplied value of a variable cannot be converted to the required type.

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. [XSLT 3.0 Erratum E22, bug 30238].

ERR XTTE0780

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.

ERR XTTE0945

It is a type error to use the xsl:copy instruction with no select attribute when the context item is absent.

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.

ERR XTTE0990

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.

ERR XTTE1000

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.

ERR XTTE1100

It is a type error if the result of evaluating the group-adjacent expression is an empty sequence or a sequence containing more than one item, unless composite="yes" is specified.

ERR XTTE1510

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.

ERR XTTE1512

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.

ERR XTTE1515

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.

ERR XTTE1535

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.

ERR XTTE1540

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.

ERR XTTE1545

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.

ERR XTTE1550

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.

ERR XTTE1555

It is a type error if, when validating a document node, document-level constraints (such as ID/IDREF constraints) are not satisfied.

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.

ERR XTTE3090

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.

ERR XTTE3100

It is a type error if an xsl:apply-templates instruction in a particular mode selects an element or attribute whose type is xs:untyped or xs:untypedAtomic when the typed attribute of that mode specifies the value yes, strict, or lax.

ERR XTTE3110

It is a type error if an xsl:apply-templates instruction in a particular mode selects an element or attribute whose type is anything other than xs:untyped or xs:untypedAtomic when the typed attribute of that mode specifies the value no.

ERR XTTE3165

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()*).

ERR XTTE3170

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.

ERR XTTE3180

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.

ERR XTTE3375

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(*)*.

ERR XTTE4045

A type error is raised if the result of evaluating the select expression or contained sequence constructor of an xsl:array instruction is not an instance of one of the following sequence types: empty-sequence(), xs:anyAtomicType+, node()+, or record(value as item()*, *)+. As with other type errors, the error may be raised statically if it can be detected statically.

Dynamic errors

ERR XTDE0030

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.

ERR XTDE0040

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.

ERR XTDE0041

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.

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).

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).

ERR XTDE0050

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.

ERR XTDE0160

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.

ERR XTDE0290

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.

ERR XTDE0410

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.

ERR XTDE0420

It is a dynamic error if the sequence used to construct the content of a document node contains a namespace node or attribute node.

ERR XTDE0430

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).

ERR XTDE0440

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).

ERR XTDE0540

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.

ERR XTDE0555

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.

ERR XTDE0560

It is a dynamic error if xsl:apply-imports or xsl:next-match is evaluated when the current template rule is absent.

ERR XTDE0565

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.

ERR XTDE0640

In general, a circularity in a stylesheet is a dynamic error.

ERR XTDE0700

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.

ERR XTDE0820

It is a dynamic error if the effective value of the name attribute [of the xsl:element instruction] is not a lexical QName.

ERR XTDE0830

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.

ERR XTDE0835

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/.

ERR XTDE0850

It is a dynamic error if the effective value of the name attribute [of an xsl:attribute instruction] is not a lexical QName.

ERR XTDE0855

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.

ERR XTDE0860

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.

ERR XTDE0865

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/.

ERR XTDE0890

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.

ERR XTDE0905

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/.

ERR XTDE0920

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.

ERR XTDE0925

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.

ERR XTDE0930

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.

ERR XTDE0980

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).

ERR XTDE1030

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 for which the result of the XPath lt operator is an error. If the processor is able to detect the error statically, it may optionally raise it as a static error.

ERR XTDE1035

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.

ERR XTDE1061

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.

ERR XTDE1071

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.

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].)

ERR XTDE1140

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.

ERR XTDE1145

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.

ERR XTDE1160

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).

ERR XTDE1162

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.

ERR XTDE1260

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.

ERR XTDE1262

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.

ERR XTDE1270

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.

ERR XTDE1360

If the current function is evaluated within an expression that is evaluated when the context item is absent, a dynamic error occurs.

ERR XTDE1370

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.

ERR XTDE1380

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.

ERR XTDE1390

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.

ERR XTDE1400

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.

ERR XTDE1420

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.

ERR XTDE1425

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.

ERR XTDE1428

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.

ERR XTDE1440

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.

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.

ERR XTDE1460

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.

ERR XTDE1480

It is a dynamic error to evaluate the xsl:result-document instruction in temporary output state.

ERR XTDE1490

It is a dynamic error for a transformation to generate two or more final result trees with the same URI.

ERR XTDE1500

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.

ERR XTDE1665

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.

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 XTDE3052

It is a dynamic error if an invocation of an abstract component is evaluated.

ERR XTDE3086

It is a dynamic error if an xsl:global-context-item declaration specifies use="required", and no global context item is supplied. [XSLT 3.0 Erratum E6, bug 30173].

ERR XTSE3155

It is a static error if an xsl:function element with no xsl:param children has a streamability attribute with any value other than unclassified.

ERR XTDE3160

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).

ERR XTDE3175

It is a dynamic error if an xsl:evaluate instruction is evaluated when use of xsl:evaluate has been statically or dynamically disabled.

ERR XTDE3340

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.

ERR XTDE3350

It is a dynamic error to call the accumulator-before or accumulator-after function when there is no context item.

ERR XTTE3360

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.

ERR XTDE3362

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.

ERR XTDE3365

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.

ERR XTDE3400

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.

ERR XTDE3480

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.

ERR XTDE3490

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.

ERR XTDE3510

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.

ERR XTDE3530

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".

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.

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.

E Pattern Syntax Summary (Non-Normative)

This appendix gives the grammar for XSLT patterns. The top-level rule for patterns is Pattern40.

This is an extension of the grammar for XPath expressions. The extended BNF notation is explained at [XPath 4.0] section Section A.1.1 NotationXP.

Productions that are identical to their counterparts in XPath 4.0 are suffixed XP and link to the corresponding production in the XPath 4.0 specification. Productions whose names end with P are restrictions of the corresponding XPath production: for example, ArgumentListP is a restricted form of the XPath production ArgumentList.

F Checklist of Implementation-Defined Features (Non-Normative)

This appendix provides a summary of XSLT language features whose effect is explicitly implementation-defined. The conformance rules (see 27 Conformance) require vendors to provide documentation that explains how these choices have been exercised.

The implementation-defined features are grouped into categories for convenience.

F.5 Dependencies

When this specification refers normatively to other specifications, it generally gives implementations freedom to decide (within constraints) which version of the referenced specification should be used. Specifically:

  1. It is implementation-defined which versions and editions of XML and XML Namespaces (1.0 and/or 1.1) are supported. (See 4.1 XML Versions)

  2. It is implementation-defined which versions of XML, HTML, and XHTML are supported in the version attribute of the xsl:output declaration. (See 26.2 Serialization parameters)

  3. It is implementation-defined whether (and if so how) an XSLT 3.0 processor is able to work with versions of [XSLT and XQuery Serialization][xslt-xquery-serialization-30] later than 3.1. (See 27.3 Serialization Feature)

G Summary of Available Functions (Non-Normative)

G.1 Function Classification

The functions available for use within an XSLT stylesheet can be classified based firstly, on where the function is defined, and secondly, on where it can be used. Specifically, the set of functions available is slightly different for :

The categories are listed in the following table:

Categories of Function, and their Availability
CategoryDefined where?Available where?Notes
User-defined functionsDefined using xsl:function declarations in the stylesheetR, DFunctions are private by default; private functions can be referenced only within the package where they are declared (and not in xsl:evaluate expressions).
Constructor functions for built-in types[Functions and Operators 4.0] section Section 22 Constructor functionsFOR, S, DThese functions are all in the namespace conventionally associated with the prefix xs. The semantics of a constructor function are identical to the semantics of a cast expression.
Constructor functions for user-defined types[Functions and Operators 4.0] section Section 22 Constructor functionsFOR, D (if schema-aware="yes")This category includes a function for every named user-defined simple type in an imported schema; the function allows the conversion of strings and certain other values to instances of the user-defined type.
Functions defined in XPath 4.0[Functions and Operators 4.0]R, S, DIncludes functions in the namespaces conventionally referred to be the prefixes fn and math.
Functions defined in XSLT 4.0This specificationR, S (see note), DSee G.2 List of XSLT-defined functions. There is an overlap with the set of functions defined in XPath 4.0. The functions available in static expressions are: element-available, function-available, type-available, available-system-properties, and system-property.
Extension functionsImplementation-defined: see 24.1 Extension Functions.R, S, DAvailability is implementation-defined

J Incompatibilities with XSLT 3.0 (Non-Normative)

This section lists all known incompatibilities with XSLT 3.0, that is, situations where a stylesheet that is error-free according to the XSLT 3.0 specification and where all elements have an effective version of 3.0 or less, will produce different results depending on whether it is run under an XSLT 3.0 processor or an XSLT 4.0 processor.

  1. The rules for comparing values in xsl:for-each-group now reference the rules for distinct-values, which have themselves changed to be compatible with fn:atomic-equal. This change eliminates the intransitivity in the previous specification, which meant that in edge cases involving rounding of numeric values of different types, two items in different groups could compare equal. Any change in behavior is confined to this edge case.

  2. The rules for matching nodes against patterns using the intersect and except operators have changed to deliver a more intuitive result.

  3. The rules for comparing values in keys have changed, to align with the rules for maps. The changes affect edge cases involving rounding of numeric values of different types, and the comparison of date/time values with and without timezones.

  4. In previous versions, a template rule whose match pattern was a union pattern and that had no explicity priority was treated as equivalent to a set of template rules, one for each alternative in the union, each potentially with different default priority. This rule has not been carried forward into XSLT 4.0: instead, the priority of the rule is taken as being the highest priority of any of the alternatives.

  5. In XSLT 4.0, an xsl:apply-imports or xsl:next-match instruction automatically passes on the values of any non-tunnel parameters that were present in its own invocation. This means that the template rule invoked by xsl:apply-imports or xsl:next-match, if it declares a default value for such a parameter, will take the implicitly-supplied value in preference to the default value.

    This change in the specification applies only if the effective version of the xsl:apply-imports or xsl:next-match is 4.0 or greater. This means that 3.0 behavior can be retained by adding the attribute version="3.0" to the instruction, or to some ancestor element (for example, the xsl:stylesheet or xsl:transform element).

This specification also corrects a number of errors and omissions in XSLT 3.0, in a way that might create incompatibilities for some processors, depending on how they interpreted the XSLT 3.0 specification:

  1. XSLT 3.0 (and earlier releases) did not fully define the evaluation context for the default values of template parameters. For example, if the default value of a parameter of a template rule invoked xsl:next-match, it was not specified whether the current template rule should be the calling template or the called template. This omission has been corrected.

  2. Where different packages import different schemas, the specification is now more prescriptive about which schema is used for validation. The rules may differ from the conventions adopted by implementations of XSLT 3.0.

  3. XSLT 3.0 failed to specify a default value for the serialization parameter indent where the serialization method is json or adaptive. XSLT 4.0 specifies a default value of no.

See also [XPath 4.0], [Functions and Operators 4.0], and [XSLT and XQuery Serialization 4.0] for incompatibilities in other related specifications that may affect XSLT stylesheets.