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 30 January2 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, but also offering support for other data formats including JSON, HTML, and CSV.

XSLT 4.0 is a revised version of the XSLT 3.0 Recommendation [XSLT 3.0] published on 8 June 2017. Changes are presented in 1.2 What’s New in XSLT 4.0?.

XSLT 4.0 is designed to be used in conjunction with XPath 4.0, which is defined in [XPath 4.0]. XSLT shares the same data model as XPath 4.0, which is defined in [XDM 4.0], and it uses the library of functions and operators defined in [Functions and Operators 4.0]. XPath 4.0 and the underlying function library introduce a number of enhancements, for example the availability of union and record types.

This document contains hyperlinks to specific sections or definitions within other documents in this family of specifications. These links are indicated visually by a superscript identifying the target specification: for example XP for XPath 4.0, DM for the XDM data model version 4.0, FO for Functions and Operators version 4.0, SG for XSLT Streaming version 4.0.

An optional feature of the XSLT language is support for streamed transformations. The XSLT 4.0 specification has been modularized so that streaming is now described in a separate specification document. This has been done in order to make the specifications more manageable, both for editors and readers: it does not alter the status of streaming as an optional feature, available in some processors and not others.

Status of this Document

This section describes the status of this document at the time of its publication. Other documents may supersede this document.

This document is a working draft developed and maintained by a W3C Community Group, the XQuery and XSLT Extensions Community Group unofficially known as QT4CG (where "QT" denotes Query and Transformation). This draft is work in progress and should not be considered either stable or complete. Standard W3C copyright and patent conditions apply.

The community group welcomes comments on the specification. Comments are best submitted as issues on the group's GitHub repository.

The community group maintains two extensive test suites, one oriented to XQuery and XPath, the other to XSLT. These can be found at qt4tests and xslt40-test respectively. New tests, or suggestions for correcting existing tests, are welcome. The test suites include extensive metadata describing the conditions for applicability of each test case as well as the expected results. They do not include any test drivers for executing the tests: each implementation is expected to provide its own test driver.

Dedication

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


2 Concepts

2.2 Notation

[Definition: An XSLT element is an element in the XSLT namespace whose syntax and semantics are defined in this specification.] For a non-normative list of XSLT elements, see C Element Syntax Summary.

In this document the specification of each XSLT element is preceded by a summary of its syntax in the form of a model for elements of that element type. A full list of all these specifications can be found in C Element Syntax Summary. The meaning of the syntax summary notation is as follows:

  • An attribute that is required is shown with its name in bold. An attribute that may be omitted is shown with a question mark following its name.

  • An attribute that is deprecated is shown in a grayed font within square brackets.

  • The string that occurs in the place of an attribute value specifies the allowed values of the attribute. If this is surrounded by curly brackets ({...}), then the attribute value is treated as an attribute value template, and the string occurring within curly brackets specifies the allowed values of the result of evaluating the attribute value template. Alternative allowed values are separated by |. A quoted string indicates a value equal to that specific string. An unquoted, italicized name specifies a particular type of value.

    The types used, and their meanings, are as follows:

    boolean

    One of the strings "yes", "true", or "1" to indicate the value true, or one of the strings "no", "false", or "0" to indicate the value false. Note: the values are synonyms; where this specification uses a phrase such as “If required='yes' is specified ...” this is to be interpreted as meaning “If the attribute named required is present, and has the value yes, true, or 1 (after stripping leading and trailing whitespace) ...”.

    string

    Any string.

    expression

    An XPath expression.

    pattern

    A pattern as described in 6.3 Patterns.

    item-type

    An ItemTypeXP as defined in the XPath 4.0 specification.

    sequence-type

    A SequenceTypeXP as defined in the XPath 4.0 specification.

    uri; uris

    A URI, for example a namespace URI or a collation URI; a whitespace-separated list of URIs.

    qname

    A lexical QName as defined in 5.1.1 Qualified Names.

    eqname; eqnames

    An EQName as defined in 5.1.1 Qualified Names; a whitespace-separated list of EQNames.

    token; tokens

    A string containing no significant whitespace; a whitespace-separated list of such strings.

    nmtoken; nmtokens

    A string conforming to the XML schema rules for the type xs:NMTOKEN; a whitespace-separated list of such strings.

    char

    A string comprising a single Unicode character.

    language

    A string in the value space of xs:language, or a zero-length string.

    integer

    An integer, that is, a string that is castable to the schema type xs:integer.

    decimal

    A decimal value, that is, a string that is castable to the schema type xs:decimal.

    ncname; ncnames

    An unprefixed name: a string that is castable to the schema type xs:NCName; a whitespace-separated list of such strings.

    prefix; prefixes

    An xs:NCName representing a namespace prefix, which must be in scope for the element on which it appears; a whitespace-separated list of such strings.

    id

    An xs:NCName used as a unique identifier for an element in the containing XML document.

    Except where the set of allowed values of an attribute is specified using the italicized name string or char, leading and trailing whitespace in the attribute value is ignored. In the case of an attribute value template, this applies to the effective value obtained when the attribute value template is expanded.

    XPath comments (delimited by (: ... :)) are permitted anywhere that inter-token whitespace is permitted in attributes whose type is given as expression, pattern, item-type, or sequence-type, and are not permitted in attributes of other types (other than within expressions enclosed by curly braces within an attribute value template).

  • If an attribute has a simple default value, this is shown between tortoise-shell brackets (for example 〔'no'〕). Where no default is shown, the consequence of omitting the attribute is explained in the prose narrative. Default values shown in the summary apply only where the attribute itself is applicable; if an attribute is not permitted to appear in the particular context, then its default value should be ignored. (For example, the stable attribute of xsl:sort is shown as having a default value of 'yes', but the attribute is allowed only on the first of a sequence of adjacent xsl:sort elements.) The quotation marks around a default value are not part of the value.

  • Unless the element is required to be empty, the model element contains a comment specifying the allowed content. The allowed content is specified in a way similar to an element type declaration in XML; sequence constructor means that any mixture of text nodes, literal result elements, extension instructions, and XSLT elements from the instruction category is allowed; other-declarations means that any mixture of XSLT elements from the declaration category is allowed, together with user-defined data elements.

  • The element is prefaced by comments indicating if it belongs to the instruction category or declaration category or both. The category of an element affects only whether it is allowed in the content of elements that allow a sequence constructor or other-declarations.

Example: Syntax Notation

This example illustrates the notation used to describe XSLT elements.

<!-- Category: instruction -->
<xsl:example-element
  select = expression
  debug? = boolean
  validation? = { "strict" | "lax" }〔strict〕 >
  <!-- Content: ((xsl:variable | xsl:param)*, xsl:sequence) -->
</xsl:example-element>

This example defines a (non-existent) element xsl:example-element. The element is classified as an instruction. It takes the following attributes:

  1. A mandatory select attribute, whose value is an XPath expression

  2. An optional debug attribute, whose value must be yes, true, or 1 to indicate true, or no, false, or 0 to indicate false.

  3. An optional validation attribute, whose value must be strict or lax; the curly brackets indicate that the value can be defined as an attribute value template, allowing a value such as validation="{ $val }", where the variableval is evaluated to yield "strict" or "lax" at run-time. The value strict in tortoise-shell brackets indicates the default value, if the attribute is not present.

The content of an xsl:example-element instruction is defined to be a sequence of zero or more xsl:variable and xsl:param elements, followed by an xsl:sequence element.

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

The rules in the element syntax summary (both for the element structure and for its attributes) apply to the stylesheet content after preprocessing as described in 3.123.11 Stylesheet Preprocessing.

[Definition: The effective value of an attribute or text node in the stylesheet is the value after any required expansion or normalization.]

More specifically, the effective value is the value after:

  • Expanding shadow attributes as described in 3.12.43.11.4 Shadow Attributes;

  • Expanding defaults (for example, if an xsl:message instruction has no terminate attribute, then the effective value of the terminate attribute is no);

  • Stripping ignored whitespace (for example, the effective value of a boolean attribute written as terminate=" no " is no);

  • Replacing synonyms (for example in boolean attributes, 1 and true are synonyms of yes);

  • Expanding attribute value templates and text value templates.

  • Applying rules from the static context: for example, the effective value of a collation attribute is the value after expanding a relative URI against the static base URI.

Attributes are validated as follows. These rules apply to the value of the attribute after removing leading and trailing whitespace.

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

Special rules apply if the construct appears in part of the stylesheet that is processed with forwards compatible behavior: see 3.9 Forwards Compatible Processing.

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

Note:

This specification includes a non-normative XML Schema for XSLT stylesheet modules (see H Schemas for XSLT 4.0 Stylesheets). The syntax summaries described in this section are normative.

XSLT defines a set of standard functions which are additional to those defined in [Functions and Operators 4.0]. A list of these functions appears in G.2 List of XSLT-defined functions. The signatures of these functions are described using the same notation as used in [Functions and Operators 4.0]. The names of many of these functions are in the standard function namespace.

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.12.33.11.3 Conditional Element Inclusion) and shadow attributes (see 3.12.43.11.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.10 Stylesheets and XML Schemas

Changes in 4.0 (next | previous)

  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.143.13 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.133.12 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. The data model (see [XDM 4.0]) requires that the processor has sufficient information about such types to correctly implement the semantics of the language, even though the schema has not been imported; it also requires that all schemas used by the processor in a given processing episode (for example, an XSLT transformation) should be consistent. For example, if a type annotation of a node is the simple type my:percentage, and a type named my:percentage appears in an imported schema, then they must be the same type.

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

3 Stylesheet Structure

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

3.3 Standard Attributes

Changes in 4.0 (next | previous)

  1. The standard attribute [xsl:]schema-role is introduced, to allow different parts of a stylesheet to use different schemas.   [Issue 451 PR 1819 18 February 2025]

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

These attributes may also appear on a literal result element, but in this case, to distinguish them from user-defined attributes, the names of the attributes are in the XSLT namespace. They are thus typically written as xsl:default-collation, xsl:default-mode, xsl:default-validation, xsl:exclude-result-prefixes, xsl:expand-text, xsl:extension-element-prefixes, xsl:use-when, xsl:version, or xsl:xpath-default-namespace.

It is recommended that all these attributes should also be permitted on extension instructions, but this is at the discretion of the implementer of each extension instruction. They may also be permitted on user-defined data elements, though they will only have any useful effect in the case of data elements that are designed to behave like XSLT declarations or instructions.

In the following descriptions, these attributes are referred to generically as [xsl:]version, and so on.

These attributes all affect the element they appear on, together with any elements and attributes that have that element as an ancestor. The two forms with and without the XSLT namespace have the same effect; the XSLT namespace is used for the attribute if and only if its parent element is not in the XSLT namespace.

In the case of [xsl:]default-collation, [xsl:]expand-text, [xsl:]schema-role, [xsl:]version, and [xsl:]xpath-default-namespace, the value can be overridden by a different value for the same attribute appearing on a descendant element. The effective value of the attribute for a particular stylesheet element is determined by the innermost ancestor-or-self element on which the attribute appears.

In an embedded stylesheet module, standard attributes appearing on ancestors of the outermost element of the stylesheet module have no effect.

In the case of [xsl:]exclude-result-prefixes and [xsl:]extension-element-prefixes the values are cumulative. For these attributes, the value is given as a whitespace-separated list of namespace prefixes, and the effective value for an element is the combined set of namespace URIs designated by the prefixes that appear in this attribute for that element and any of its ancestor elements. Again, the two forms with and without the XSLT namespace are equivalent.

The effect of the [xsl:]use-when attribute is described in 3.12.33.11.3 Conditional Element Inclusion.

Because these attributes may appear on any XSLT element, they are not listed in the syntax summary of each individual element. Instead they are listed and described in the entry for the xsl:stylesheet, xsl:transform, and xsl:package elements only. This reflects the fact that these attributes are often used on the outermost element of the stylesheet, in which case they apply to the entire stylesheet module or package manifest.

Note that the effect of these attributes does not extend to stylesheet modules referenced by xsl:include or xsl:import declarations, nor to packages referenced using xsl:use-package.

For the detailed effect of each attribute, see the following sections:

[xsl:]default-collation

see 3.6.2 The default-collation Attribute

[xsl:]default-mode

see 3.6.3 The default-mode Attribute

[xsl:]default-validation

see 25.4 Validation

[xsl:]exclude-result-prefixes

see 11.1.3 Namespace Nodes for Literal Result Elements

[xsl:]expand-text

see 5.6.2 Text Value Templates

[xsl:]extension-element-prefixes

see 24.3 Extension Instructions

[xsl:]schema-role

see 3.14.13.13.1 Multiple Schemas

[xsl:]use-when

see 3.12.33.11.3 Conditional Element Inclusion

[xsl:]version

see 3.8 Backwards Compatible Processing and 3.9 Forwards Compatible Processing

[xsl:]xpath-default-namespace

see 5.1.2 Unprefixed Lexical QNames in Expressions and Patterns

3.5 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 4.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.11 Embedded Stylesheet Modules.]

3.6 Stylesheet Element

Changes in 4.0 (next | previous)

  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.8 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.9 Forwards Compatible Processing).

The effect of the input-type-annotations attribute is described in 4.2.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 principal stylesheet module of the relevant package, and thus to gather information about all the global variables, templates, and functions available within the module being edited. This information can be used (for example) to enable auto-completion and error highlighting of the code as it is entered. Note that it may be inconvenient or misleading to use this attribute when the stylesheet module module is used as a shared component within multiple packages.

[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.12.13.11.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.6.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.6.1 The fixed-namespaces Attribute

Changes in 4.0 (next | previous)

  1. The xsl:stylesheet, xsl:transform, or xsl:package element may have a fixed-namespaces attribute making it easier to have the same namespace declarations in force throughout a stylesheet.   [Issue 369 PR 470 29 November 2023]

The fixed-namespaces attribute, if present, defines the fixed namespace bindings for a stylesheet module. The attribute may appear only on the outermost element of a stylesheet module (xsl:stylesheet, xsl:transform, or xsl:package). It is not available with simplified stylesheet modules.

If the fixed-namespaces attribute is present, then it defines the entire set of namespace bindings present in the static context of XPath expressions and patterns within the stylesheet, as well as other constructs where namespace prefixes are used in attribute and text nodes, such as the name attribute of declarations like xsl:function and xsl:variable, and as and type attributes referring to item types and schema types.

The value of the attribute is a whitespace-separated list of tokens, where each token contributes one or more namespace bindings to the fixed namespace bindings of the stylesheet module. Each token must be one of the following. If a token falls into more than one of these categories, then the first one that applies takes precedence.

  • The string #standard, which is equivalent to specifying xsl xml xs xsi fn math map array err. This has the effect of binding each of these namespace prefixes to the reserved namespace with which it is conventionally associated.

  • An NCName corresponding to one of the namespace prefixes present in the in-scope namespaces of the containing element node. This has the effect of adding the corresponding namespace binding to the fixed namespace bindings.

  • Any one of the strings xsl, xml, xs, xsi, fn, math, map, array, err. This has the effect of binding that particular namespace prefix to the reserved namespace with which it is conventionally associated, whether or not the native namespace bindings contain a binding for this prefix.

    Note:

    Including xml in the list has no effect, since the XML namespace will always be in scope anyway.

    If the namespace prefix is explicitly bound to a different namespace, for example xmlns:math="java:java.util.Math", then that binding takes precedence.

  • A string in the form prefix=uri, where prefix is an NCName and uri is a (non-empty) namespace URI: for example, xalan=http://xml.apache.org/xalan. This has the effect of binding the specified prefix to the specified URI.

  • A URI Reference identifying the location of an XML document whose namespace bindings are to be used. For example, ./package.xsl. A token is interpreted as a URI if it does not match any of the other possibilities listed above (which will be the case if it contains a "/" as in this example).

    The URI Reference is used to locate an XML document, in the same way as described for xsl:include and xsl:import in 3.10.1 Locating Stylesheet Modules. The resource that is retrieved may be any namespace well-formed XML document. The in-scope namespace bindings of the outermost element of this document are added to the fixed namespace bindings of the stylesheet module.

    Note:

    Such URIs cannot contain whitespace.

If different tokens in the fixed-namespaces attribute result in multiple bindings for the same namespace prefix, the last one wins.

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

The following observations apply when a fixed-namespaces attribute is present:

  • All expressions in the stylesheet module will have the same statically known namespacesXP in their static context. This means that all prefixes used in XPath expressions, patterns, and similar constructs must be declared at the top level.

  • Namespace prefixes used in element and attribute names in the stylesheet cannot be declared using this mechanism. Such prefixes must be bound using native namespace bindings. This also applies to namespace prefixes used in the [xsl:]exclude-result-prefixes and [xsl:]extension-element-prefixes attributes, and the stylesheet-prefix and result-prefix attributes of xsl:namespace-alias.

  • It is not an error for an element within a stylesheet module to rebind a prefix listed in the fixed-namespaces attribute to a different URI; however this rebinding has no effect on the static context of XPath expressions and other similar constructs within its scope.

  • The fixed-namespaces attribute has no effect on the interpretation of unprefixed names.

Note:

It is possible to use the fixed namespace bindings in other attributes of the xsl:stylesheet element, such as default-mode. It is also possible to use them in shadow attributes (see 3.12.43.11.4 Shadow Attributes).

It is possible for the fixed-namespaces attribute itself to be supplied as a shadow attribute (written with an underscore, _fixed-namespaces). It can then refer to static variables declared in an importing or including stylesheet module. This provides an alternative way of sharing common namespace bindings throughout a package.

Note:

The ability to fetch namespace bindings using a URI can be exploited in various ways:

  • Generally, the benefit is that it avoids repeating the same information in every stylesheet module, thereby reducing the amount of boilerplate code and keeping common information in a common place. This satisfies the DRY principle in software engineering: Don't Repeat Yourself.

  • The document identified by the URI may be a stylesheet module. One way to use the feature is to use the package manifest as the primary source for namespace bindings.

  • It is also possible to adopt the namespace bindings from a sample source document. For example, if it is known that the stylesheet is designed primarily to process documents whose first start tag takes the form:

    <w:document
      xmlns:wps="http://schemas.microsoft.com/office/word/2010/wordprocessingShape"
      xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
      xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main">

    then these three namespace bindings may conveniently be copied to the stylesheet by referencing a sample document of this form.

    Note however, that only the namespace bindings from the outermost element of the document will be copied.

  • It is possible to supply multiple URIs to assemble namespace bindings from more than one source.

  • Namespace bindings taken from an external document may be overridden using a local declaration for the prefix. This must appear after the URI in the content of the fixed-namespaces attribute.

Note:

Using the fixed-namespaces attribute rather than native namespace bindings to bind namespaces has a number of potential benefits:

  • It reduces repetitive coding across stylesheet module boundaries, and thus eliminates a source of potential errors.

  • It ensures that all expressions in a stylesheet module have the same namespace bindings in their static context. This can reduce implementation overheads because it reduces the need to maintain the namespace context at the level of individual expressions through rewrites such as function inlining. With processors that compile stylesheets to a persistent executable form, it can contribute to a reduction in the size of compiled code.

  • Namespaces bound in this way will never accidentally leak into a result tree; there is no need to exclude them using [xsl:]exclude-result-prefixes.

  • Namespaces declared on literal result elements are used purely to define the namespace of elements and attributes within the result tree; they no longer leak into the static context used when evaluating XPath expressions.

3.9 Forwards Compatible Processing

The intent of forwards compatible behavior is to make it possible to write a stylesheet that takes advantage of features introduced in some version of XSLT subsequent to XSLT 4.0, while retaining the ability to execute the stylesheet with an XSLT 4.0 processor using appropriate fallback behavior.

It is always possible to write conditional code to run under different XSLT versions by using the use-when feature described in 3.12.33.11.3 Conditional Element Inclusion. The rules for forwards compatible behavior supplement this mechanism in two ways:

  • Certain constructs in the stylesheet that mean nothing to an XSLT 4.0 processor are ignored, rather than being treated as errors.

  • Explicit fallback behavior can be defined for instructions defined in a future XSLT release, using the xsl:fallback instruction.

The detailed rules follow.

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

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

When an element is processed with forwards compatible behavior:

  • If the element is in the XSLT namespace and appears as a child of the xsl:stylesheet element, and XSLT 4.0 does not allow the element to appear as a child of the xsl:stylesheet element, then the element and its content must be ignored.

  • If the element has an attribute that XSLT 4.0 does not allow the element to have, then the attribute must be ignored.

  • If the element is in the XSLT namespace and appears as a child of an element whose content model requires a sequence constructor, and XSLT 4.0 does not allow such elements to appear as part of a sequence constructor, then:

    1. If the element has one or more xsl:fallback children, then no error is raised either statically or dynamically, and the result of evaluating the instruction is the concatenation of the sequences formed by evaluating the sequence constructors within its xsl:fallback children, in document order. Siblings of the xsl:fallback elements are ignored, even if they are valid XSLT 4.0 instructions.

    2. If the element has no xsl:fallback children, then a static error is raised in the same way as if forwards compatible behavior were not enabled.

Example: Forwards Compatible Behavior

For example, an XSLT 4.0 processor will process the following stylesheet without error, although the stylesheet includes elements from the XSLT namespace that are not defined in this specification:

<xsl:stylesheet version="17.0"
                xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <xsl:template match="/">
    <xsl:exciting-new-17.0-feature>
      <xsl:fly-to-the-moon/>
      <xsl:fallback>
        <html>
          <head>
            <title>XSLT 17.0 required</title>
          </head>
          <body>
            <p>Sorry, this stylesheet requires XSLT 17.0.</p>
          </body>
        </html>
      </xsl:fallback>
    </xsl:exciting-new-17.0-feature>
  </xsl:template>
</xsl:stylesheet>

Note:

If a stylesheet depends crucially on a declaration introduced by a version of XSLT after 4.0, then the stylesheet can use an xsl:message element with terminate="yes" (see 23.1 Messages) to ensure that implementations that conform to an earlier version of XSLT will not silently ignore the declaration.

Example: Testing the XSLT Version

For example,

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

  <xsl:important-new-17.0-declaration/>

  <xsl:template match="/">
    <xsl:choose>
      <xsl:when test="number(system-property('xsl:version')) lt 17.0">
        <xsl:message terminate="yes">
          <xsl:text>Sorry, this stylesheet requires XSLT 17.0.</xsl:text>
        </xsl:message>
      </xsl:when>
      <xsl:otherwise>
        ...
      </xsl:otherwise>
    </xsl:choose>
  </xsl:template>
  ...
</xsl:stylesheet>

Note:

The XSLT 1.0 and XSLT 2.0 specifications did not anticipate the introduction of the xsl:package element. An XSLT 1.0 or 2.0 processor encountering this element will raise a static error, regardless of the version setting.

This problem can be circumvented by using the simplified package syntax (whereby an xsl:stylesheet element is implicitly treated as xsl:package), or by writing the stylesheet code in a separate module from the package manifest, and using the separate module as the version of the stylesheet that is presented to a 2.0 processor.

For an XSLT 4.0 processor, the effective version of an xsl:fallback element that has no explicit version attribute is 4.0: more generally, it is the version of XSLT supported by the processor. This rule is designed to ensure that the xsl:fallback element itself is not processed with forwards compatible behavior, which would be pointless since the whole purpose of the instruction is to provide code that can be evaluated with an earlier version of XSLT.

Note:

This rule was not present in earlier versions of this specification. On a strict reading of the XSLT 3.0 specification, for example, an xsl:fallback instruction with no version attribute is evaluated with forwards compatible behavior. This means, for example, that if the stylesheet author writes <xsl:fallback select="42"/> (which is incorrect, because the instruction does not define a select attribute) then the select attribute will simply be ignored.

Stylesheet authors can prevent this problem by adding an explicit version attribute to xsl:fallback indicating the version of XSLT that is needed to evaluate the fallback code.

This specification cannot retrospectively dictate what XSLT 3.0 (or earlier) processors should do; however, developers of such processors are encouraged to adopt this rule, so that in an XSLT 4.0 stylesheet, an xsl:fallback instruction that cannot be properly evaluated by an XSLT 3.0 processor is rejected rather than being silently ignored.

3.11 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 7.6.5 is-id Accessor. 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.2 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.

3.123.11 Stylesheet Preprocessing

This specification provides three features that cause the raw stylesheet to be preprocessed as the first stage of static processing:

Note that many of the rules affecting the validity of stylesheet documents apply to a stylesheet after this preprocessing phase has been carried out.

3.12.13.11.1 Stripping Whitespace and Commentary from the Stylesheet

The tree representing the stylesheet is preprocessed as follows:

  1. All comments and processing instructions are removed.

  2. All xsl:note elements are removed, together with their content (see 3.12.23.11.2 The xsl:note element).

  3. Any text nodes that are now adjacent to each other are merged.

  4. Any whitespace text node that satisfies both the following conditions is removed from the tree:

    • The parent of the text node is not an xsl:text element

    • The text node does not have an ancestor element that has an xml:space attribute with a value of preserve, unless there is a closer ancestor element having an xml:space attribute with a value of default.

  5. Any whitespace text node whose parent is one of the following elements is removed from the tree, regardless of any xml:space attributes:

    xsl:accumulator
    xsl:analyze-string
    xsl:apply-imports
    xsl:apply-templates
    xsl:attribute-set
    xsl:call-template
    xsl:character-map
    xsl:choose
    xsl:evaluate
    xsl:fork
    xsl:merge
    xsl:merge-source
    xsl:mode
    xsl:next-iteration
    xsl:next-match
    xsl:override
    xsl:package
    xsl:stylesheet
    xsl:switch
    xsl:transform
    xsl:use-package

  6. Any whitespace text node whose immediate following-sibling node is an xsl:param or xsl:sort or xsl:context-item or xsl:on-completion element is removed from the tree, regardless of any xml:space attributes.

  7. Any whitespace text node whose immediate preceding-sibling node is an xsl:catch element is removed from the tree, regardless of any xml:space attributes.

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

Note:

Using xml:space="preserve" in parts of the stylesheet that contain sequence constructors will cause whitespace text nodes in that part of the stylesheet to be copied to the result of the sequence constructor. When the result of the sequence constructor is used to form the content of an element, this can cause errors if such text nodes are followed by attribute nodes generated using xsl:attribute.

Note:

If an xml:space attribute is specified on a literal result element, it will be copied to the result tree in the same way as any other attribute.

3.12.23.11.2 The xsl:note element

Changes in 4.0 (next | previous)

  1. A new element xsl:note is available for documentation and similar purposes: it can appear anywhere in the stylesheet and is ignored by the XSLT processor.   [Issue 109 PR 353 19 April 2023]

An xsl:note element may appear anywhere in the stylesheet, except as the outermost element.

<xsl:note
  #any#? = string >
  <!-- Content: any -->
</xsl:note>

The element may have any attributes and any children, subject only to rules imposed by other specifications such as the XML specification. The XSLT processor discards xsl:note elements at an early stage of processing, without performing any validation, as described in 3.12.13.11.1 Stripping Whitespace and Commentary from the Stylesheet.

An xsl:note element is typically used for documentation. The format of this documentation is not prescribed here: it might be free text, or XHTML, or some custom vocabulary understood by a free-standing documentation generator.

An xsl:note element might also be used for “commenting out” XSLT declarations or instructions.

Note:

A number of documentation processors have been produced for use with XSLT, and the general convention has been to use user-defined data elements for this purpose. This approach has its drawbacks:

  • Annotations can only appear at the top level of the stylesheet (between declarations, but not within declarations). Extension instructions can also potentially be used as annotations, but this abuses their intended purpose and may create an unwanted dependency on a specific processor.

  • Annotations require a custom namespace to be declared, typically on the xsl:stylesheet element, and this namespace becomes part of the static context for all expressions within the stylesheet, thus changing (if only very slightly) the semantics of the stylesheet code. This is true even if the namespace is excluded from the result tree by means of an [xsl:]exclude-result-prefixes attribute.

Implementations must not interpret the contents of an xsl:note element to modify the behavior of the stylesheet in any way, whether or not the resulting behavior remains conformant with this specification.

Note:

For example, xsl:note elements must not be used to provide processor-specific performance hints. There are better mechanisms for this, such as user-defined data elements and extension attributes.

3.12.33.11.3 Conditional Element Inclusion

Any element in the XSLT namespace may have a use-when attribute whose value is an XPath expression that can be evaluated statically. A literal result element, or any other element within a stylesheet module that is not in the XSLT namespace, may similarly carry an xsl:use-when attribute. If the attribute is present and the effective boolean valueXP of the expression is false, then the element, together with all the nodes having that element as an ancestor, is effectively excluded from the stylesheet module. When a node is effectively excluded from a stylesheet module the stylesheet module has the same effect as if the node were not there. Among other things this means that no static or dynamic errors will be raised in respect of the element and its contents, other than errors in the use-when attribute itself.

Note:

This does not apply to XML parsing or validation errors, which will be raised in the usual way. It also does not apply to attributes that are necessarily processed before [xsl:]use-when, examples being xml:space and [xsl:]xpath-default-namespace.

If the xsl:package, xsl:stylesheet or xsl:transform element itself is effectively excluded, the effect is to exclude all the children of the xsl:stylesheet or xsl:transform element, but not the xsl:stylesheet or xsl:transform element or its attributes.

Note:

This allows all the declarations that depend on the same condition to be included in one stylesheet module, and for their inclusion or exclusion to be controlled by a single use-when attribute at the level of the module.

Conditional element exclusion happens after stripping of whitespace text nodes from the stylesheet, as described in 3.12.13.11.1 Stripping Whitespace and Commentary from the Stylesheet.

The XPath expression used as the value of the xsl:use-when attribute follows the rules for static expressions, including the rules for handling errors.

The use of [xsl:]use-when is illustrated in the following examples.

Example: Using Conditional Exclusion to Achieve Portability

This example demonstrates the use of the use-when attribute to achieve portability of a stylesheet across schema-aware and non-schema-aware processors.

<xsl:import-schema schema-location="http://example.com/schema"
              use-when="system-property('xsl:is-schema-aware')='yes'"/>

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

<xsl:template match="/">
  <xsl:apply-templates/>
</xsl:template>

The effect of these declarations is that a non-schema-aware processor ignores the xsl:import-schema declaration and the first template rule, and therefore raises no errors in respect of the schema-related constructs in these declarations.

 

Example: Including Variant Stylesheet Modules

This example includes different stylesheet modules depending on which XSLT processor is in use.

<xsl:include href="module-A.xsl" 
     use-when="system-property('xsl:vendor')='vendor-A'"/>
<xsl:include href="module-B.xsl" 
     use-when="system-property('xsl:vendor')='vendor-B'"/>

3.12.43.11.4 Shadow Attributes

When a no-namespace attribute name N is permitted to appear on an element in the XSLT namespace (provided that N does not start with an underscore), then a value V can be supplied for N in one of two ways:

  • The conventional way is for an attribute node with name N and value V to appear in the XDM representation of the element node in the stylesheet tree.

  • As an alternative, a shadow attribute may be supplied allowing the value V to be statically computed during the preprocessing phase. The shadow attribute has a name that is the same as the name N prefixed with an underscore, and the value of the shadow attribute is a value template in which all expressions enclosed between curly braces must be static expressions. The value V is the result of evaluating the value template. If a shadow attribute is present, then any attribute node with name N (sharing the same parent element) is ignored.

For example, an xsl:include element might be written:

<xsl:include _href="common{ $VERSION }.xsl"/>

allowing the stylesheet to include a specific version of a library module based on the value of a static parameter.

Similarly, a mode might be declared like this:

<xsl:param name="streamable" as="xs:boolean" 
                  required="yes" static="yes"/>
<xsl:mode _streamable="{ $streamable }" on-no-match="shallow-skip"/>

this allowing the streamability of the mode to be controlled using a static parameter (Note: this example relies on the fact that the streamable attribute accepts a boolean value, which means that the values true and false are accepted as synonyms of yes and no).

This mechanism applies to all attributes in the stylesheet where the attribute name is in no namespace and the name of the parent element is in the XSLT namespace. This includes attributes that have static significance such as the use-when attribute, the version attribute, and the static attribute on xsl:variable. The mechanism does not apply to shadow attributes (that is, it is not possible to invoke two stages of preprocessing by using two leading underscores). It does not apply to attributes of literal result elements, nor to attributes in a namespace such as the XML or XSLT namespace, nor to namespace declarations.

Note:

If a shadow attribute and its corresponding target attribute are both present in the stylesheet, the non-shadow attribute is ignored. This may be useful to make stylesheet code compatible across XSLT versions; an XSLT 2.0 processor operating in forwards compatible mode will ignore shadow attributes, and will require the target attribute to be valid.

Note:

The statement that the non-shadow attribute is ignored extends to error detection: it is not an error if the non-shadow attribute has an invalid value. However, this is not reflected in the schema for XSLT stylesheets, so validation using this schema may raise errors in such cases.

Note:

An attribute whose name begins with an underscore is treated specially only when it appears on an element in the XSLT namespace. On a literal result element, it is treated in the same way as any other attribute (that is, its effective value is copied to the result tree). On an extension instruction or user-defined data element, as with other attributes on these elements, its meaning is entirely implementation-defined.

Example: Using Shadow Attributes to Parameterize XPath Default Namespace

Although it is not usually considered good practice, it sometimes happens that variants or versions of an XML vocabulary exist in which the same local names are used, but in different namespaces. There is then a requirement to write code that will process source documents in a variety of different namespaces.

It is possible to define a static stylesheet parameter containing the target namespace, for example:

<xsl:param name="NS" as="xs:string" static="yes" 
                          select="'http://example.com/ns/one'"/>

And this can then be used to set the default namespace for XPath expressions:

_xpath-default-namespace="{ $NS }"

However, it is not possible to put this shadow attribute on the xsl:stylesheet or xsl:package element of the principal stylesheet module, because at that point the variable $NS is not in scope. A workaround is to create a stub stylesheet module which contains nothing but the static parameter declaration and an xsl:include of the stylesheet module containing the real logic. The static stylesheet parameter will then be in scope on the xsl:stylesheet element of the included stylesheet module, and the shadow attribute _xpath-default-namespace="{ $NS }" can therefore appear on this xsl:stylesheet element.

 

Example: Using Shadow Attributes to Parameterize Selection of Elements

The following stylesheet produces a report giving information about selected employees. The predicate defining which employees are to be included in the report is supplied (as a string containing an XPath expression) in a static stylesheet parameter:

<xsl:param name="filter" static="yes"
           as="xs:string" select="'true()'"/>
<xsl:function name="local:filter" as="xs:boolean">
   <xsl:param name="e" as="element(employee)"/>
   <xsl:sequence _select="$e/({ $filter })"/>
</xsl:function>
<xsl:template match="/">
   <report>
      <xsl:apply-templates mode="report" select="//employee[local:filter(.)]"/>
   </report>
</xsl:template>

If the supplied value of the filter parameter is, say location = "UK", then the report will cover employees based in the UK.

Note:

The stylesheet function local:filter is used here in preference to direct use of the supplied predicate within the select attribute of the xsl:apply-templates instruction because it reduces exposure to code injection attacks. It does not necessarily eliminate all such risks, however. For example, it would be possible for a caller to supply an expression that never terminates, thus creating a denial-of-service risk.

3.133.12 Built-in Types

Every XSLT 4.0 processor includes the following named type definitions in the in-scope schema components:

  • All built-in types defined in [XML Schema Part 2], including xs:anyType and xs:anySimpleType.

  • The following types defined in [XPath 4.0]: xs:yearMonthDuration, xs:dayTimeDuration, xs:anyAtomicType, xs:untyped, and xs:untypedAtomic.

XSLT 4.0 processors may optionally include types defined in XSD 1.1 (see [XML Schema 1.1 Part 1]). XSD 1.1 adopts the types xs:yearMonthDuration, xs:dayTimeDuration, and xs:anyAtomicType previously defined in XPath 2.0, and adds one new type: xs:dateTimeStamp. XSD 1.1 also allows implementers to define additional primitive types, and XSLT 4.0 permits such types to be supported by an XSLT processor.

A schema-aware XSLT processor additionally supports:

Note:

The names that are imported from the XML Schema namespace do not include all the names of top-level types defined in either the Schema for Schema Documents or the Schema for Schema Documents (Datatypes). The Schema for Schema Documents, as well as defining built-in types such as xs:integer and xs:double, also defines types that are intended for use only within that schema, such as xs:derivationControl. A stylesheet that is designed to process XML Schema documents as its input or output may import the Schema for Schema Documents.

An implementation may define mechanisms that allow additional schema components to be added to the in-scope schema components for the stylesheet. For example, the mechanisms used to define extension functions (see 24.2 Extension Functions) may also be used to import the types used in the interface to such functions.

These schema components are the only ones that may be referenced in XPath expressions within the stylesheet, or in the [xsl:]type and as attributes of those elements that permit these attributes.

3.143.13 Importing Schema Components

Changes in 4.0 (next | previous)

  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. Different parts of a stylesheet may now use different imported schemas.   [Issue 451 PR 1819 18 February 2025]

Note:

The facilities described in this section are not available with a basic XSLT processor. They require a schema-aware XSLT processor, as described in 27 Conformance.

<!-- Category: declaration -->
<xsl:import-schema
  role? = ncname
  namespace? = uri
  schema-location? = uri >
  <!-- Content: xs:schema? -->
</xsl:import-schema>

The xsl:import-schema declaration is used to identify schema components (that is, top-level type definitions and top-level element and attribute declarations) that need to be available statically, that is, before any source document is available. Names of such components used statically within the stylesheet must refer to an in-scope schema component, which means they must either be built-in types as defined in 3.133.12 Built-in Types, or they must be imported using an xsl:import-schema declaration.

The xsl:import-schema declaration identifies a namespace containing the names of the components to be imported (or indicates that components whose names are in no namespace are to be imported). The effect is that the names of top-level element and attribute declarations and type definitions from this namespace (or non-namespace) become available for use within XPath expressions in the package, and within other stylesheet constructs such as the type and as attributes of various XSLT elements.

If the role attribute is absent, the relevant schema components are available in all stylesheet modules within the declaring package, except within subtrees of a stylesheet module where a different schema is selected using an [xsl:]schema-role attribute. Importing components in one stylesheet module makes them available throughout the package, subject to the constraints imposed by the [xsl:]schema-role attribute.

The schema components imported into different packages within a stylesheet (regardless of the schema role) must be compatibleDM. Specifically, it is not permitted to use the same name in the same XSD symbol space to refer to different schema components within different packages; and the union of the schema components imported into the packages of a stylesheet must constitute a valid schema (as well as the set of schema components imported into each package forming a valid schema in its own right).

Note:

The fact that the schemas used in different packages must be compatible does not mean they must be identical. There are circumstances where validating an element using one schema might produce a different outcome from validation with a different schema, despite these consistency rules: an example is where the two schemas define different membership for a substitution group.

Nevertheless, the consistency rules are strong enough to ensure that an element node validated using one schema can safely be passed to a function declared in another package, where the function declares the required type of an argument as (say) element(*, T).

The namespace and schema-location attributes are both optional.

If the xsl:import-schema element contains an xs:schema element, then the schema-location attribute must be absent, and one of the following must be true:

  • the namespace attribute of the xsl:import-schema element and the targetNamespace attribute of the xs:schema element are both absent (indicating a no-namespace schema), or

  • the namespace attribute of the xsl:import-schema element and the targetNamespace attribute of the xs:schema element are both present and both have the same value, or

  • the namespace attribute of the xsl:import-schema element is absent and the targetNamespace attribute of the xs:schema element is present, in which case the target namespace is as given on the xs:schema element.

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

If two xsl:import-schema declarations with the same effective role name specify the same namespace, or if both specify no namespace, then only the one with highest import precedence is used. If this leaves more than one, then all the declarations at the highest import precedence are used (which may cause conflicts, as described below).

After discarding any xsl:import-schema declarations under the above rule, the effect of the remaining xsl:import-schema declarations for each distinct schema role is defined in terms of a hypothetical document called the synthetic schema document, which is constructed as follows. The synthetic schema document defines an arbitrary target namespace that is different from any namespace actually used by the application, and it contains xs:import elements corresponding one-for-one with the xsl:import-schema declarations with that effective schema role in the stylesheet, with the following correspondence:

  • The namespace attribute of the xs:import element is copied from the namespace attribute of the xsl:import-schema declaration if it is explicitly present, or is implied by the targetNamespace attribute of a contained xs:schema element, and is absent if it is absent.

  • The schemaLocation attribute of the xs:import element is copied from the schema-location attribute of the xsl:import-schema declaration if present, and is absent if it is absent. If there is a contained xs:schema element, the effective value of the schemaLocation attribute is a URI referencing a document containing a copy of the xs:schema element.

  • The base URI of the xs:import element is the same as the base URI of the xsl:import-schema declaration.

The schema components included in the in-scope schema components of an XPath expression or other construct within a stylesheet (that is, the components whose names are available for use within that construct) depend on the effective schema role for that construct, which is determined by the value of the [xsl:]schema-role attribute of the innermost ancestor element having such an attribute; in the absence of such an attribute, the unnamed schema role applies. The schema components whose names are available are the top-level element and attribute declarations and type definitions that are available for reference within the synthetic schema document for that schema role. See [XML Schema Part 1] (section 4.2.3, References to schema components across namespaces).

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

Note:

The synthetic schema document does not need to be constructed by a real implementation. It is purely a mechanism for defining the semantics of xsl:import-schema in terms of rules that already exist within the XML Schema specification. In particular, it implicitly defines the rules that determine whether the set of xsl:import-schema declarations are mutually consistent.

These rules do not cause names to be imported transitively. The fact that a name is available for reference within a schema document A does not of itself make the name available for reference in a stylesheet that imports the target namespace of schema document A. (See [XML Schema Part 1] section 3.15.3, Constraints on XML Representations of Schemas.) The stylesheet must import all the namespaces containing names that it actually references.

The namespace attribute indicates that a schema for the given namespace is required by the stylesheet. This information may be enough on its own to enable an implementation to locate the required schema components. The namespace attribute may be omitted to indicate that a schema for names in no namespace is being imported. The zero-length string is not a valid namespace URI, and is therefore not a valid value for the namespace attribute.

The schema-location attribute is a URI Reference that gives a hint indicating where a schema document or other resource containing the required definitions may be found. It is likely that a schema-aware XSLT processor will be able to process a schema document found at this location.

The XML Schema specification gives implementations flexibility in how to handle multiple imports for the same namespace. Multiple imports do not cause errors if the definitions do not conflict.

A consequence of these rules is that it is not intrinsically an error if no schema document can be located for a namespace identified in an xsl:import-schema declaration. This will cause an error only if it results in the stylesheet containing references to names that have not been imported.

An inline schema document (using an xs:schema element as a child of the xsl:import-schema element) has the same status as an external schema document, in the sense that it acts as a hint for a source of schema components in the relevant namespace. To ensure that the inline schema document is always used, it is advisable to use a target namespace that is unique to this schema document.

The use of a namespace in an xsl:import-schema declaration does not by itself associate any namespace prefix with the namespace. If names from the namespace are used within the stylesheet module then a namespace declaration must be included in the stylesheet module, in the usual way.

Example: An Inline Schema Document

The following example shows an inline schema document. This declares a simple type local:yes-no, which the stylesheet then uses in the declaration of a variable.

The example assumes the namespace declaration xmlns:local="http://example.com/ns/yes-no"

<xsl:import-schema>
  <xs:schema targetNamespace="http://example.com/ns/yes-no"
             xmlns:xs="http://www.w3.org/2001/XMLSchema"
             xmlns:local="http://example.com/ns/yes-no">
    <xs:simpleType name="yes-no">
      <xs:restriction base="xs:string">
        <xs:enumeration value="yes"/>
        <xs:enumeration value="no"/>
      </xs:restriction>
    </xs:simpleType>
  </xs:schema>
</xsl:import-schema>

<xsl:variable name="condition" select="local:yes-no('yes')" 
                               as="local:yes-no"/>

There are two built-in functions (analyze-string and json-to-xml) whose result is an XML structure for which a schema is defined. The namespace for these schema definitions is (in both cases) http://www.w3.org/2005/xpath-functions. Schema components for these namespaces are available for reference within the stylesheet if and only if an xsl:import-schema declaration is present referencing this namespace. If such a declaration is present, then the schema that is imported is the schema defined in the specification of these functions: the schemaLocation attribute has no effect.

3.14.13.13.1 Multiple Schemas

Changes in 4.0 (next | previous)

  1. A stylesheet can import multiple schemas with different schema role names.   [Issue 451 PR 1819 18 February 2025]

A stylesheet might perform a transformation from an input document conforming to one schema, to an output document conforming to a different schema. To facilitate this, a schema can be imported with a specific role name, and it is then used only in parts of the stylesheet within the scope of an [xsl:]schema-role attribute specifying this role name.

More specifically, within the subtree rooted at an element having an [xsl:]schema-role attribute, the static context uses in-scope schema definitions taken from the named schema role.

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

Note:

The introduction of multiple schema roles in XSLT 4.0 enables different input and output documents to be validated against different schemas. For example, a stylesheet might contain the instruction:

<xsl:result-document validation="strict" schema-role="output">
   ...
</xsl:result-document>

to control which schema is used to validate the result document. Any instructions used to create validated element nodes in this result document should normally also be within the scope of the same [xsl:]schema-role.

The fact that multiple schemas can be imported does not relax the requirement that all schemas used in a transformation must be compatibleDM. This may mean, for example, that a transformation designed to convert documents from one version of a defined schema to a later version of the same schema may be unable to import both.

The reason for this restriction is to ensure that stylesheet components (such as functions) using schema components in their type signatures are compatible across the stylesheet as a whole, and that instance documents whose nodes have type annotations resulting from validation against a schema can be checked for conformance with types declared anywhere in the stylesheet.

It is possible to validate different parts of a constructed document against different schemas. However, validating an element in a document validates the entire subtree rooted at that element, so requesting validation at more than one level may be redundant.

4 Data Model

The data model used by XSLT is the XPath 4.0 and XQuery 4.0 data model (XDM), as defined in [XDM 4.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.12.13.11.1 Stripping Whitespace and Commentary from the Stylesheet and 4.2.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.

5 Features of the XSLT Language

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 2.2 Expression Context). This section describes the way in which these components are initialized when an XPath expression is contained within an XSLT stylesheet.

This section does not apply to static expressions (whose context is defined in 9.7 Static Expressions), nor to XPath expressions evaluated using xsl:evaluate (whose context is defined in 10.5.2 Dynamic context for the target expression).

As well as providing values for the static and dynamic context components defined in the XPath specification, XSLT defines additional context components of its own. These context components are used by XSLT instructions (for example, xsl:next-match and xsl:apply-imports), and also by the functions in the extended function library described in this specification.

The following four sections describe:

5.3.1 Initializing the Static Context
5.3.2 Additional Static Context Components used by XSLT
5.3.3 Initializing the Dynamic Context
5.3.4 Additional Dynamic Context Components used by XSLT

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 1.9 Terminology). 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 2.2.2 Dynamic Context 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.12.33.11.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.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.12.13.11.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.3 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:

8 Conditional Processing

There are several instructions in XSLT that support conditional processing: xsl:if, xsl:choose, and xsl:switch. The xsl:if instruction provides simple if-then-else conditionality; the xsl:choose instruction supports selection of one choice when there are several possibilities, and xsl:switch allows a branch to be selected based on the value of a given expression.

XSLT 3.0 also supports xsl:try and xsl:catch which define conditional processing to handle dynamic errors.

Note:

XSLT offers a number of ways of expressing conditional logic.

XSLT 1.0 offered the xsl:if instruction for cases where output was to be produced only if a condition was true, with xsl:choose available for multi-way branches where different output was to be produced under different input conditions. In addition, of course, XSLT 1.0 also offered the option of rule-based processing using templates and match patterns.

XSLT 2.0 added the XPath conditional expression providing two-way branches for use at a finer-grained level where xsl:choose could be excessively verbose: it allowed constructs such as <xsl:value-of select="if ($x) then 'red' else 'green'/> to be reduced from eight lines of code to one.

XSLT 4.0 introduces the then and else attributes for xsl:if, which are particularly useful in contexts such as the body of an xsl:function declaration where the alternative results are conveniently evaluated using XPath expressions rather than XSLT instructions: for example a recursive function might have as its body the instruction <xsl:if test="empty($seq)" then="1" else="head($seq) * my:f(tail($seq))"/>. The select attribute of xsl:when and xsl:otherwise is introduced for similar reasons: XSLT instructions are most useful when contructing node trees, whereas XPath expressions are more convenient when computing atomic items. Again, the main contribution of these enhancements is to reduce visual clutter, making the code more concise and more easily readable.

The xsl:switch instruction is introduced in XSLT 4.0 as an alternative to xsl:choose for the common use case where the conditions test for multiple different values of some common expression. By avoiding repetition of the common expression whose value is being tested, the logic becomes self-explanatory both to the human reader of the code and to an optimizing compiler, making it easier to generate efficient branching code.

8.5 Conditional Content Construction

The facilities described in this section are designed to make it easier to generate result trees conditionally depending on what is found in the input, without violating the rules for streamability. Although these facilities were introduced to the language specifically to make streaming easier, they are available whether or not streaming is in use, and users have often found them convenient in non-streaming applications.

The facilities are introduced first by example:

Example: Generating a Wrapper Element for a non-Empty Sequence

The following example generates an events element if and only if there are one or more event elements. The code could be written like this:

<xsl:if test="exists(event)">
  <events>
    <xsl:copy-of select="event"/>
  </events>
</xsl:if>

However, the above code would not be guaranteed-streamableSG, because it processes the child event elements more than once. To make it streamable, it can be rewritten as:

<xsl:where-populated>
  <events>
    <xsl:copy-of select="event"/>
  </events>
</xsl:where-populated>

The effect of the xsl:where-populated instruction, as explained later, is to avoid outputting the events element if it would have no children. A streaming implementation will typically hold the start tag of the events element in a buffer, to be sent to the output destination only if and when a child node is generated.

 

Example: Generating a Header and Footer only if there is Content

The following example generates an h3 element and a summary paragraph only if a list of items is non-empty. The code could be written like this:

<xsl:if test="exists(item-for-sale)">
  <h1>Items for Sale</h1>
</xsl:if>  
<xsl:apply-templates select="item-for-sale"/>
<xsl:if test="exists(item-for-sale)">
  <p>Total value: {accumulator-before('total-value')}</p>
</xsl:if>

However, the above code would not be guaranteed-streamableSG, because it processes the child item-for-sale elements more than once. To make it streamable, it can be rewritten as:

<xsl:sequence>
  <xsl:on-non-empty>
    <h1>Items for Sale</h1>
  </xsl:on-non-empty>  
  <xsl:apply-templates select="item-for-sale"/>
  <xsl:on-non-empty>
    <p>Total value: {accumulator-before('total-value')}</p>
  </xsl:on-non-empty>  
</xsl:sequence>

The effect of the xsl:on-non-empty instruction, as explained later, is to output the enclosed content only if the containing sequence constructor also generates “ordinary” content, that is, if there is content generated by instructions other than xsl:on-empty and xsl:on-non-empty instructions.

 

Example: Generating Substitute Text when there is no Content

The following example generates a summary paragraph only if a list of items is empty. The code could be written like this:

<xsl:apply-templates select="item-for-sale"/>
<xsl:if test="empty(item-for-sale)">
  <p>There are no items for sale.</p>
</xsl:if>

However, the above code would not be guaranteed-streamableSG, because it processes the child item-for-sale elements more than once (the fact that the list is empty is irrelevant, because streamability is determined statically). To make the code streamable, it can be rewritten as:

<xsl:sequence>
  <xsl:apply-templates select="item-for-sale"/>
  <xsl:on-empty>
    <p>There are no items for sale.</p>
  </xsl:on-empty>
</xsl:sequence>

The effect of the xsl:on-empty instruction, as explained later, is to output the enclosed content only if the containing sequence constructor generates no “ordinary” content, that is, if there is no content generated by instructions other than xsl:on-empty and xsl:on-non-empty instructions.

For further examples showing the use of these instructions when streaming, see 7 Handling Empty InputSG.

8.5.2 The xsl:on-empty instruction

<!-- Category: instruction -->
<xsl:on-empty
  select? = expression >
  <!-- Content: sequence-constructor -->
</xsl:on-empty>

The xsl:on-empty instruction has the same content model as xsl:sequence, and when it is evaluated, the same rules apply. In particular, the select attribute and the contained sequence constructor are mutually exclusive [see ERR XTSE3185].

When an xsl:on-empty instruction appears in a sequence constructor, then:

  1. It must be the only xsl:on-empty instruction in the sequence constructor, and

  2. It must not be followed in the sequence constructor by any other instruction, other than xsl:fallback, or by a significant text node (that is, a text node that has not been discarded under the provisions of 3.12.13.11.1 Stripping Whitespace and Commentary from the Stylesheet), or by a literal result element. It may, however, be followed by non-instructions such as xsl:catch where appropriate.

[Definition: An item is vacuous if it is one of the following: a zero-length text node; a document node with no children; an atomic item which, on casting to xs:string, produces a zero-length string; or an array which on flattening using the array:flatten function produces either an empty sequence or a sequence consisting entirely of vacuous items.]

An xsl:on-empty instruction is triggered only if every preceding sibling instruction, text node, and literal result element in the same sequence constructor returns either an empty sequence, or a sequence consisting entirely of vacuous items.

If an xsl:on-empty instruction is triggered, then the result of the containing sequence constructor is the result of the xsl:on-empty instruction.

Note:

This means that the (vacuous) results produced by other instructions in the sequence constructor are discarded. This is relevant mainly when the result of the sequence constructor is used for something other than constructing a node: for example if it forms the result of a function, or the value of a variable, and the function or variable specifies a required type.

When streaming, it may be necessary to buffer vacuous items in the result sequence until it is known whether the result will contain items that are non-vacuous. In many common situations, however — in particular, when the sequence constructor is being used to create the content of a node — vacuous items can be discarded immediately because they do not affect the content of the node being constructed.

Note:

In nearly all cases, the rules for xsl:on-empty are aligned with the rules for constructing complex content. If the sequence constructor within a literal result element or an xsl:element instruction includes an xsl:on-empty instruction, then the content of the element will be the value delivered by the xsl:on-empty instruction if and only if the content would otherwise be empty.

There is one minor exception to this rule: if the sequence constructor delivers multiple zero-length strings, then in the absence of the xsl:on-empty instruction the new element would contain whitespace, made up of the separators between these zero-length strings; but xsl:on-empty takes no account of these separators.

Note:

Attribute and namespace nodes created by the sequence constructor are significant; the xsl:on-empty instruction will not be triggered if such nodes are present. If this is not the desired effect, it is possible to partition the sequence constructor to change the scope of xsl:on-empty, for example:

<ol>
  <xsl:attribute name="class" select="numbered-list"/>
  <xsl:sequence>
    <xsl:value-of select="xyz"/>
    <xsl:on-empty select="'The list is empty'"/>
  </xsl:sequence>
</ol>

Note:

Where the sequence constructor is a child of an instruction with an [xsl:]use-attribute-sets attribute, any attribute nodes created by expanding the referenced attribute set(s) are not part of the result of the sequence constructor and therefore play no role in determining whether an xsl:on-empty or xsl:on-non-empty instruction is triggered. Equally, when the sequence constructor is a child of a literal result element, attribute nodes generated by expanding the attributes of the literal result element are not taken into account.

Note:

If xsl:on-empty is the only instruction in a sequence constructor then it is always evaluated.

If xsl:on-empty and xsl:on-non-empty appear in the same sequence constructor, then the rules ensure that only one of them will be evaluated.

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

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 4.0] (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 7.6.2 base-uri Accessor)
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.5 Dynamic XPath Evaluation

Changes in 4.0 (next | previous)

  1. A new attribute trusted=yes|no is added to xsl:evaluate to indicate whether the XPath expression to be evaluated is trusted to access external resources. The default value is no, which may cause backwards incompatibility. Dynamic evaluation using xsl:evaluate is no longer an optional feature of the XSLT language.   [Issue 2047 PR 2213 23 October 2025]

<!-- Category: instruction -->
<xsl:evaluate
  xpath = expression
  as? = sequence-type〔'item()*'〕
  base-uri? = { uri }
  with-params? = expression
  context-item? = expression
  namespace-context? = expression
  schema-aware? = { boolean }〔'no'〕
  trusted? = { boolean }〔'no'〕 >
  <!-- Content: (xsl:with-param | xsl:fallback)* -->
</xsl:evaluate>

The xsl:evaluate instruction constructs an XPath expression in the form of a string, evaluates the expression in a specified context, and returns the result of the evaluation.

The expression given as the value of the xpath attribute is evaluated and the result is converted to a string using the coercion rules.

[Definition: The string that results from evaluating the expression in the xpath attribute is referred to as the target expression.]

[ERR XTDE3160] It is a dynamic error if the target expression is not a valid expression (that is, if a static error occurs when analyzing the string according to the rules of the XPath specification).

The as attribute, if present, indicates the required type of the result. If the attribute is absent, the required type is item()*, which allows any result. The result of evaluating the target expression is converted to the required type using the coercion rules. This may cause a type error if conversion is not possible. The result after conversion is returned as the result of the xsl:evaluate instruction.

The target expression may contain variable references; the values of such variables may be supplied using an xsl:with-param child instruction if the names of the variables are known statically, or using a map supplied as the value of the expression in the with-params attribute if the names are only known dynamically. If the with-params attribute is present then it must contain an expression whose value, when evaluated, is of type map(xs:QName, item()*) (see 21 Maps for details of maps).

[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()*).

10.5.1 Static context for the target expression

The static contextXP for the target expression is as follows:

  • XPath 1.0 compatibility mode is false.

  • Trust level: the trust levelXP of the target expression is determined by the effective value of the trusted attribute. If the value is yes, the target expression has the same level of trust, and may therefore access the same external resources, as the calling stylesheet. If the value is no, the target expression has no access to external resources, other than any resources made explicitly available via some secure implementation-defined mechanism.

  • Statically known namespaces and default namespaces for elements and for types:

    • if the namespace-context attribute is present, then its value is an expression whose required type is a single node. The expression is evaluated, and the in-scope namespaces of the resulting node are used as the statically known namespaces for the target expression. The binding for the default namespace in the in-scope namespaces is used as the default namespace for both elements and types in the target expression.

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

    • if the namespace-context attribute is absent, then the applicable static namespaces of the xsl:evaluate instruction (with the exception of any binding for the default namespace) are used as the statically known namespaces for the target expression, and the value of the attribute [xsl:]xpath-default-namespace, if present, is used to establish the default namespace for elements and types in the target expression, as described in 5.1.2 Unprefixed Lexical QNames in Expressions and Patterns.

    Note:

    XPath 3.0 allows expanded names to be written in a context-independent way using the syntax Q{namespace-uri}local-name

  • Default function namespace: the standard function namespace.

  • In-scope schema definitions: if the schema-aware attribute is present and has the effective valueyes, then the in-scope schema definitions from the stylesheet context of the xsl:evaluate instruction (that is, the schema definitions imported using xsl:import-schema, taking into account any [xsl:]schema-role on the xsl:evaluate instruction or on any of its ancestors). Otherwise, the built-in types (see 3.133.12 Built-in Types).

    Note:

    If the containing stylesheet does not import a schema, then the in-scope schema definitions for the target expression will contain only the built-in schema types, regardless of the value of the schema-aware attribute.

  • In-scope variables: the names of the in-scope variables are the union of the names appearing in the name attribute of the contained xsl:with-param elements, and the names present as keys in the map obtained by evaluating the with-params attribute, if present. The corresponding type is item()* in the case of a name found as a key in the with-params map, or the type named in the as attribute of xsl:with-param child (defaulting to item()*) otherwise.

    If a variable name is present both the static xsl:with-param children and also in the dynamic with-params map, the value from the latter takes precedence.

    Note:

    Variables declared in the stylesheet in xsl:variable or xsl:param elements are not in-scope within the target expression.

  • Function signatures:

    • All functions defined in [Functions and Operators 4.0] in the fn, math, map, and array namespaces;

    • Constructor functions for named simple types included in the in-scope schema definitions;

    • All user-defined functions present in the containing package provided their visibility is not hidden or private;

    • An implementation-defined set of extension functions.

    Note that this set deliberately excludes XSLT-defined functions in the standard function namespace including for example, key, current-group, and system-property. A list of these functions is in G.2 List of XSLT-defined functions.

  • Statically known collations: the same as the collations available at this point in the stylesheet.

  • Default collation: the same as the default collation defined at this point in the stylesheet (for example, by use of the [xsl:]default-collation attribute)

  • Base URI: if the base-uri attribute is present, then its effective value; otherwise, the base URI of the xsl:evaluate instruction.

11 Creating Nodes

This section describes instructions that directly create new nodes.

11.4 Creating Text Nodes

Changes in 4.0 (next | previous)

  1. The xsl:text instruction can now have a select attribute, and it can take a sequence constructor as its content. The only remaining distinction between the xsl:text and xsl:value-of instructions is that whitespace text node children of xsl:text are treated as significant, rather than being stripped during stylesheet preprocessing.   [Issue 323 PR 2251 14 October 2025]

This section describes three different ways of creating text nodes: by means of literal text nodes in the stylesheet, or by using the xsl:text and xsl:value-of instructions. It is also possible to create text nodes using the xsl:number instruction described in 12 Numbering.

If and when the sequence that results from evaluating a sequence constructor is used to form the content of a node, as described in 5.7.2 Constructing Simple Content and 5.7.1 Constructing Complex Content, adjacent text nodes in the sequence are merged. Within the sequence itself, however, they exist as distinct nodes.

Example: A Sequence of Text Nodes

The following function returns a sequence of three text nodes:

<xsl:function name="f:wrap">
  <xsl:param name="s"/>
  <xsl:text>(</xsl:text>
  <xsl:value-of select="$s"/>
  <xsl:text>)</xsl:text>
</xsl:function>

When this function is called as follows:

<xsl:value-of select="f:wrap('---')"/>

the result is:

(---)

No additional spaces are inserted, because the calling xsl:value-of instruction merges adjacent text nodes before atomizing the sequence. However, the result of the instruction:

<xsl:value-of select="data(f:wrap('---'))"/>

is:

( --- )

because in this case the three text nodes are atomized to form three strings, and spaces are inserted between adjacent strings.

This example reflects the traditional usage of xsl:text to output constant text and xsl:value-of to output variable text. In XSLT 4.0, however, either instruction can be used for either purpose, and in the example above either instruction could be replaced by the other.

It is possible to construct text nodes whose string value is zero-length. A zero-length text node, when atomized, produces a zero-length string. However, zero-length text nodes are ignored when they appear in a sequence that is used to form the content of a node, as described in 5.7.1 Constructing Complex Content and 5.7.2 Constructing Simple Content.

11.4.1 Literal Text Nodes

A sequence constructor can contain text nodes. Each text node in a sequence constructor remaining after whitespace text nodes have been stripped as specified in 3.12.13.11.1 Stripping Whitespace and Commentary from the Stylesheet will construct a new text node with the same string value. The resulting text node is added to the result of the containing sequence constructor.

Text is processed at the tree level. Thus, markup of &lt; in a template will be represented in the stylesheet tree by a text node that includes the character <. This will create a text node in the result tree that contains a < character, which will be represented by the markup &lt; (or an equivalent character reference) when the result tree is serialized as an XML document, unless otherwise specified using character maps (see 26.3 Character Maps) or disable-output-escaping (see 26.5 Disabling Output Escaping).

A non-whitespace text node in the stylesheet that is not contained within an xsl:text or xsl:value-of instruction is equivalent to wrapping the text node in xsl:text. For example:

<xsl:if test="$debug">Here I am</xsl:if>

is equivalent to:

<xsl:if test="$debug"><xsl:text>Here I am</xsl:text></xsl:if>

11.4.2 The xsl:text and xsl:value-of instructions

Changes in 4.0 (next | previous)

  1. The rules for xsl:text and xsl:value-of are integrated, allowing xsl:text to be used to construct all text nodes, whether the content is fixed or variable.  [Issue 323 PR 2251 31 October 2025]

  2. The attribute cdata is added to xsl:text and xsl:value-of to request serialization of a text node as a CDATA section.  [Issue 2198 PR 2301 19 November 2025]

<!-- Category: instruction -->
<xsl:text
  select? = expression
  separator? = { string }
  cdata? = { boolean }〔'no'〕
  [disable-output-escaping]? = boolean〔'no'〕 >
  <!-- Content: sequence-constructor -->
</xsl:text>

<!-- Category: instruction -->
<xsl:value-of
  select? = expression
  separator? = { string }
  cdata? = { boolean }〔'no'〕
  [disable-output-escaping]? = boolean〔'no'〕 >
  <!-- Content: sequence-constructor -->
</xsl:value-of>

The xsl:text and xsl:value-ofelement have identical content models. The only differences between them are:

  1. The xsl:text element is treated specially during whitespace-stripping, as described in 3.12.13.11.1 Stripping Whitespace and Commentary from the Stylesheet. Specifically, whitespace text nodes that are children of xsl:text are preserved, whereas whitespace text nodes that are children of xsl:value-of are discarded.

  2. Special rules apply to xsl:value-of when the instruction is processed with XSLT 1.0 behavior. Specifically, if no separator attribute is present, and if the select attribute is present, then all items in the atomized result sequence other than the first are ignored.

The xsl:text or xsl:value-of instruction is evaluated to construct a new text node; the result of the instruction is the newly constructed text node.

The string value of the new text node may be defined either by using the select attribute, or by the sequence constructor (see 5.7 Sequence Constructors) that forms the content of the xsl:text or xsl:value-of 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 result of the instruction is a text node whose string value is zero-length. The way in which the value is constructed is specified in 5.7.2 Constructing Simple Content.

[ERR XTSE0870] It is a static error if the select attribute of the xsl:text or xsl:value-of element is present when the content of the element is non-empty.

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.

If the element or one of its ancestors has an [xsl:]expand-text attribute, and the nearest ancestor with such an attribute has the value yes, then any unescaped curly brackets in the value of the element indicate the presence of text value templates, which are expanded as described in 5.6.2 Text Value Templates.

In the absence of such an attribute, or if the effective value is no, the content of the xsl:text or xsl:value-of instruction may comprise a single text node whose value forms the string value of the constructed text node. An xsl:text or xsl:value-of element may also be empty, in which case the result of evaluating the instruction is a text node whose string value is the zero-length string.

For the effect of the cdata attribute, see 11.4.3 Generating CDATA Sections.

For the effect of the deprecateddisable-output-escaping attribute, see 26.5 Disabling Output Escaping

Note:

It is not always necessary to use the xsl:text or xsl:value-of instruction to write text nodes to the result tree. Literal text can be written to the result tree by including it anywhere in a sequence constructor. The principal reason for using xsl:text is that it offers improved control over whitespace handling.

Note:

Historically, xsl:value-of was used to construct variable content, while xsl:text was used to copy fixed text from the stylesheet to the result document. In 4.0, that distinction is no longer relevant. Stylesheet authors should consider using xsl:text whenever there is a need to construct text nodes, as the intent is more clearly expressed. The xsl:value-of instruction has often been misunderstood; it is a common mistake to use it where xsl:sequence or xsl:copy-of is more appropriate.

Example: Generating a List with Separators

The instruction:

<x><xsl:text select="1 to 4" separator="|"/></x>

produces the output:

<x>1|2|3|4</x>

 

Example: Generating Whitespace using xsl:textExample: Generating Whitespace using xsl:text

The instruction:

<a><xsl:text>  <x/>  </xsl:text></a>

produces the output:

<a>  <x/>  </a>

This illustrates that all whitespace text node children of xsl:text are preserved, even if they have non-whitespace siblings.

21 Maps

Maps are defined in the XDM Data Model: see [XDM 4.0] section 8.2 Map Items.

21.1 Map Instructions

Changes in 4.0 (next | previous)

  1. The xsl:map instruction allows a select attribute as an alternative to the contained sequence constructor.   [Issue 1632 PR 1694 14 January 2025]

  2. The xsl:map-entry instruction, in common with other instructions, now raises error XTSE3185 (rather than XTSE3280) if both a select attribute and a sequence constructor are present.   [Issue 1632 PR 1694 14 January 2025]

  3. Ordered maps are introduced.   [Issue 1651 PR 1703 14 January 2025]

Three instructions are added to XSLT to facilitate the construction of maps.

<!-- Category: instruction -->
<xsl:map
  select? = expression
  duplicates? = expression〔fn($a, $b) { error(xs:QName(err:XTDE3365)) }〕 >
  <!-- Content: sequence-constructor -->
</xsl:map>

The instruction xsl:map constructs and returns a new map.

The select attribute and the contained sequence constructor are mutually exclusive: if a select attribute is present, then the content must be empty except optionally for xsl:fallback instructions. [see ERR XTSE3185]

The result of evaluating the select expression or the contained sequence constructor is referred to as the input sequence.

The input sequence must be a sequence of maps: call this $maps.

In the absence of duplicate keys, the result of the instruction is then given by the XPath 3.1 expression:

map:merge($maps)

Note:

Informally: in the absence of duplicate keys the resulting map contains the union of the map entries from the supplied sequence of maps.

Note:

The order of entries in the returned map will reflect the order of items in the sequence that results from evaluation of the input sequence.

The handling of duplicate keys is described in 21.1.2 Handling of duplicate keys below.

There is no requirement that the supplied input maps should have the same or compatible types. The type of a map (for example map(xs:integer, xs:string)) is descriptive of the entries it currently contains, but is not a constraint on how the map may be combined with other maps.

Note:

A common coding pattern is to supply the input as a set of single-entry maps, that is, maps containing a single key-value pair. Moreover, it is often convenient to construct these using the xsl:map-entry instruction. However, it is not required that the input maps should be single-entry maps, nor is it required that they should be constructed using this instruction.

[ERR XTTE3375] A type error occurs if the result of the input sequence is not an instance of the required type map(*)*.

Note:

In practice, the effect of this rule is that the result of the select expression or sequence constructor contained in the xsl:map instruction is severely constrained: it doesn’t make sense, for example, for it to contain instructions such as xsl:element that create new nodes. As with other type errors, processors are free to raise the error statically if they are able to determine that the sequence constructor would always fail when evaluated.

Note:

It is legitimate to construct a map using an instruction such as <xsl:map select="{'a':1, 'b':2}"/>. In this situation xsl:map has exactly the same effect as xsl:sequence, but users may feel that it improves readability.

<!-- Category: instruction -->
<xsl:map-entry
  key = expression
  select? = expression >
  <!-- Content: sequence-constructor -->
</xsl:map-entry>

The instruction xsl:map-entry constructs and returns a singleton map: that is, a map which contains one key and one value. Such a map is primarily used as a building block when constructing maps using the xsl:map instruction.

The select attribute and the contained sequence constructor are mutually exclusive: if a select attribute is present, then the content must be empty except optionally for xsl:fallback instructions. [see ERR XTSE3185]

The key of the entry in the new map is the value obtained by evaluating the expression in the key attribute, converted to the required type xs:anyAtomicType by applying the coercion rules. If the supplied key (after conversion) is of type xs:untypedAtomic, it is cast to xs:string.

The associated value is the value obtained by evaluating the expression in the select attribute, or the contained sequence constructor, with no conversion. If there is no select attribute and the sequence constructor is empty, the associated value is the empty sequence.

Example: Using XSLT instructions to create a fixed map

The following example binds a variable to a map whose content is statically known:

<xsl:variable name="week" as="map(xs:string, xs:string)">
  <xsl:map>
    <xsl:map-entry key="'Mo'" select="'Monday'"/>
    <xsl:map-entry key="'Tu'" select="'Tuesday'"/>
    <xsl:map-entry key="'We'" select="'Wednesday'"/>
    <xsl:map-entry key="'Th'" select="'Thursday'"/>
    <xsl:map-entry key="'Fr'" select="'Friday'"/>
    <xsl:map-entry key="'Sa'" select="'Saturday'"/>
    <xsl:map-entry key="'Su'" select="'Sunday'"/>
  </xsl:map>
</xsl:variable>

In simple cases like this the same effect can be achieved using the xsl:record instruction:

<xsl:variable name="week" as="map(xs:string, xs:string)">
  <xsl:record
    Mo="'Monday'"
    Tu="'Tuesday'"
    We="'Wednesday'"
    Th="'Thursday'"
    Fr="'Friday'"
    Sa="'Saturday'"
    Su="'Sunday'"/>
</xsl:variable>

A third option is to construct the map in XPath:

<xsl:variable name="week" as="map(xs:string, xs:string)">
  <xsl:select>
    {'Mo':'Monday', 'Tu':'Tuesday', 'We':'Wednesday',
     'Th':'Thursday', 'Fr': 'Friday', 'Sa':'Saturday',
     'Su':'Sunday'}
  </xsl:select>   
</xsl:variable>

 

Example: Using XSLT instructions to create a computed map

The following example binds a variable to a map acting as an index into a source document:

<xsl:variable name="index" as="map(xs:string, element(employee))">
  <xsl:map>
    <xsl:for-each select="//employee">
      <xsl:map-entry key="@empNr" select="."/>
    </xsl:for-each>
  </xsl:map>
</xsl:variable>

Again, an alternative is to use an XPath expression:

<xsl:variable name="index" as="map(xs:string, element(employee))">
  <xsl:select>
    map:build(//employee, fn{@empNr})
  </xsl:select>
</xsl:variable>

 

Example: Modifying the keys in a map

The following example modifies a supplied map $input by changing all the keys to upper case. A dynamic error occurs if this results in duplicate keys:

<xsl:map>
  <xsl:for-each select="map:pairs($map)">
    <xsl:map-entry key="upper-case(?key)" select="?value"/>
  </xsl:for-each>
</xsl:map>

 

Example: Modifying the values in a map

The following example modifies a supplied map $input by wrapping each of the values in an array:

<xsl:map>
  <xsl:for-each select="map:pairs($map)">
    <xsl:map-entry key="?key">
       <xsl:array select="?value"/>
    </xsl:map-entry>
  </xsl:for-each>
</xsl:map>

This could also be written:

<xsl:map select="
  map:pairs($map) ! { ?key : array{ ?value } }"/>

21.1.1 Record Instruction

Changes in 4.0 (next | previous)

  1. The xsl:record instruction is introduced to make construction of record maps simpler.   [Issue 322 PR 1858 25 March 2025]

<!-- Category: instruction -->
<xsl:record
  xsl:as? = item-type〔'map(*)'〕
  xsl:duplicates? = expression〔fn($a, $b) { error(xs:QName(err:XTDE3365)) }〕
  * = expression >
  <!-- Content: sequence-constructor -->
</xsl:record>

(The notation * = expression indicates that this instruction accepts any number of additional attributes in no namespace.)

Editorial note 
There needs to be a construct available within element-catalog.xml to declare 'any permitted attribute of a given name type/pattern', in this case xs:NCName

The instruction xsl:record constructs and returns a new populated map, permitting entries to be declared as attributes on the instruction. It is intended to make writing maps where the entry keys are NCNames simpler and more concise, avoiding larger XSLT constructs using xsl:map and xsl:map-entry or xsl:sequence containing map-constructing XPath expressions.

Note:

Unlike all other XSLT elements, the names of the attributes xsl:as and xsl:duplicates as well as the standard attributes (such as use-when or xpath-default-namespace) attached to the xsl:record instruction must be in the XSLT namespace, as opposed to being in no namespace. This has been chosen to avoid reserving the names of such attributes (e.g. as, duplicates, use-when etc.) as potential entry keys, leaving any valid NCName as a candidate.

The xsl:record generates a new map: call this $record. For each of the attributes of the instruction whose name is an xs:NCName an entry is added to $record whose key is the name of the attribute (as xs:string) and whose value is the result of evaluating the value of that attribute as an expression in the current context.

Note:

As the values of the attributes whose names are xs:NCName are considered to be XPath expressions, two consequences follow for such attributes:

  1. They must not be considered as shadow attributes (see 3.12.43.11.4 Shadow Attributes) as a leading underscore is a valid character within an xs:NCName.
  2. They are not designated as attribute value templates.

These restrictions do not apply to attributes of xsl:record whose names are in namespaces.

Note:

The order of attribute-generated entries in $record will reflect the order of attributes returned along the attribute:: axis, which is implementation-dependent but stable.

After processing the applicable attributes of the instruction, any contained sequence constructor is evaluated and the result must be a (possibly empty) sequence of maps. The entries in these maps are merged into $record. By this means entries can be added whose keys are not NCNames, or conditionally generated entries can be included.

Each of the map entries in $record is modified by applying the coercion rules to convert the singleton map to the type declared in the xsl:as attribute of the xsl:record instruction, if present. This may contain a map type declaration or a reference to one of the in-scope named item typesXP, which may include record types. Unless any type restriction is violated $record is returned as the instruction result.

Editorial note 
This implies that xsl:map and possibly xsl:map-entry should support an as attribute, restricting type.

The treatment of duplicate keys between entries defined in the attributes of xsl:record and any generated by a contained sequence constructor is described in 21.1.2 Handling of duplicate keys below. Note that in the absence of a sequence constructor, no duplicate keys can appear, as all attributes of xsl:record must have a unique name within the element tag.

The effect of this instruction, in the absence of errors, is equivalent to execution of the XSLT xsl:map instruction generated by the the following source transformation of the xsl:record subtree

                   <xsl:namespace-alias stylesheet-prefix="t" result-prefix="xsl"/>
...

<xsl:mode name="record" on-no-match="shallow-copy">
   <xsl:template match="xsl:record">
      <xsl:variable name="xsl-attributes" select="@xsl:*"/>
      <xsl:variable name="ncname-attributes" select="@*[empty(prefix-from-QName(node-name()))]"/>
      <xsl:variable name="other-attributes"
          select="@* except ($xsl-attributes, $ncname-attributes)"/>
      <t:map>
         <xsl:sequence select="$other-attributes"/>
         <xsl:apply-templates select="$xsl-attributes, $ncname-attributes, node()"/>
      </t:map>
   </xsl:template>
   <xsl:template match="xsl:record/@*">
      <t:map-entry key="'{name()}'" select="{.}"/>
   </xsl:template>
   <xsl:template match="xsl:record/@xsl:*" priority="1">
      <xsl:attribute name="{local-name()}" select="."/>
   </xsl:template>
</xsl:mode>

which for the instruction:

 <xsl:record xsl:as="eg:book" author="string(AUTHOR)"
               title="string(TITLE)" 
               price="xs:decimal(PRICE)" 
               publisher="string(../@name)">
      <xsl:if test="@private">
         <xsl:map-entry name="'private entry'" select="true()"/>
      </xsl:if>
   </xsl:record>

would produce

 <xsl:map as="eg:book">
      <xsl:map-entry key="'author'" select="string(AUTHOR)"/>
      <xsl:map-entry key="'title'" select="string(TITLE)"/>
      <xsl:map-entry key="'price'" select="xs:decimal(PRICE)"/>
      <xsl:map-entry key="'publisher'" select="string(../@name)"/>
      <xsl:if test="@private">
         <xsl:map-entry name="'private entry'" select="true()"/>
      </xsl:if>
   </xsl:map>
Example: Generating a map with xsl:recordExample: Generating a map with xsl:record

The following example constructs a map using xsl:record

<xsl:template match="book" as="map(*)">
   <xsl:record author="string(AUTHOR)"
               title="string(TITLE)" 
               price="xs:decimal(PRICE)" 
               publisher="string(../@name)">
      <xsl:if test="@private">
         <xsl:map-entry name="'private entry'" select="true()"/>
      </xsl:if>
   </xsl:record>
</xsl:template>

with the following input

<catalog name="QT4 Community">
  <book private="true">
    <AUTHOR>MHK</AUTHOR>
    <TITLE>XSLT 4.0</TITLE>
    <PRICE>123.45</PRICE>
  </book>
</catalog>

will produce a resulting map:

map{'author':'MHK', 'title': 'XSLT 4.0', 'price':123.45, 
                     'publisher':'QT4 Community', 'private entry': true()}

24 Extensibility and Fallback

Changes in 4.0 (next | previous)

  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]

XSLT allows three kinds of extension: extension attributes, extension instructions, and extension functions.

[Definition: An extension attribute is an attribute appearing on an XSLT element, where the name of the attribute is in a non-null namespace other than the XSLT namespace.]

[Definition: An extension instruction is an element within a sequence constructor that is in a namespace (not the XSLT namespace) designated as an extension namespace.]

[Definition: An extension function is a named function introduced to the static or dynamic context by mechanisms outside the scope of this specification.]

This specification does not define any mechanism for creating or binding implementations of extension attributes, extension instructions, or extension functions, and it is not required that implementations support any such mechanism. Such mechanisms, if they exist, are implementation-defined. Therefore, an XSLT stylesheet that must be portable between XSLT implementations cannot rely on particular extensions being available. XSLT provides mechanisms that allow an XSLT stylesheet to determine whether the implementation makes particular extensions available, and to specify what happens if those extensions are not available. If an XSLT stylesheet is careful to make use of these mechanisms, it is possible for it to take advantage of extensions and still retain portability.

[ERR XTSE0085] It is a static error to use a reserved namespace in the name of any extension attribute, extension function, or extension instruction, other than a function or instruction defined in this specification or in a normatively referenced specification. It is a static error to use a prefix bound to a reserved namespace in the [xsl:]extension-element-prefixes attribute.

24.2 Extension Functions

The set of functions that can be called from a FunctionCallXP within an XPath expression may include one or more extension functions. The expanded QName of an extension function always has a non-null namespace URI, which must not be the URI of a reserved namespace.

Note:

The definition of the term extension function is written to exclude user-written stylesheet functions, constructor functions for built-in and user-defined types, functions in the fn, math, map, and array namespaces, anonymous XPath inline functions, maps and arrays, and partial function applications (including partial applications of extension functions). It also excludes functions obtained by invoking XPath-defined functions such as load-xquery-module. The definition allows extension functions to be discovered at evaluation time (typically using function-lookup) rather than necessarily being known statically.

Technically, the definition of extension functions excludes anonymous functions obtained by calling or partially applying other extension functions. Since such functions are by their nature implementation-defined, they may however share some of the characteristics of extension functions.

24.2.1 fn:function-available

Summary

Determines whether a particular function is or is not available for use. The function is particularly useful for calling within an [xsl:]use-when attribute (see 3.12.33.11.3 Conditional Element Inclusion) to test whether a particular extension function is available.

Signature
fn:function-available(
$nameas (xs:string | xs:QName),
$arityas xs:integer?:= ()
) as xs:boolean
Properties

This function is deterministicFO, context-dependentFO, and focus-independentFO. It depends on namespaces, and known function signatures.

Rules

A function is said to be available within an XPath expression if it is present in the statically known function definitionsXP for that expression (see 5.3.1 Initializing the Static Context). Function definitions in the static context are uniquely identified by the name of the function (a QName) in combination with its arity range.

The value of $namemust be either an xs:QName, or a string containing an EQName. A lexical QName is expanded into an expanded QName using the namespace declarations in scope for the expression. If the value is an unprefixed lexical QName, then the standard function namespace is used in the expanded QName.

When the $arity argument is present and non-empty, the function-available function returns true if and only if there is an available function whose name matches the value of the $function-name argument and whose arity range includes the value of the $arity argument.

When the $arity argument is omitted or empty, the function-available function returns true if and only if there is at least one available function (with some arity) whose name matches the value of the $name argument.

When the containing expression is evaluated with XPath 1.0 compatibility mode set to true, the function-available function returns false in respect of a function name and arity for which no implementation is available (other than the fallback error function that raises a dynamic error whenever it is called). This means that it is possible (as in XSLT 1.0) to use logic such as the following to test whether a function is available before calling it:

Example: Calling an extension function with backwards compatibility enabled
<summary xsl:version="1.0">
  <xsl:choose>
    <xsl:when test="function-available('my:summary')">
      <xsl:value-of select="my:summary()"/>
    </xsl:when>
    <xsl:otherwise>
      <xsl:text>Summary not available</xsl:text>
    </xsl:otherwise>
  </xsl:choose>
</summary>
Error Conditions

[ERR XTDE1400] It is a dynamic error if the $name argument 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.

Notes

The fact that a function with a given name is available gives no guarantee that any particular call on the function will be successful. For example, it is not possible to determine the types of the arguments expected.

The introduction of the function-lookup function in XPath 3.0 reduces the need for function-available, since function-lookup not only tests whether a function is available, but also returns a function item that enables it to be dynamically called.

If a function is present in the static context but with no useful functionality (for example, if the system has been configured for security reasons so that available-environment-variables returns no information), then function-available when applied to that function should return false.

It is not necessary that there be a direct equivalence between the results of function-available and function-lookup in all cases. For example, there may be extension functions whose side-effects are such that for security reasons, dynamic calls to the function are disallowed; function-lookup might then not provide access to the function. The main use-case for function-available, by contrast, is for use in [xsl:]use-when conditions to test whether static calls on the function are possible.

In XSLT 4.0, the argument can be supplied as a QName literal, for example function-available( #fn:matches ). Note that in this case the default function namespace is not used for unprefixed names.

Examples
Example: Stylesheet portable between XSLT 1.0, XSLT 2.0, and XSLT 3.0

A stylesheet that is designed to use XSLT 2.0 facilities when running under an XSLT 2.0 or XSLT 3.0 processor, but to fall back to XSLT 1.0 capabilities when not, might be written using the code:

<out xsl:version="2.0">
  <xsl:choose>
    <xsl:when test="function-available('matches')">
      <xsl:value-of select="matches(/doc/title, '[a-z]*')"/>
    </xsl:when>
    <xsl:otherwise>
      <xsl:value-of select="string-length(
	        translate(/doc/title, 'abcdefghijklmnopqrstuvwxyz', '')) = 0"/>
    </xsl:otherwise>
  </xsl:choose>
</out>

Here an XSLT 2.0 or XSLT 3.0 processor will always take the xsl:when branch, while a 1.0 processor will follow the xsl:otherwise branch. The single-argument version of the function-available function is used here, because that is the only version available in XSLT 1.0. Under the rules of XSLT 1.0, the call on the matches function is not an error, because it is never evaluated.

Example: Stylesheet portable between XSLT 3.0 and a future version of XSLT

A stylesheet that is designed to use facilities in some future XSLT version when they are available, but to fall back to XSLT 2.0 or XSLT 3.0 capabilities when not, might be written using code such as the following. This hypothesizes the availability in some future version of a function pad which pads a string to a fixed length with spaces:

 <xsl:value-of select="pad(/doc/title, 10)" 
               use-when="function-available('pad', 2)"/>
 <xsl:value-of select="concat(/doc/title, string-join(
                          for $i in 1 to 10 - string-length(/doc/title) 
						  return ' ', ''))"
               use-when="not(function-available('pad', 2))"/>

In this case the two-argument version of function-available is used, because there is no requirement for this code to run under XSLT 1.0.

24.3 Extension Instructions

Changes in 4.0 (next | previous)

  1. It is possible to invoke a named template using an extension instruction, specifically, an element whose name matches the name of the named template.   [Issue 168  30 September 2022]

[Definition: The extension instruction mechanism allows namespaces to be designated as extension namespaces. When a namespace is designated as an extension namespace and an element with a name from that namespace occurs in a sequence constructor, then the element is treated as an instruction rather than as a literal result element.] The namespace determines the semantics of the instruction.

Note:

Since an element that is a child of an xsl:stylesheet element is not occurring in a sequence constructor, user-defined data elements (see 3.6.4 User-defined Data Elements) are not extension elements as defined here, and nothing in this section applies to them.

In XSLT 4.0 it is possible to use extension instructions to invoke named templates: see 10.1.3 Invoking Named Templates using Extension Instructions.

24.3.2 fn:element-available

Summary

Determines whether a particular instruction is or is not available for use. The function is particularly useful for calling within an [xsl:]use-when attribute (see 3.12.33.11.3 Conditional Element Inclusion) to test whether a particular extension instruction is available.

Signature
fn:element-available(
$nameas (xs:string | xs:QName)
) as xs:boolean
Properties

This function is deterministicFO, context-dependentFO, and focus-independentFO. It depends on namespaces.

Rules

The value of the $name argument must be either an xs:QName, or a string containing an EQName. If it is a lexical QName with a prefix, then it is expanded into an expanded QName using the namespace declarations in the static context of the expression. If there is a default namespace in scope, then it is used to expand an unprefixed lexical QName.

If the resulting expanded QName is in the XSLT namespace, the function returns true if and only if the local name matches the name of an XSLT element that is defined in this specification and implemented by the XSLT processor.

If the expanded QName has a null namespace URI, the element-available function will return false.

If the expanded QName is not in the XSLT namespace, the function returns true if and only if the processor has an external implementation available of an extension instruction with the given expanded QName. This applies whether or not the namespace has been designated as an extension namespace.

The term external implementation excludes the use of a named template as the instruction’s implementation. The function does not return true simply because the name matches the name of a named template.

If the processor does not have an implementation of a particular extension instruction available, and such an extension instruction is evaluated, then the processor must perform fallback for the element as specified in 24.3.3 Fallback. An implementation must not raise an error merely because the stylesheet contains an extension instruction for which no implementation is available.

Error Conditions

[ERR XTDE1440] It is a dynamic error if the argument 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.

Notes

For element names in the XSLT namespace:

  • This function can be useful to distinguish processors that implement XSLT 3.0 from processors that implement other (older or newer) versions of the specification, and to distinguish full implementations from incomplete implementations. (Incomplete implementations, of course, cannot be assumed to behave as described in this specification.)

  • In earlier versions of this specification, element-available was defined to return true only for elements classified as instructions. The distinction between instructions and other elements, however, is sometimes rather technical, and in XSLT 3.0 the effect of the function has therefore been aligned to do what its name might suggest.

  • If an instruction is recognized but offers no useful functionality (for example, if the system has been configured for security reasons so that xsl:evaluate always raises an error), then element-available when applied to that instruction should return false.

For element names in other namespaces:

  • The result of the element-available does not depend on whether or not the namespace of the supplied instruction name has been designated as an extension element namespace; it tests whether the instruction would be available if the namespace were designated as such.

In XSLT 4.0, the argument can be supplied as a QName literal, for example element-available( #xsl:switch ). Note that in this case the default element namespace is not used for unprefixed names.

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

Changes in 4.0 (next | previous)

  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.

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

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 [Serialization 4.0]. 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.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 [Serialization 4.0].

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.12.43.11.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 4.1.5 XML and XSD Versions.

27 Conformance

Changes in 4.0 (previous)

  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]

  2. The dynamic evaluation feature no longer exists; processor are now required to support the xsl:evaluate instruction.   [Issue 2047 PR 2213 23 October 2025]

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.

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 4.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.9 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.2 Schema-Awareness Conformance Feature

A conformant processor must either be a conformant schema-aware XSLT processor or a conformant non-schema-aware processor.

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

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

[ERR XTSE1650] A non-schema-aware processormust raise a static error if a package includes an xsl:import-schema declaration.

Note:

A processor that rejects an xsl:import-schema declaration will also reject any reference to a user-defined type defined in a schema, or to a user-defined element or attribute declaration; it will not, however, reject references to the built-in types listed in 3.133.12 Built-in Types.

A non-schema-aware processor is not able to validate input documents, and is not able to handle input documents containing type annotations other than xs:untyped or xs:untypedAtomic. Therefore, such a processor must treat any [xsl:]validation attribute with a value of preserve or lax, or a [xsl:]default-validation attribute with a value of preserve as if the value were strip.

Note:

The values lax and preserve indicate that the validation to be applied depends on the calling application, so it is appropriate for the request to be treated differently by different kinds of processor. By contrast, requesting strict validation, either through the [xsl:]validation attribute or the type attribute, indicates that the stylesheet is expecting to deal with typed data, and therefore cannot be processed without performing the validation.

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

A non-schema-aware processor constrains the data model as follows, and raises a dynamic error ([see ERR XTDE1665]) if the constraints are not satisfied:

  • Atomic items must belong to one of the atomic types listed in 3.133.12 Built-in Types (except as noted below).

    An atomic item may also belong to an implementation-defined type that has been added to the context for use with extension functions or extension instructions.

    The set of constructor functions available are limited to those that construct values of the above atomic types.

    The static context, which defines the full set of type names recognized by an XSLT processor and also by the XPath processor, includes these atomic types, plus xs:anyType, xs:anySimpleType, xs:untyped, and xs:anyAtomicType.

  • Element nodes must be annotated with the type annotationxs:untyped, and attribute nodes with the type annotation xs:untypedAtomic.

B Glossary (Non-Normative)

A sequence comparator is an expression that evaluates two sequences of items and results in a true or false value.

absent

A component of the context that has no value is said to be absent.

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 2.6.3 Atomization. It is a process that takes as input a sequence of items, and returns a sequence of atomic items, in which the nodes are replaced by their typed values as defined in [XDM 4.0]. Arrays (see 22 Arrays) are atomized by atomizing their members, recursively.

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.

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.

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.

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.

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 4.0]) is either an atomic item (such as an integer, date, or string), a node, or a function item. It changes whenever instructions such as xsl:apply-templates and xsl:for-each are used to process a sequence of items; each item in such a sequence becomes the context item while that item is being processed.

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

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

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

disqualifying element

The disqualifying elements are xsl:map, xsl:map-entry, xsl:array, xsl:array-member, xsl:record, and xsl:select. If a sequence constructor includes one of these elements, then construction of the implicit document node does not take place.

dynamic error

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

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.3 Standard Attributes) on that element or on the innermost ancestor element that has such an attribute, subject to special rules for the xsl:output and xsl:fallback elements.

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.11 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 4.0]): that is, a triple containing namespace prefix (optional), namespace URI (optional), and local name. Two expanded QNames are equal if the namespace URIs are the same (or both absent) and the local names are the same. The prefix plays no part in the comparison, but is used only if the expanded QName needs to be converted back to a string.

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 extension attribute is an attribute appearing on an XSLT element, where the name of the attribute is in a non-null namespace other than the XSLT namespace.

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.

forwards compatible behavior

An element is processed with forwards compatible behavior if its effective version is greater than 4.0.

function definition

The term function definition is defined in [XPath 4.0] section 2.2.1 Static Context. It is the definition of a function that can be called statically from within an XPath expression: in the case of XSLT it typically means either a stylesheet function, or a built-in function such as those defined in [Functions and Operators 4.0]

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.

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.

GNode pattern

An GNode pattern uses a subset of the syntax for path expressions, and is defined to match a GNode if the corresponding path expression would select the GNode.

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

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

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.

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

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

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

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 callsXP, (that is calls to function items). It excludes calls to some functions in the namespace http://www.w3.org/2005/xpath-functions, in particular those that explicitly depend on the context, such as the current-group and regex-group functions. It is implementation-defined whether, and under what circumstances, calls to extension functions are non-contextual.

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.

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.

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 4.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.10.2 Stylesheet Inclusion and 3.10.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.3.3 Default Priority for Patterns.

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.

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 4.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.7 Simplified Stylesheet Modules. This is first converted to a standard stylesheet module by wrapping it in an xsl:stylesheet element using the transformation described in 3.7 Simplified Stylesheet Modules.

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

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-streamableSG according to this specification.

string value

The term string value is defined in [XDM 4.0] section 7.6.12 string-value Accessor. Every node has a string value. For example, the string value of an element is the concatenation of the string values of all its descendant text nodes.

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.

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.4.2 Dependencies between Packages.

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 4.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 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 7.6.13 type-name Accessor.

typed value

The term typed value is defined in [XDM 4.0] section 7.6.14 typed-value Accessor. Every node, other than an element whose type annotation identifies it as having element-only content, has a typed value. For example, the typed value of an attribute of type xs:IDREFS is a sequence of zero or more xs:IDREF values.

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 is written as ~T (where T is an ItemTypeXP) followed by zero or more predicates in square brackets, and it matches any item of type T for which each of the predicates evaluates to true.

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.

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 4.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 2.2.1 Static Context. This is a setting in the static context of an XPath expression; it has two values, true and false. When the value is set to true, the semantics of function calls and certain other operations are adjusted to give a greater degree of backwards compatibility between XPath 4.0 and XPath 1.0.

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

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.2 Vendor and User Extensions

This category covers extensions and extensibility: mechanisms for providing vendor or user extensions to the language without sacrificing interoperability.

In general terms, it is implementation-defined:

  • whether and under what circumstances the implementation recognizes any extension functions, extension instructions, extension attributes, user-defined data elements, additional types, additional serialization methods or serialization parameters, or additional collations, and if so, what effect they have.

  • whether, how, and under what circumstances the implementation allows users to define extension functions, extension instructions, extension attributes, user-defined data elements, additional types, additional serialization methods or serialization parameters, or additional collations. If it does allow users to do so, it must follow the rules given elsewhere in this specification.

  • what information is available to such extensions (for example, whether they have access to the static and dynamic context.)

  • where such extensions are allowed, the extent to which the processor enforces their correct behavior (for example, checking that strings returned by extension functions contain only valid XML characters)

More specifically:

  1. The mechanisms for creating new extension instructions and extension functions are implementation-defined. It is not required that implementations provide any such mechanism. (See 2.9 Extensibility)

  2. The set of namespaces that are specially recognized by the implementation (for example, for user-defined data elements, and extension attributes) is implementation-defined. (See 3.6.4 User-defined Data Elements)

  3. The effect of user-defined data elements whose name is in a namespace recognized by the implementation is implementation-defined. (See 3.6.4 User-defined Data Elements)

  4. An implementation may define mechanisms, above and beyond xsl:import-schema, that allow schema components such as type definitions to be made available within a stylesheet. (See 3.133.12 Built-in Types)

  5. The set of extension functions available in the static context for the target expression of xsl:evaluate is implementation-defined. (See 10.5.1 Static context for the target expression)

  6. If the data-type attribute of the xsl:sort element has a value other than text or number, the effect is implementation-defined. (See 13.1.2 Comparing Sort Key Values)

  7. The effect of an extension function returning a string containing characters that are not permitted in XML is implementation-defined. (See 24.2.2 Calling Extension Functions)

  8. The way in which external objects are represented in the type system is implementation-defined. (See 24.2.3 External Objects)

I Changes since XSLT 3.0 (Non-Normative)

I.1 Changes in this specification

  1. If a section of this specification has been updated since version 3.0, an overview of the changes is provided, along with links to navigate to the next or previous change.

    See 1.2 What’s New in XSLT 4.0?

  2. Sections with significant changes are marked with a ✭ symbol in the table of contents.

    See 1.2 What’s New in XSLT 4.0?

  3. PR 751 1386 

    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.

    See 6.7.5 Declaring the Result Type of a Mode

  4. The xsl:for-each and xsl:apply-templates instructions acquire an attribute separator that can be used to insert content between adjacent items. [This change was in the editor's draft adopted as a baseline when the WG commenced work.]

    See 7.1 The xsl:for-each instruction

  5. PR 2015 2296 

    A variable-binding with no as or select attribute no longer attempts to create an implicit document node if the sequence constructor contains certain instructions (such as xsl:map, xsl:array, xsl:record, and xsl:select).

    See 9.3 Values of Variables and Parameters

  6. PR 2200 2236 

    Stylesheet functions may now be in no namespace, and may be invoked without use of a namespace prefix, provided they are private to a package.

    See 10.3.1 Function Name and Arity

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

    See 20 Additional Functions

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

    See 24 Extensibility and Fallback

  9. New in 4.0

    See 26.4.1 fn:character-map

  10. The xsl:for-each and xsl:apply-templates instructions acquire an attribute separator that can be used to insert content between adjacent items. [This change was in the editor's draft adopted as a baseline when the WG commenced work.]

    See 6.4 Applying Template Rules

  11. It is possible to invoke a named template using an extension instruction, specifically, an element whose name matches the name of the named template.

    See 10.1.3 Invoking Named Templates using Extension Instructions

    See 24.3 Extension Instructions

  12. A new attribute xsl:map/@duplicates is available, allowing control over how duplicate keys are handled by the xsl:map instruction.

    See 21.1.2 Handling of duplicate keys

  13. PR 1497 1546 

    A new serialization parameter json-lines is available to enable output as one JSON value per line.

    See 25.1 Creating Secondary Results

    See 26.1 The xsl:output declaration

  14. PR 159 

    Parameters on functions declared using xsl:function can now be defined as optional, with a default value supplied.

    See 9.2.2 Default Values of Parameters

    See 10.3 Stylesheet Functions

  15. PR 237 

    The xsl:if instruction now allows then and else attributes.

    See 8.1 Conditional Processing with xsl:if

    In xsl:choose, the xsl:when and xsl:otherwise elements can take a select attribute in place of a sequence constructor.

    See 8.2 Conditional Processing with xsl:choose

    A new xsl:switch instruction is introduced.

    See 8.3 Conditional Processing with xsl:switch

  16. PR 326 

    The higher-order-function feature no longer exists; higher-order functions are now a core part of XSLT, no longer an optional extra.

    See 27 Conformance

  17. PR 353 

    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.

    See 3.6 Stylesheet Element

    A new element xsl:note is available for documentation and similar purposes: it can appear anywhere in the stylesheet and is ignored by the XSLT processor.

    See 3.12.23.11.2 The xsl:note element

  18. PR 401 

    Patterns (especially those used in template rules) can now be defined by reference to item types, so any item type can be used as a match pattern. For example match="~record(longitude, latitude, *)" matches any map that includes the key values "longitude" and "latitude".

    See 6.3.2.2 Type Patterns

  19. PR 406 

    The new instruction xsl:array is introduced to allow construction of arrays.

    See 22.1 Array Construction

  20. PR 470 

    The xsl:stylesheet, xsl:transform, or xsl:package element may have a fixed-namespaces attribute making it easier to have the same namespace declarations in force throughout a stylesheet.

    See 3.6.1 The fixed-namespaces Attribute

  21. PR 489 

    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.

    See 17.1 The xsl:analyze-string Instruction

  22. PR 534 

    A new serialization parameter escape-solidus is provided to control whether the character / is escaped as \/ by the JSON serialization method.

    See 25.1 Creating Secondary Results

    See 26.1 The xsl:output declaration

  23. PR 542 

    A mode (called an enclosing mode) can be defined in which all the relevant template rules are children of the xsl:mode element. This is intended to allow a stylesheet design in which it is easier to determine which rules might apply to a given xsl:apply-templates call.

    See 6.7.6 Enclosing Modes

  24. PR 599 

    Simplified stylesheets no longer require an xsl:version attribute (which means they might not need a declaration of the XSLT namespace). Unless otherwise specified, a 4.0 simplified stylesheet defaults expand-text to true.

    See 3.7 Simplified Stylesheet Modules

  25. PR 635 

    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.

    See 3.143.13 Importing Schema Components

    See 25.4 Validation

  26. PR 717 

    Capturing accumulators have been added; when streaming with a capturing accumulator, the accumulator-after has full access to a snapshot of the matched element node.

    See 19.9 Capturing Accumulators

  27. PR 718 

    To allow recursive-descent transformation on a tree of maps and arrays, a new set of built-in templates rules shallow-copy-all is introduced.

    See 6.8 Built-in Template Rules

  28. PR 740 

    A new attribute xsl:for-each-group/@split-when is available to give applications more complete control over how a sequence is partitioned

    See 14 Grouping

  29. PR 751 

    The xsl:mode declaration acquires an attribute as="sequence-type" which declares the return type of all template rules in that mode.

    See 6.7.1 Declaring Modes

  30. PR 1181 

    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.

    See 5.1.2 Unprefixed Lexical QNames in Expressions and Patterns

  31. PR 1250 

    The strings used in the formatted number to represent a decimal separator, grouping separator, exponent separator, percent sign, per mille sign, or minus sign, are no longer constrained to be single characters.

    See 5.5 Defining a Decimal Format

  32. PR 1254 

    The rules concerning the interpretation of xsi:schemaLocation and xsi:noNamespaceSchemaLocation attributes have been tightened up.

    See 25.4 Validation

    See 25.4 Validation

  33. PR 1306 

    An as attribute is available on the xsl:sequence instruction.

    See 10.4.1 The xsl:sequence Instruction

  34. PR 1361 

    The term atomic value has been replaced by atomic item.

    See 2.1 Terminology

  35. PR 1378 

    A function call at the outermost level can now be named using any valid EQName (for example fn:doc) provided it binds to one of the permitted functions fn:doc, fn:id, fn:element-with-id, fn:key, or fn:root. If two functions are called, for example doc('a.xml')/id('abc'), it is no longer necessary to put the second call in parentheses.

    See 6.3.2.3 GNode Patterns

  36. PR 1442 

    Default priorities are added for new forms of ElementTest and AttributeTest, for example element(p:*) and element(a|b).

    See 6.3.3 Default Priority for Patterns

  37. PR 1454 

    Duplicate xsl:include declarations within a stylesheet level are now ignored, preventing spurious errors caused by the presence of duplicate named components.

    See 3.10.2 Stylesheet Inclusion

  38. PR 1505 

    New variables err:stack-trace, err:additional, and err:map are available within an xsl:catch clause.

    See 8.4 Try/Catch

  39. PR 1530 

    The contents of a character map declared using xsl:character-map are now available dynamically via a new character-map function.

    See 26.4 The character-map function

  40. PR 1544 

    It is no longer an intrinsic error for a global variable to refer to itself; this is now permitted, for example in cases where the value of the global variable is a recursive inline function. Cases where self-reference would not make sense are covered by the existing rules on circularities: see 9.11 Circular Definitions.

    See 9.5 Global Variables and Parameters

  41. PR 1549 

    The input to the serializer can be defined using the select attribute of xsl:result-document as an alternative to using a sequence constructor.

    See 25.1 Creating Secondary Results

  42. PR 1560 

    The default value for the indent parameter is now defined to be no for all output methods other than html and xhtml.

    See 26.2 Serialization parameters

  43. PR 1617 

    Named item types can be declared using the new xsl:item-type element. This is designed to avoid repeating lengthy type definitions (for example function types) every time they are used.

    See 5.4.1 Named Item Types

  44. PR 1622 

    The rules for equality comparison have changed to bring keys into line with maps.

    See 20.2.2 fn:key

    New in 4.0.

    See 20.2.3 fn:map-for-key

  45. PR 1674 

    Composite sort keys are allowed in xsl:sort.

    See 13.1.2 Comparing Sort Key Values

  46. PR 1689 

    Composite merge keys are now allowed.

    See 15 Merging

    New in 4.0

    See 15.5.2 fn:current-merge-key-array

  47. PR 1694 

    The xsl:map instruction allows a select attribute as an alternative to the contained sequence constructor.

    See 21.1 Map Instructions

    The xsl:map-entry instruction, in common with other instructions, now raises error XTSE3185 (rather than XTSE3280) if both a select attribute and a sequence constructor are present.

    See 21.1 Map Instructions

  48. PR 1703 

    Ordered maps are introduced.

    See 21.1 Map Instructions

  49. PR 1708 

    Named record types are introduced.

    See 5.4.2 Named Record Types

  50. PR 1772 

    The default priority for a template rule using a union pattern has changed. This change may cause incompatible behavior.

    See 6.3.3 Default Priority for Patterns

  51. PR 1819 

    Different parts of a stylesheet may now use different imported schemas.

    See 2.10 Stylesheets and XML Schemas

    The standard attribute [xsl:]schema-role is introduced, to allow different parts of a stylesheet to use different schemas.

    See 3.3 Standard Attributes

    Different parts of a stylesheet may now use different imported schemas.

    See 3.143.13 Importing Schema Components

    A stylesheet can import multiple schemas with different schema role names.

    See 3.14.13.13.1 Multiple Schemas

  52. PR 1856 

    The rules for xsl:analyze-string have been adjusted to allow for new capabilities in regular expressions, such as zero-width assertions.

    See 17.1 The xsl:analyze-string Instruction

  53. PR 1858 

    The xsl:record instruction is introduced to make construction of record maps simpler.

    See 21.1.1 Record Instruction

    Attribute xsl:record/@xsl:duplicates is added to control duplicate keys handling in the xsl:record instruction.

    See 21.1.2 Handling of duplicate keys

  54. PR 1875 

    The xsl:apply-imports and xsl:next-match instructions automatically pass supplied parameters to the overridden template rule.

    See 6.9 Overriding Template Rules

  55. PR 1888 

    A new XSLT element, xsl:package-location is provide to indicate to the processor where the required package is to be found.

    See 3.4.3 Locating Packages

  56. PR 1929 

    The xsl:mode declaration acquires an attribute copy-namespaces which determines whether or not the built-in template rule copies unused namespace bindings.

    See 6.7.1 Declaring Modes

  57. PR 2006 

    A new function fn:apply-templates is introduced.

    See 6.7.3 The apply-templates Function

    New in 4.0

    See 6.7.3.1 fn:apply-templates

  58. PR 2008 

    The xsl:select instruction is new in 4.0.

    See 10.4.2 The xsl:select Instruction

  59. PR 2030 

    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.

    See 25.4 Validation

  60. PR 2123 

    A new attribute xsl:for-each-group/@merge-when is available to give applications control to create groups based on clustering, overlap, and networks.

    See 14 Grouping

  61. PR 2200 

    User-defined functions can now have names that are in no namespace. An unprefixed name appearing in a function call is resolved to a no-namespace function with matching local name in preference to a function in the standard fn namespace.

    See 10.3 Stylesheet Functions

  62. PR 2213 

    A new attribute trusted=yes|no is added to xsl:evaluate to indicate whether the XPath expression to be evaluated is trusted to access external resources. The default value is no, which may cause backwards incompatibility. Dynamic evaluation using xsl:evaluate is no longer an optional feature of the XSLT language.

    See 10.5 Dynamic XPath Evaluation

    The dynamic evaluation feature no longer exists; processor are now required to support the xsl:evaluate instruction.

    See 27 Conformance

  63. PR 2218 

    Numeric values of type xs:decimal are compared as decimals, without first converting to xs:double.

    See 13.1.2 Comparing Sort Key Values

  64. PR 2251 

    The xsl:text instruction can now have a select attribute, and it can take a sequence constructor as its content. The only remaining distinction between the xsl:text and xsl:value-of instructions is that whitespace text node children of xsl:text are treated as significant, rather than being stripped during stylesheet preprocessing.

    See 11.4 Creating Text Nodes

    The rules for xsl:text and xsl:value-of are integrated, allowing xsl:text to be used to construct all text nodes, whether the content is fixed or variable.

    See 11.4.2 The xsl:text and xsl:value-of instructions

  65. PR 2259 

    A new serialization parameter canonical is available to give control over serialization of XML, XHTML, and JSON.

    See 25.1 Creating Secondary Results

    See 26.1 The xsl:output declaration

  66. PR 2274 

    XSLT-specific components of the dynamic context can now be retained in the captured context of a function item, in the same way as XPath-defined components of the dynamic context.

    See 5.3.4 Additional Dynamic Context Components used by XSLT

    In XSLT 4.0, the function item current-group#0 retains the value of the current group within its captured context.

    See 14.2.1 fn:current-group

    In XSLT 4.0, the function item current-grouping-key#0 retains the value of the current grouping key within its captured context.

    See 14.2.2 fn:current-grouping-key

    In XSLT 4.0, the function item current-merge-group retains the value of the current merge-key within its captured context.

    See 15.5.1 fn:current-merge-group

    In XSLT 4.0, the function item current-merge-key#0 retains the value of the current group within its captured context.

    See 15.5.3 fn:current-merge-key

    In XSLT 4.0, the function item regex-group#1 retains the value of the current captured substrings within its captured context.

    See 17.2.2 fn:regex-group

    In XSLT 4.0, the function item current#0 retains the value of the current item within its captured context.

    See 20.5.1 fn:current

    In XSLT 4.0, the function item current-output-uri#0 retains the value of the current output URI within its captured context.

    See 25.3.1 fn:current-output-uri

  67. PR 2283 

    The conformance requirements for extension attributes have been relaxed: the requirement to maintain strict conformance to the specification in the presence of extension attributes is now a should rather than a must, and extension attributes are allowed to modify the form of serialized output without limitation.

    See 24.1 Extension Attributes

  68. PR 2301 

    The attribute cdata is added to xsl:text and xsl:value-of to request serialization of a text node as a CDATA section.

    See 11.4.2 The xsl:text and xsl:value-of instructions

    See 11.4.3 Generating CDATA Sections

  69. PR 2323 

    The outermost element of a simplified stylesheet need no longer be a literal result element, it can now be any instruction (including xsl:result-document). This allows a simplified stylesheet to produce JSON output as well as XML or HTML.

    See 3.7 Simplified Stylesheet Modules

  70. PR 2736 

    The xsl:mode/@typed attribute has been clarified and expanded to provide better control over the handling of items other than XNodes.

    See 6.7.4 Declaring the Type of Values Processed by a Mode