The following associated resources are available: Specification in XML format, XSD 1.1 Schema for XSLT 4.0 Stylesheets (non-normative), Relax-NG Schema for XSLT 4.0 Stylesheets (non-normative), Stylesheet for XML-to-JSON conversion (non-normative)
Copyright © 2026 W3C® (MIT, ERCIM, Keio, Beihang). W3C liability, trademark and document use rules apply.
This specification defines the syntax and semantics of XSLT 4.0, a language designed primarily for transforming XML documents into other XML documents, but also offering support for other data formats including JSON, HTML, and CSV.
XSLT 4.0 is a revised version of the XSLT 3.0 Recommendation [XSLT 3.0] published on 8 June 2017. Changes are presented in 1.2 What’s New in XSLT 4.0?.
XSLT 4.0 is designed to be used in conjunction with XPath 4.0, which is defined in [XPath 4.0]. XSLT shares the same data model as XPath 4.0, which is defined in [XDM 4.0], and it uses the library of functions and operators defined in [Functions and Operators 4.0]. XPath 4.0 and the underlying function library introduce a number of enhancements, for example the availability of union and record types.
This document contains hyperlinks to specific sections or definitions within other documents in this family of specifications. These links are indicated visually by a superscript identifying the target specification: for example XP for XPath 4.0, DM for the XDM data model version 4.0, FO for Functions and Operators version 4.0, SG for XSLT Streaming version 4.0.
An optional feature of the XSLT language is support for streamed transformations. The XSLT 4.0 specification has been modularized so that streaming is now described in a separate specification document. This has been done in order to make the specifications more manageable, both for editors and readers: it does not alter the status of streaming as an optional feature, available in some processors and not others.
This section describes the status of this document at the time of its publication. Other documents may supersede this document.
This document is a working draft developed and maintained by a W3C Community Group, the XQuery and XSLT Extensions Community Group unofficially known as QT4CG (where "QT" denotes Query and Transformation). This draft is work in progress and should not be considered either stable or complete. Standard W3C copyright and patent conditions apply.
The community group welcomes comments on the specification. Comments are best submitted as issues on the group's GitHub repository.
The community group maintains two extensive test suites, one oriented to XQuery and XPath, the other to XSLT. These can be found at qt4tests and xslt40-test respectively. New tests, or suggestions for correcting existing tests, are welcome. The test suites include extensive metadata describing the conditions for applicability of each test case as well as the expected results. They do not include any test drivers for executing the tests: each implementation is expected to provide its own test driver.
The publications of this community group are dedicated to our co-chair, Michael Sperberg-McQueen (1954–2024).
XSLT is a programming language designed principally to transform data.
A transformation in the XSLT language is expressed in the form of a stylesheet. A stylesheet is made up of one or more well-formed XML [XML 1.0] documents conforming to the Namespaces in XML Recommendation [Namespaces in XML].
A stylesheet generally includes elements that are defined by XSLT as well as elements that are not defined by XSLT. XSLT-defined elements are distinguished by use of the namespace http://www.w3.org/1999/XSL/Transform (see 3.1.1 XSLT Namespace), which is referred to in this specification as the XSLT namespace. Thus this specification is a definition of the syntax and semantics of the XSLT namespace.
The term stylesheet reflects the fact that one of the important roles of XSLT is to add styling information to an XML source document, by transforming it into a document consisting of XSL formatting objects (see [XSL-FO]), or into another presentation-oriented format such as HTML, XHTML, or SVG. However, XSLT is used for a wide range of transformation tasks, not exclusively for formatting and presentation applications.
A transformation expressed in XSLT describes rules for transforming input data into output data. The inputs and outputs will all be instances of the XDM data model, described in [XDM 4.0]. In the simplest and most common case, the input is an XML document referred to as the source document or source tree, and the output is an XML document referred to as the result tree. It is also possible to process multiple source documents, to generate multiple result documents, and to handle formats other than XML.
The transformation is achieved by a set of template rules. A template rule associates a pattern, which typically matches nodes in the source document, with a sequence constructor. In many cases, evaluating the sequence constructor will cause new nodes to be constructed, which can be used to produce part of a result tree. The structure of the result trees can be completely different from the structure of the source trees. In constructing a result tree, nodes from the source trees can be filtered and reordered, and arbitrary structure can be added. Because patterns can point to nodes according to typological features, a stylesheet can be applicable to a wide class of source documents that have similar tree structures.
Stylesheets are modular; they may contain several packages developed independently of each other, and each package may consist of several stylesheet modules.
[Definition: [Definition: A stylesheet consists of one or more packages: specifically, one top-level package and zero or more library packages.]
[Definition: [Definition: For a given transformation, one package functions as the top-level package. The complete stylesheet is assembled by finding the packages referenced directly or indirectly from the top-level package using xsl:use-package declarations: see 3.4.2 Dependencies between Packages.]
[Definition: [Definition: Every package within a stylesheet, other than the top-level package, is referred to as a library package.]
[Definition: [Definition: Within a package, one stylesheet module functions as the principal stylesheet module. The complete package is assembled by finding the stylesheet modules referenced directly or indirectly from the principal stylesheet module using xsl:include and xsl:import elements: see 3.10.2 Stylesheet Inclusion and 3.10.3 Stylesheet Import.]
For a full glossary of terms, see B Glossary.
[Definition: [Definition: The software responsible for transforming source trees into result trees using an XSLT stylesheet is referred to as the processor. This is sometimes expanded to XSLT processor to avoid any confusion with other processors, for example an XML processor.]
[Definition: [Definition: A specific product that performs the functions of an XSLT processor is referred to as an implementation.]
[Definition: [Definition: 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.]
Note:
The use of the term tree in this document in phrases such as source tree, result tree, and temporary tree does not imply the use of a data structure in memory that holds the entire contents of the document at one time. It implies rather a logical view of the XML input and output in which elements have a hierarchic relationship to each other. When a source document is being processed in a streaming manner, access to the nodes in this tree is constrained, but it is still viewed and described as a tree.
The output of a transformation consists of the following:
[Definition: [Definition: A principal result: this can be any sequence of items (as defined in [XDM 4.0]).] The principal result is the value returned by the function or template in the stylesheet that is nominated as the entry point, as described in 2.3 Initiating a Transformation.
[Definition: [Definition: Zero or more secondary results: each secondary result can be any sequence of items (as defined in [XDM 4.0]).] A secondary result is the value returned by evaluating the body of an xsl:result-document instruction.
Zero or more messages. Messages are generated by the xsl:message and xsl:assert instructions, and are described in 23.1 Messages and 23.2 Assertions.
Static or dynamic errors: see 2.12 Error Handling.
The principal result and the secondary results may be post-processed as described in 2.3.6 Post-processing the Raw Result.
[Definition: [Definition: The term result tree is used to refer to any tree constructed by instructions in the stylesheet. A result tree is either a final result tree or a temporary tree.]
[Definition: [Definition: A final result tree is a result tree that forms part of the output of a transformation: specifically, a tree built by post-processing the items in the principal result or in a secondary result. Once created, the contents of a final result tree are not accessible within the stylesheet itself.] Any final result tree may be serialized as described in 26 Serialization.
[Definition: [Definition: The term source tree means any tree provided as input to the transformation. This includes the document containing the global context item if any, documents containing nodes present in the initial match selection, documents containing nodes supplied as the values of stylesheet parameters, documents obtained from the results of functions such as document, doc, and collection, documents read using the xsl:source-document instruction, and documents returned by extension functions or extension instructions. In the context of a particular XSLT instruction, the term source tree means any tree provided as input to that instruction; this may be a source tree of the transformation as a whole, or it may be a temporary tree produced during the course of the transformation.]
[Definition: [Definition: The term temporary tree means any tree that is neither a source tree nor a final result tree.] Temporary trees are used to hold intermediate results during the execution of the transformation.
Unless otherwise stated, the term “tree” refers to a tree rooted at a parentless node: that is, the term does not include subtrees of larger trees. Every node therefore belongs to exactly one tree.
In this specification the phrases must, must not, should, should not, may, required, and recommended, when used in normative text and rendered in small capitals, are to be interpreted as described in [RFC2119].
Where the phrase must, must not, or required relates to the behavior of the XSLT processor, then an implementation is not conformant unless it behaves as specified, subject to the more detailed rules in 27 Conformance.
Where the phrase must, must not, or required relates to a stylesheet then the processor must enforce this constraint on stylesheets by raising an error if the constraint is not satisfied.
Where the phrase should, should not, or recommended relates to a stylesheet then a processor may produce warning messages if the constraint is not satisfied, but must not treat this as an error.
[Definition: [Definition: In this specification, the term implementation-defined refers to a feature where the implementation is allowed some flexibility, and where the choices made by the implementation must be described in documentation that accompanies any conformance claim.]
[Definition: [Definition: The term implementation-dependent refers to a feature where the behavior may vary from one implementation to another, and where the vendor is not expected to provide a full specification of the behavior.] (This might apply, for example, to limits on the size of source documents that can be transformed.)
In all cases where this specification leaves the behavior implementation-defined or implementation-dependent, the implementation has the option of providing mechanisms that allow the user to influence the behavior.
A paragraph labeled as a Note or described as an example is non-normative.
Many terms used in this document are defined in the XPath specification [XPath 4.0] or the XDM specification [XDM 4.0]. Particular attention is drawn to the following:
[Definition: [Definition: 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.] For some items (for example, elements with element-only content, function items, and maps, atomization raises a dynamic error.
[Definition: [Definition: 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.]
[Definition: [Definition: 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.]
[Definition: [Definition: 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.]
[Definition: [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]]
[Definition: [Definition: A function definition has an arity range, which defines the minimum and maximum number of arguments that must be supplied in a call to the function. The static context can contain multiple function definitions with the same name, provided that their arity ranges do not overlap.]
[Definition: [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:
booleanOne 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) ...”.
stringAny string.
expressionAn XPath expression.
patternA pattern as described in 6.3 Patterns.
item-typeAn ItemTypeXP as defined in the XPath 4.0 specification.
sequence-typeA SequenceTypeXP as defined in the XPath 4.0 specification.
uri; urisA URI, for example a namespace URI or a collation URI; a whitespace-separated list of URIs.
qnameA lexical QName as defined in 5.1.1 Qualified Names.
eqname; eqnamesAn EQName as defined in 5.1.1 Qualified Names; a whitespace-separated list of EQNames.
token; tokensA string containing no significant whitespace; a whitespace-separated list of such strings.
nmtoken; nmtokensA string conforming to the XML schema rules for the type xs:NMTOKEN; a whitespace-separated list of such strings.
charA string comprising a single Unicode character.
languageA string in the value space of xs:language, or a zero-length string.
integerAn integer, that is, a string that is castable to the schema type xs:integer.
decimalA decimal value, that is, a string that is castable to the schema type xs:decimal.
ncname; ncnamesAn unprefixed name: a string that is castable to the schema type xs:NCName; a whitespace-separated list of such strings.
prefix; prefixesAn 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.
idAn 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.
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:
A mandatory select attribute, whose value is an XPath expression
An optional debug attribute, whose value must be yes, true, or 1 to indicate true, or no, false, or 0 to indicate false.
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.11 Stylesheet Preprocessing.
[Definition: [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.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: [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.
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.11.3 Conditional Element Inclusion) and shadow attributes (see 3.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: [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.
The information needed when priming a stylesheet is as follows:
A set (possibly empty) of values for non-static stylesheet parameters (see 9.5 Global Variables and Parameters). These values are available for use within expressions in the stylesheet. As a minimum, values must be supplied for any parameters declared with the attribute required="yes".
A supplied value is converted if necessary to the declared type of the stylesheet parameter using the coercion rules.
Note:
Non-static stylesheet parameters are implicitly public, which ensures that all the parameters in the stylesheet for which values can be supplied externally have distinct names. Static parameters, by contrast, are local to a package.
[Definition: [Definition: An item that is the global context item for the transformation acts as the context item when evaluating the select expression or sequence constructor of a global variablewhose declaration is within the top-level package, as described in 5.3.3.1 Maintaining Position: the Focus. The global context item may also be available in a named template when the stylesheet is invoked as described in 2.3.4 Call-Template Invocation].
Note:
In previous releases of this specification, a single node was typically supplied to represent the source document for the transformation. This node was used as the target node for the implicit call on xsl:apply-templates used to start the transformation process (now called the initial match selection), and the root node of the containing tree was used as the context item for evaluation of global variables (now called the global context item). This relationship between the initial match selection and the global context item is likely to be found for compatibility reasons in a transformation API designed to work with earlier versions of this specification, but it is no longer a necessary relationship; the two values can in principle be completely independent of each other.
Stylesheet authors wanting to write code that can be invoked using legacy APIs should not rely on the caller being able to supply different values for the initial match selection and the global context item.
In XPath 4.0, the concept of context item has been generalized and is now referred to as the context valueXP. For XSLT 4.0, however, the global context item is still constrained to be either a single item, or absent.
The value given to the global context item (and the values given to stylesheet parameters) cannot be nodes in a streamed document. This rule ensures that all global variables can freely navigate within the relevant tree, with no constraints imposed by the streamability rules.
The global context item is potentially used when initializing global variables and parameters. If the initialization of any global variables or parameter depends on the context item, a dynamic error can occur if the context item is absent. It is implementation-defined whether this error occurs during priming of the stylesheet or subsequently when the variable is referenced; and it is implementation-defined whether the error occurs at all if the variable or parameter is never referenced. The error can be suppressed by use of xsl:try and xsl:catch within the sequence constructor used to initialize the variable or parameter. It cannot be suppressed by use of xsl:try around a reference to the global variable.
In a library package, the context item, context position, and context size used for evaluation of global variables will be absent, and the evaluation of any expression that references these values will result in a dynamic error. This will also be the case in the top-level package if no global context item is supplied.
Note:
If a context item is available within a global variable declaration, then the context position and context size will always be 1 (one).
Note:
For maximum reusability of code, it is best to avoid use of the context item when initializing global variables and parameters. Instead, all external information should be supplied using named stylesheet parameters, ideally with namespaces, to avoid confusion and conflicts in the information supplied externally to different packages.
When a stylesheet parameter is defined in a library package, it is possible for a using package to supply a value for the parameter by overriding the parameter declaration within an xsl:override element. If the using package is the top-level package then the overriding declaration can refer to the global context item.
A mechanism for obtaining a document node and a media type, given an absolute URI. The total set of available documents (modeled as a mapping from URIs to document nodes) forms part of the context for evaluating XPath expressions, specifically the doc function. The XSLT document function additionally requires the media type of the resource representation, for use in interpreting any fragment identifier present within a URI Reference.
Note:
The set of documents that are available to the stylesheet is implementation-dependent, as is the processing that is carried out to construct a tree representing the resource retrieved using a given URI. Some possible ways of constructing a document (specifically, rules for constructing a document from an Infoset or from a PSVI) are described in [XDM 4.0].
Once a stylesheet is primed, the values of global variables remain stable through all component invocations. In addition, priming a stylesheet creates an execution scopeFO during which the dynamic context and all calls on deterministicFO functions remain stable; for example two calls on the current-dateTime function within an execution scope are defined to return the same result.
Parameters passed to the transformation by the client application when a stylesheet is primed are matched against stylesheet parameters (see 9.5 Global Variables and Parameters), not against the template parameters of any template executed during the course of the transformation.
[ERR XTDE0050] It is a dynamic error if a stylesheet declares a visible stylesheet parameter that is explicitly or implicitly mandatory, and no value for this parameter is supplied when the stylesheet is primed. A stylesheet parameter is visible if it is not masked by another global variable or parameter with the same name and higher import precedence. If the parameter is a static parameter then the value must be supplied prior to the static analysis phase.
[Definition: [Definition: A stylesheet may be evaluated by supplying a value to be processed, together with an initial mode. The value (which can be any sequence of items) is referred to as the initial match selection. The processing then corresponds to the effect of the xsl:apply-templates instruction.]
The initial match selection will often be a single document node, traditionally called the source document of the transformation; but in general, it can be any sequence. If the initial match selection is the empty sequence, the result of the transformation will be empty, since no template rules are evaluated.
Processing proceeds by finding the template rules that match the items in the initial match selection, and evaluating these template rules with a focus based on the initial match selection. The template rules are evaluated in final output state.
The following information is needed when dynamic evaluation is to start with a template rule:
The initial match selection. An API that chooses to maintain compatibility with previous versions of this specification should allow a method of invocation in which a singleton node is provided, which is then used in two ways: the node itself acts as the initial match selection, and the root node of the containing tree acts as the global context item.
Optionally, an initial mode.
[Definition: [Definition: The initial mode is the mode used to select template rules for processing items in the initial match selection when apply-templates invocation is used to initiate a transformation.]
In searching for the template rule that best matches the items in the initial match selection, the processor considers only those rules that apply to the initial mode.
If no initial mode is supplied explicitly, then the initial mode is that named in the default-mode attribute of the (explicit or implicit) xsl:package element of the top-level package or in the absence of such an attribute, the unnamed mode.
[ERR XTDE0044] It is a dynamic error if the invocation of the stylesheet specifies an initial mode when no initial match selection is supplied (either explicitly, or defaulted to the global context item).
A (named or unnamed) modeM is eligible as an initial mode if one of the following conditions applies, where P is the top-level package of the stylesheet:
M is explicitly declared in an xsl:mode declaration within P, and has public or finalvisibility (either by virtue of its visibility attribute, or by virtue of an xsl:expose declaration).
M is the unnamed mode.
M is named in the default-mode attribute of the (explicit or implicit) xsl:package element of P.
M is declared in a package used by P, and is given public or finalvisibility in P by means of an xsl:accept declaration.
The effective value of the declared-modes attribute of the explicit or implicit xsl:package element of P is no, and M appears as a mode-name in the mode attribute of a template rule declared within P.
[ERR XTDE0045] It is a dynamic error if the invocation of the stylesheet specifies an initial mode and the specified mode is not eligible as an initial mode (as defined above).
Parameters, which will be passed to the template rules used to process items in the input sequence. The parameters consist of two sets of (QName, value) pairs, one set for tunnel parameters and one for non-tunnel parameters, in which the QName identifies the name of a parameter and the value provides the value of the parameter. Either or both sets of parameters may be empty. The effect is the same as when a template is invoked using xsl:apply-templates with an xsl:with-param child specifying tunnel="yes" or tunnel="no" as appropriate. If a parameter is supplied that is not declared or used, the value is simply ignored. These parameters are not used to set stylesheet parameters.
A supplied value is converted if necessary to the declared type of the template parameter using the coercion rules.
Details of how the result of the initial template is to be returned. For details, see 2.3.6 Post-processing the Raw Result
The raw result of the invocation is the result of processing the supplied input sequence as if by a call on xsl:apply-templates in the specified mode: specifically, each item in the input sequence is processed by selecting and evaluating the best matching template rule, and converting the result (if necessary) to the type declared in the as attribute of that template using the coercion rules; and the results of processing each item are then concatenated into a single sequence, respecting the order of items in the input sequence.
Note:
The design of the API for invoking a transformation should provide some means for users to designate the unnamed mode as the initial mode in cases where it is not the default mode.
It is a dynamic error[see ERR XTDE0700] if the template rule selected for processing any item in the initial match selection defines a template parameter that specifies required="yes" and no value is supplied for that parameter.
Note:
A stylesheet can process further source documents in addition to those supplied when the transformation is invoked. These additional documents can be loaded using the functions document (see 20.1 fn:document); or doc, unparsed-text, unparsed-text-lines, or collection (see [Functions and Operators 4.0]); or using the xsl:source-document instruction; alternatively, they can be supplied as stylesheet parameters (see 9.5 Global Variables and Parameters), or returned as the result of an extension function (see 24.2 Extension Functions).
[Definition: [Definition: A stylesheet may be evaluated by selecting a named template to be evaluated; this is referred to as the initial named template.] The effect is analogous to the effect of executing an xsl:call-template instruction. The following information is needed in this case:
Optionally, the name of the initial named template which is to be executed as the entry point to the transformation. If no template name is supplied, the default template name is xsl:initial-template. The selected template must exist within the stylesheet.
Optionally, a context item for evaluation of this named template, defaulting to the global context item if it exists. This is constrained by any xsl:context-item element appearing within the selected xsl:template element. The initial named template is evaluated with a singleton focus based on this context item if it exists, or with an absent focus otherwise.
Note:
The context item for evaluation of the named template must be either a single item or absent; it cannot be an arbitrary value.
Parameters, which will be passed to the selected template rule. The parameters consist of two sets of (QName, value) pairs, one set for tunnel parameters and one for non-tunnel parameters, in which the QName identifies the name of a parameter and the value provides the value of the parameter. Either or both sets of parameters may be empty. The effect is the same as when a template is invoked using xsl:call-template with an xsl:with-param child specifying tunnel="yes" or tunnel="no" as appropriate. If a parameter is supplied that is not declared or used, the value is simply ignored. These parameters are not used to set stylesheet parameters.
A supplied value is converted if necessary to the declared type of the template parameter using the coercion rules.
Details of how the result of the initial named template is to be returned. For details, see 2.3.6 Post-processing the Raw Result
The raw result of the invocation is the result of evaluating the initial named template, after conversion of the result to the type declared in the as attribute of that template using the coercion rules, if such conversion is necessary.
The initial named template is evaluated in final output state.
[ERR XTDE0040] It is a dynamic error if the invocation of the stylesheet specifies a template name that does not match the expanded QName of a named template defined in the stylesheet, whose visibility is public or final.
Note:
When the top-level package is rooted at an xsl:stylesheet or xsl:transform element, named templates having no explicit visibility attribute are automatically exposed as public components. (This is a consequence of the transformation applied to a package written using “simplified syntax”, described in 3.4 Packages.)
It is a dynamic error[see ERR XTDE0700] if the initial named template, or any of the template rules invoked to process items in the initial match selection, defines a template parameter that specifies required="yes" and no value is supplied for that parameter.
[Definition: [Definition: A stylesheet may be evaluated by calling a named stylesheet function, referred to as the initial function.] The following additional information is needed in this case:
The name and arity of a stylesheet function which is to be executed as the entry point to the transformation.
Note:
In the design of a concrete API, the arity may be inferred from the length of the parameter list.
A list of values to act as parameters to the initial function. The number of values in the list must be the same as the arity of the function.
A supplied value is converted if necessary to the declared type of the function parameter using the coercion rules.
Details of how the result of the initial function is to be returned. For details, see 2.3.6 Post-processing the Raw Result
The raw result of the invocation is the result of evaluating the initial function, after conversion of the result to the type declared in the as attribute of that function using the coercion rules, if such conversion is necessary.
Note:
The initial function (like all stylesheet functions) is evaluated with an absentfocus.
If the initial function is declared-streamableSG, a streaming processor should allow the value of the first argument to be supplied in streamable form, and if it is supplied in this form, then it must be processed using streaming.
[ERR XTDE0041] It is a dynamic error if the invocation of the stylesheet specifies a function name and arity that does not match the expanded QName and arity of a named stylesheet function defined in the stylesheet, whose visibility is public or final.
When a transformation is invoked by calling an initial function, the entire transformation executes in temporary output state, which means that calls on xsl:result-document are not permitted.
[TODO: Generalize the above description to allow for the possibility of keyword-based and optional arguments.]
There are three ways the result of a transformation may be delivered. (This applies both to the principal result, described here, and also to secondary results, generated using xsl:result-document.)
The raw result (a sequence of values) may be returned directly to the calling application.
A result tree may be constructed from the raw result. By default, a result tree is constructed if the build-tree attribute of the unnamed output definition has the effective valueyes. An API for invoking transformations may allow this setting to be overridden by the calling application. If result tree construction is requested, it is performed as described in 2.3.6.1 Result Tree Construction.
Alternatively, the raw result may be serialized as described in 2.3.6.2 Serializing the Result. The decision whether or not to serialize the result is determined by the rules of transformation API provided by the processor, and is not influenced by anything in the stylesheet.
Note:
This specification does not constrain the design of application programming interfaces or the choice of defaults. In previous versions of this specification, result tree construction was a mandatory process, while serialization was optional. When invoking stylesheet functions directly, however, result tree construction and serialization may be inappropriate as defaults. These considerations may affect the design of APIs.
In previous versions of XSLT, results were delivered either in serialized form (as a character or byte stream), or as a tree. In the latter case processors typically would use either their own tree representation, or a standardized tree representation such as the W3C Document Object Model (DOM) (see [DOM Level 2]), adapted to the data structures offered by the programming language in which the API is defined. To deliver a raw result, processors need to define a representation not only of XDM nodes but also of sequences, atomic items, maps, arrays, and even functions. As with the return of a simple tree, this may involve a trade-off between strict fidelity to the XDM data model and usability in the particular programming language environment. It is not a requirement that an API should return results in a way that exposes every property of the XDM data model; for example there may be APIs that do not expose the precise type annotation of a returned node or atomic item, or that fail to expose the base URI or document URI of a node, or that provide no way of determining whether two nodes in the result sequence are the same node in the sense of the XPath is operator. The way in which maps, arrays, and functions are returned requires careful design choices. It is recommended that an API should be capable of returning any XDM value without error, and that there should be minimal loss of information if the raw results output by one transformation are subsequently used as input to another transformation.
See 2.7 Parsing and Serialization.
The raw result may optionally be serialized as described in 26 Serialization. The serialization is controlled by the serialization parameters defined in the unnamed output definition of the top-level package.
Note:
The first phase of serialization, called sequence normalizationSE, takes place for some output methods but not others. For example, if the json output method (defined in [Serialization 4.0]) is selected, then the process of constructing a tree is bypassed.
The effect of serialization is to generate a sequence of octets, representing the serialized result in some character encoding. The processor’s API may define mechanisms enabling this sequence of octets to be written to persistent storage at some location. The default location is the location identified by the base output URI.
In previous versions of this specification it was stated that when the raw result of the initial template or function is the empty sequence, a result tree should be produced if and only if the transformation generates no secondary results (that is, if it does not invoke xsl:result-document). This provision is most likely to have a noticeable effect if the transformation produces serialized results, and these results are written to persistent storage: the effect is then that a transformation producing the empty principal result will overwrite any existing content at the base output URI location if and only if the transformation produces no other output. Processor APIs offering backwards compatibility with earlier versions of XSLT must respect this behavior, but there is no requirement for new processor APIs to do so.
[Definition: [Definition: The base output URI is a URI to be used as the base URI when resolving a relative URI reference allocated to a final result tree. If the transformation generates more than one final result tree, then typically each one will be allocated a URI relative to this base URI.] The way in which a base output URI is established is implementation-defined. Each invocation of the stylesheet may supply a different base output URI. It is acceptable for the base output URI to be absent, provided no constructs (such as xsl:result-document) are evaluated that depend on the value of the base output URI.
Note:
It will often be convenient for the base output URI to be the same as the location to which the principal result document is serialized, but this relationship is not a necessary one.
The main executable components of a stylesheet are templates and functions. The body of a template or function is a sequence constructor, which is a sequence of elements and text nodes that can be evaluated to produce a result.
A sequence constructor is a sequence of sibling nodes in the stylesheet, each of which is either an XSLT instruction, a literal result element, a text node, or an extension instruction.
[Definition: [Definition: An instruction is either an XSLT instruction or an extension instruction.]
[Definition: [Definition: An XSLT instruction is an XSLT element whose syntax summary in this specification contains the annotation <!-- category: instruction -->.]
Extension instructions are described in 24.3 Extension Instructions.
The main categories of XSLT instruction are as follows:
instructions that create new nodes: xsl:document, xsl:element, xsl:attribute, xsl:processing-instruction, xsl:comment, xsl:value-of, xsl:text, xsl:namespace;
instructions that construct maps and arrays: xsl:array, xsl:map, xsl:map-entry, xsl:record;
instructions that copy nodes: xsl:copy, xsl:copy-of;
instructions that returns an arbitrary sequence by evaluating an XPath expression: xsl:sequence, xsl:select, xsl:evaluate;
instructions that cause conditional or repeated evaluation of nested instructions: xsl:if, xsl:choose, xsl:switch, xsl:try, xsl:for-each, xsl:for-each-group, xsl:fork, xsl:iterate and its subordinate instructions xsl:next-iteration and xsl:break;
instructions that generate output conditionally if elements are or are not empty: xsl:on-empty, xsl:on-non-empty, xsl:where-populated;
instructions that invoke templates: xsl:apply-templates, xsl:apply-imports, xsl:call-template, xsl:next-match;
Instructions that declare variables: xsl:variable;
Instructions to assist debugging: xsl:message, xsl:assert;
other specialized instructions: xsl:number, xsl:analyze-string, xsl:fork, xsl:result-document, xsl:source-document, xsl:perform-sort, xsl:merge.
The classic method of executing an XSLT transformation is to apply template rules to the root node of an input document (see 2.3.3 Apply-Templates Invocation). The operation of applying templates to a node searches the stylesheet for the best matching template rule for that node. This template rule is then evaluated. A common coding pattern, especially when XSLT is used to convert XML documents into display formats such as HTML, is to have one template rule for each kind of element in the source document, and for that template rule to generate some appropriate markup elements, and to apply templates recursively to its own children. The effect is to perform a recursive traversal of the source tree, in which each node is processed using the best-fit template rule for that node. The final result of the transformation is then the tree produced by this recursive process. This result can then be optionally serialized (see 2.3.6 Post-processing the Raw Result).
This example uses rule-based processing to convert a simple XML input document into an HTML output document.
The input document takes the form:
<PERSONAE PLAY="OTHELLO">
<TITLE>Dramatis Personae</TITLE>
<PERSONA>DUKE OF VENICE</PERSONA>
<PERSONA>BRABANTIO, a senator.</PERSONA>
<PERSONA>Other Senators.</PERSONA>
<PERSONA>GRATIANO, brother to Brabantio.</PERSONA>
<PERSONA>LODOVICO, kinsman to Brabantio.</PERSONA>
<PERSONA>OTHELLO, a noble Moor in the service of the Venetian state.</PERSONA>
<PERSONA>CASSIO, his lieutenant.</PERSONA>
<PERSONA>IAGO, his ancient.</PERSONA>
<PERSONA>RODERIGO, a Venetian gentleman.</PERSONA>
<PERSONA>MONTANO, Othello's predecessor in the government of Cyprus.</PERSONA>
<PERSONA>Clown, servant to Othello. </PERSONA>
<PERSONA>DESDEMONA, daughter to Brabantio and wife to Othello.</PERSONA>
<PERSONA>EMILIA, wife to Iago.</PERSONA>
<PERSONA>BIANCA, mistress to Cassio.</PERSONA>
<PERSONA>Sailor, Messenger, Herald, Officers,
Gentlemen, Musicians, and Attendants.</PERSONA>
</PERSONAE>The stylesheet to render this as HTML can be written as a set of template rules:
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
version="3.0"
expand-text="yes">
<xsl:strip-space elements="PERSONAE"/>
<xsl:template match="PERSONAE">
<html>
<head>
<title>The Cast of {@PLAY}</title>
</head>
<body>
<xsl:apply-templates/>
</body>
</html>
</xsl:template>
<xsl:template match="TITLE">
<h1>{.}</h1>
</xsl:template>
<xsl:template match="PERSONA[count(tokenize(., ',')) = 2]">
<p><b>{substring-before(., ',')}</b>: {substring-after(., ',')}</p>
</xsl:template>
<xsl:template match="PERSONA">
<p><b>{.}</b></p>
</xsl:template>
</xsl:stylesheet>There are four template rules here:
The first rule matches the outermost element, named PERSONAE (it could equally have used match="/" to match the document node). The effect of this rule is to create the skeleton of the output HTML page. Technically, the body of the template is a sequence constructor comprising a single literal result element (the html element); this in turn contains a sequence constructor comprising two literal result elements (the head and body elements). The head element is populated with a literal title element whose content is computed as a mixture of fixed and variable text using a text value template. The body element is populated by evaluating an xsl:apply-templates instruction.
The effect of the xsl:apply-templates instruction is to process the children of the PERSONAE element in the source tree: that is, the TITLE and PERSONA elements. (It would also process any whitespace text node children, but these have been stripped by virtue of the xsl:strip-space declaration.) Each of these child elements is processed by the best matching template rule for that element, which will be one of the other three rules in the stylesheet.
The template rule for the TITLE element outputs an h1 element to the HTML result document, and populates this with the value of ., the context item. That is, it copies the text content of the TITLE element to the output h1 element.
The last two rules match PERSONA elements. The first rule matches PERSONA elements whose text content contains exactly one comma; the second rule matches all PERSONA elements, but it has lower priority than the first rule (see 6.3.3 Default Priority for Patterns), so in practice it applies only to PERSONA elements that contain no comma or multiple commas.
For both rules the body of the rule is a sequence constructor containing a single literal result element, the p element. These literal result elements contain further sequence constructors comprising literal result elements and text nodes. In each of these examples the text nodes are in the form of a text value template: in general this is a combination of fixed text together with XPath expressions enclosed in curly braces, which are evaluated to form the content of the containing literal result element.
[Definition: [Definition: 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.] In many cases these items are newly constructed nodes, which are then written to a result tree.
An XSLT stylesheet describes a process that constructs a set of results from a set of inputs. The inputs are the data provided at stylesheet invocation, as described in 2.3 Initiating a Transformation. The results include the principal result (an arbitrary sequence), which is the result of the initial component invocation, together with any secondary results produced using xsl:result-document instructions.
The stylesheet does not describe how a source tree is constructed. Some possible ways of constructing source trees are described in [XDM 4.0]. Frequently an implementation will operate in conjunction with an XML parser (or more strictly, in the terminology of [XML 1.0], an XML processor), to build a source tree from an input XML document. An implementation may also provide an application programming interface allowing the tree to be constructed directly, or allowing it to be supplied in the form of a DOM Document object (see [DOM Level 2]). This is outside the scope of this specification. Users should be aware, however, that since the input to the transformation is a tree conforming to the XDM data model as described in [XDM 4.0], constructs that might exist in the original XML document, or in the DOM, but which are not within the scope of the data model, cannot be processed by the stylesheet and cannot be guaranteed to remain unchanged in the transformation output. Such constructs include CDATA section boundaries, the use of entity references, and the DOCTYPE declaration and internal DTD subset.
[Definition: [Definition: A frequent requirement is to output a final result tree as an XML document (or in other formats such as HTML). This process is referred to as serialization.]
Like parsing, serialization is not part of the transformation process, and it is not required that an XSLT processor must be able to perform serialization. However, for pragmatic reasons, this specification describes declarations (the xsl:output element and the xsl:character-map declarations, see 26 Serialization), and attributes on the xsl:result-document instruction, that allow a stylesheet to specify the desired properties of a serialized output file. When serialization is not being performed, either because the implementation does not support the serialization option, or because the user is executing the transformation in a way that does not invoke serialization, then the content of the xsl:output and xsl:character-map declarations has no effect. Under these circumstances the processor may raise any errors in an xsl:output or xsl:character-map declaration, or in the serialization attributes of xsl:result-document, but is not required to do so.
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: [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: [Definition: Type definitions and element and attribute declarations are referred to collectively as schema components.]
[Definition: [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.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.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:
<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:
<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.
Streaming is an optional feature of the XSLT 4.0 language.
[Definition: [Definition: 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.]
[Definition: [Definition: A streamed document is a source tree that is processed using streaming, that is, without constructing a complete tree of nodes in memory.]
[Definition: [Definition: A streamed node is a node in a streamed document.]
For full information about streaming, see [XSLT 4.0 Streaming].
[Definition: [Definition: An error that can be detected by examining a stylesheet before execution starts (that is, before the source document and values of stylesheet parameters are available) is referred to as a static error.]
Generally, errors in the structure of the stylesheet, or in the syntax of XPath expressions contained in the stylesheet, are classified as static errors. Where this specification states that an element in the stylesheet must or must not appear in a certain position, or that it must or must not have a particular attribute, or that an attribute must or must not have a value satisfying specified conditions, then any contravention of this rule is a static error unless otherwise specified.
A processor must provide a mode of operation that takes a (possibly erroneous) stylesheet package as input and enables the user to determine whether or not that package contains any static errors.
Note:
The manner in which static errors are reported, and the behavior when there are multiple static errors, are left as design choices for the implementer. It is recommended that the error codes defined in this specification should be made available in any diagnostics.
A processor may also provide a mode of operation in which static errors in parts of the stylesheet that are not evaluated can go unreported.
Note:
For example, when operating in this mode, a processor might report static errors in a template rule only if the input document contains nodes that match that template rule. Such a mode of operation can provide performance benefits when large and well-tested stylesheets are used to process source documents that might only use a small part of the XML vocabulary that the stylesheet is designed to handle.
[Definition: [Definition: An error that is not capable of detection until a source document is being transformed is referred to as a dynamic error.]
When a dynamic error occurs, and is not caught using xsl:catch, the processormust raise the error, and the transformation fails.
Because different implementations may optimize execution of the stylesheet in different ways, the detection of dynamic errors is to some degree implementation-dependent. In cases where an implementation is able to produce a principal result or secondary result without evaluating a particular construct, the implementation is never required to evaluate that construct solely in order to determine whether doing so causes a dynamic error. For example, if a variable is declared but never referenced, an implementation may choose whether or not to evaluate the variable declaration, which means that if evaluating the variable declaration causes a dynamic error, some implementations will raise this error and others will not.
There are some cases where this specification requires that a construct must not be evaluated: for example, the content of an xsl:if instruction must not be evaluated if the test condition is false. This means that an implementation must not raise any dynamic errors that would arise if the construct were evaluated.
An implementation may raise a dynamic error before any source document is available, but only if it can determine that the error would be raised for every possible source document and every possible set of parameter values. For example, some circularity errors fall into this category: see 9.11 Circular Definitions.
There are also some dynamic errors where the specification gives a processor license to raise the error during the analysis phase even if the construct might never be executed; an example is the use of an invalid QName as a literal argument to a function such as key, or the use of an invalid regular expression in the regex attribute of the xsl:analyze-string instruction.
A dynamic error is also raised during the static analysis phase if the error occurs during evaluation of a static expression.
The XPath specification states (see [XPath 4.0] section 2.5.1 Kinds of Errors) that if any expression (at any level) can be evaluated during the analysis phase (because all its explicit operands are known and it has no dependencies on the dynamic context), then any error in performing this evaluation may be raised as a static error. For XPath expressions used in an XSLT stylesheet, however, any such errors must not be raised as static errors in the stylesheet unless they would occur in every possible evaluation of that stylesheet; instead, they must be raised as dynamic errors, and raised only if the XPath expression is actually evaluated.
An XPath processor may report statically that the expression 1 div 0 fails with a “divide by zero” error. But suppose this XPath expression occurs in an XSLT construct such as:
<xsl:choose>
<xsl:when test="system-property('xsl:version') = '1.0'">
<xsl:value-of select="1 div 0"/>
</xsl:when>
<xsl:otherwise>
<xsl:value-of select="xs:double('INF')"/>
</xsl:otherwise>
</xsl:choose>Then the XSLT processor must not report an error, because the relevant XPath construct appears in a context where it will never be executed by an XSLT 4.0 processor. (An XSLT 1.0 processor will execute this code successfully, returning positive infinity, because it uses double arithmetic rather than decimal arithmetic.)
[Definition: [Definition: Certain errors are classified as type errors. A type error occurs when the value supplied as input to an operation is of the wrong type for that operation, for example when an integer is supplied to an operation that expects a node.] If a type error occurs in an instruction that is actually evaluated, then it must be raised in the same way as a dynamic error. Alternatively, an implementation may raise a type error during the analysis phase in the same way as a static error, even if it occurs in part of the stylesheet that is never evaluated, provided it can establish that execution of a particular construct would never succeed.
It is implementation-defined whether type errors are raised statically.
The following construct contains a type error, because 42 is not allowed as the value of the select expression of the xsl:number instruction (it must be a node). An implementation may optionally raise this as a static error, even though the offending instruction will never be evaluated, and the type error would therefore never be raised as a dynamic error.
<xsl:if test="false()"> <xsl:number select="42"/> </xsl:if>
On the other hand, in the following example it is not possible to determine statically whether the operand of xsl:number will have a suitable dynamic type. An implementation may produce a warning in such cases, but it must not treat it as an error.
<xsl:template match="para"> <xsl:param name="p" as="item()"/> <xsl:number select="$p"/> </xsl:template>
If more than one error arises, an implementation is not required to raise any errors other than the first one that it detects. It is implementation-dependent which of the several errors is raised. This applies both to static errors and to dynamic errors. An implementation is allowed to raise more than one error, but if any errors have been raised, it must not finish as if the transformation were successful.
When a transformation raises one or more dynamic errors, the final state of any persistent resources updated by the transformation is implementation-dependent. Implementations are not required to restore such resources to their initial state. In particular, where a transformation produces multiple result documents, it is possible that one or more serialized result documents may be written successfully before the transformation terminates, but the application cannot rely on this behavior.
Everything said above about error handling applies equally to errors in evaluating XSLT instructions, and errors in evaluating XPath expressions. Static errors and dynamic errors may occur in both cases.
[Definition: [Definition: If a transformation has successfully produced a principal result or secondary result, it is still possible that errors may occur in serializing that result . For example, it may be impossible to serialize the result using the encoding selected by the user. Such an error is referred to as a serialization error.] If the processor performs serialization, then it must do so as specified in 26 Serialization, and in particular it must raise any serialization errors that occur.
Errors are identified by a QName. For errors defined in this specification, the namespace of the QName is always http://www.w3.org/2005/xqt-errors (and is therefore not given explicitly), while the local part is an 8-character code in the form PPSSNNNN. Here PP is always XT (meaning XSLT), and SS is one of SE (static error), DE (dynamic error), or TE (type error). Note that the allocation of an error to one of these categories is purely for convenience and carries no normative implications about the way the error is handled. Many errors, for example, can be raised either dynamically or statically. These error codes are used to label error conditions in this specification, and are summarized in D Summary of Error Conditions.
Errors defined in related specifications ([XPath 4.0], [Functions and Operators 4.0][Serialization 4.0]) use QNames with a similar structure, in the same namespace. When errors occur in processing XPath expressions, an XSLT processor should use the original error code reported by the XPath processor, unless a more specific XSLT error code is available.
Implementations must use the codes defined in these specifications when raising dynamic errors, to ensure that xsl:catch behaves in an interoperable way across implementations. Stylesheet authors should note, however, that there are many examples of errors where more than one rule in this specification is violated, and where the processor therefore has discretion in deciding which error code to associate with the condition: there is therefore no guarantee that different processors will always use the same error code for the same erroneous input.
Additional errors defined by an implementation (or by an application) may use QNames in an implementation-defined (or user-defined) namespace without risk of collision.
This section describes the overall structure of a stylesheet as a collection of XML documents.
A stylesheet module is typically written as a namespace well-formed XML document: more formally, as described in 3.5 Stylesheet Modules, a stylesheet module takes the form of an XDM tree rooted at an element node.
The names of elements and attributes in source documents and result documents are namespace-qualified names. In addition, as described in 5.1.1 Qualified Names, XSLT uses namespace-qualified names to identify variables, functions, templates, and other components. These names generally use namespace prefixes that are resolved to namespace URIs using a set of prefix-uri namespace bindings.
There are two ways namespace bindings can be established in a stylesheet module:
[Definition: [Definition: The native namespace bindings for any element in an XSLT stylesheet module are the prefix-uri mappings defined by the namespace nodes of that element, according to the rules in [XDM 4.0].]
For example, a namespace declaration of the form xmlns:math="http://www.w3.org/2005/xpath-functions/math establishes a binding of the prefix math to the namespace URI http://www.w3.org/2005/xpath-functions/math, thereby enabling functions in that namespace to be invoked using an expression such as math:sin($theta)
[Definition: [Definition: The fixed namespace bindings for a stylesheet module are established using the fixed-namespaces attribute on the xsl:stylesheet, xsl:transform, or xsl:package element enclosing the stylesheet module.]
For example, the attribute fixed-namespaces="math map array" establishes bindings for the prefixes math, map, and array to the namespace URIs conventionally associated with these prefixes as described in 5.1.3 Reserved Namespaces.
Prefixes used in element and attribute names in the stylesheet, because these are interpreted by the XML parser and not only by the XSLT processor, must be bound using native namespace bindings. In particular, the XSLT namespace is used in the names of XSLT elements, so it must be declared in every stylesheet module using a namespace declaration such as xmlns:xsl="http://www.w3.org/1999/XSL/Transform. (A different prefix can be used: some users prefer xslt, some favor the default namespace.) But namespace prefixes that are only used within the content of attribute and text nodes in the stylesheet (for example, select="math:sin($theta)") can be declared in fixed namespace bindings.
[Definition: [Definition: The applicable static namespaces for an element in a stylesheet module are the fixed namespace bindings for the module if the root element of the module has a fixed-namespaces attribute, or the native namespace bindings of the element otherwise. ]
The effect of declaring fixed namespace bindings is described in more detail in 3.6.1 The fixed-namespaces Attribute.
Note:
As a general rule:
Prefixes used in the names of elements and attributes in the stylesheet must be declared using native namespace bindings.
Prefixes used in QNames appearing in the content of attribute nodes and text nodes in the stylesheet can usually be declared using fixed namespace bindings. There are a small number of exceptions, notably the standard attributes [xsl:]exclude-result-prefixes and [xsl:]extension-element-prefixes, and the stylesheet-prefix and result-prefix attributes of xsl:namespace-alias.
[Definition: [Definition: The XSLT namespace has the URI http://www.w3.org/1999/XSL/Transform. It is used to identify elements, attributes, and other names that have a special meaning defined in this specification.]
Note:
The 1999 in the URI indicates the year in which the URI was allocated by the W3C. It does not indicate the version of XSLT being used, which is specified by attributes (see 3.6 Stylesheet Element and 3.7 Simplified Stylesheet Modules).
XSLT processorsmust use the XML namespaces mechanism [Namespaces in XML] to recognize elements and attributes from this namespace. Elements from the XSLT namespace are recognized only in the stylesheet and not in the source document. The complete list of XSLT-defined elements is specified in C Element Syntax Summary. Implementationsmust not extend the XSLT namespace with additional elements or attributes. Instead, any extension must be in a separate namespace. Any namespace that is used for additional instruction elements must be identified by means of the extension instruction mechanism specified in 24.3 Extension Instructions.
Except where the rules for forwards compatible behavior dictate otherwise, it is a static error for any element in the stylesheet to be in the XSLT namespace unless it is an element defined in this specification [see ERR XTSE0010].
This specification uses a prefix of xsl: for referring to elements in the XSLT namespace. However, XSLT stylesheets are free to use any prefix, provided that there is a namespace declaration that binds the prefix to the URI of the XSLT namespace.
Note:
Throughout this specification, an element or attribute that is in no namespace, or an expanded QName whose namespace part is the empty sequence, is referred to as having a null namespace URI.
Note:
By convention, the names of XSLT elements, attributes and functions are all lower-case; they use hyphens to separate words, and they use abbreviations only if these already appear in the syntax of a related language such as XML or HTML. Names of types defined in XML Schema are regarded as single words and are capitalized exactly as in XML Schema. This sometimes leads to composite function names such as current-dateTime.
[Definition: [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.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[xsl:]default-mode[xsl:]default-validationsee 25.4 Validation
[xsl:]exclude-result-prefixes[xsl:]expand-text[xsl:]extension-element-prefixes[xsl:]schema-role[xsl:]use-when[xsl:]versionsee 3.8 Backwards Compatible Processing and 3.9 Forwards Compatible Processing
[xsl:]xpath-default-namespacesee 5.1.2 Unprefixed Lexical QNames in Expressions and Patterns
[Definition: [Definition: An explicit package is represented by an xsl:package element, which will generally be the outermost element of an XML document. When the xsl:package element is not used explicitly, the entire stylesheet comprises a single implicit package.] (This specification does not preclude the xsl:package being embedded in another XML document, but it will never have any other XSLT element as an ancestor).
<xsl:package
id? = id
name? = uri
package-version? = string〔'1'〕
version = decimal
input-type-annotations? = "preserve" | "strip" | "unspecified"〔'unspecified'〕
declared-modes? = boolean〔'yes'〕
default-mode? = eqname | "#unnamed"〔'#unnamed'〕
default-validation? = "preserve" | "strip"〔'strip'〕
default-collation? = uris
extension-element-prefixes? = prefixes
exclude-result-prefixes? = prefixes
expand-text? = boolean〔'no'〕
fixed-namespaces? = string
schema-role? = ncname
use-when? = expression〔true()〕
xpath-default-namespace? = uri >
<!-- Content: ((xsl:expose | declarations)*) -->
</xsl:package>
[Definition: [Definition: The content of the xsl:package element is referred to as the package manifest].
The version attribute indicates the version of the XSLT language specification to which the package manifest conforms. The value should normally be 4.0. If the value is numerically less than 4.0, the content of the xsl:package element is processed using the rules for backwards compatible behavior (see 3.8 Backwards Compatible Processing). If the value is numerically greater than 4.0, it is processed using the rules for forwards compatible behavior (see 3.9 Forwards Compatible Processing).
A package typically has a name, given in its name attribute, which must be an absolute URI. Unnamed packages are allowed, but they can only be used as the “top level” of an application; they cannot be the target of an xsl:use-package declaration in another package.
A package may have a version identifier, given in its package-version attribute. This is used to distinguish different versions of a package. The value of the version attribute, after trimming leading and trailing whitespace, must conform to the syntax given in 3.4.1 Versions of a Package. If no version number is specified for a package, version 1 is assumed.
The attributes default-collation, default-mode, default-validation, exclude-result-prefixes, expand-text, extension-element-prefixes, use-when, version, and xpath-default-namespace are standard attributes that can appear on any XSLT element, and potentially affect all descendant elements. Their meaning is described in 3.3 Standard Attributes.
The package manifest contains the following elements, arbitrarily ordered:
Zero or more xsl:expose declarations that define the interface offered by this package to the outside world. An xsl:expose declaration may appear only as a child of xsl:package.
Zero or more additional declarations. These are the same as the declarations permitted as children of xsl:stylesheet or xsl:transform.
Some declarations of particular relevance to packages include:
The xsl:use-package declaration, which declares the names and versions of the packages on which this package depends.
The optional xsl:global-context-item element; if present this element defines constraints on the existence and type of the global context item.
Zero or more xsl:include and xsl:import declarations, which define additional stylesheet modules to be incorporated into this package.
Zero or more ordinary declarations, that is, elements that are permitted as children of xsl:stylesheet or xsl:transform. One possible coding style is to include in the package manifest just a single xsl:import or xsl:include declaration as a reference to the effective top-level stylesheet module; this approach is particularly suitable when writing code that is required to run under releases of XSLT earlier than 3.0. Another approach is to include the substance of the top-level stylesheet module inline within the package manifest.
The following example shows a package that offers a number of functions for manipulating complex numbers. A complex number is represented as a map with two entries, the keys being 0 for the real part, and 1 for the imaginary part.
<xsl:package
name="http://example.org/complex-arithmetic.xsl"
package-version="1.0"
version="3.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:xs="http://www.w3.org/2001/XMLSchema"
xmlns:f="http://example.org/complex-arithmetic.xsl">
<xsl:function name="f:complex-number"
as="map(xs:integer, xs:double)" visibility="public">
<xsl:param name="real" as="xs:double"/>
<xsl:param name="imaginary" as="xs:double"/>
<xsl:sequence select="{ 0: $real, 1: $imaginary }"/>
</xsl:function>
<xsl:function name="f:real"
as="xs:double" visibility="public">
<xsl:param name="complex" as="map(xs:integer, xs:double)"/>
<xsl:sequence select="$complex(0)"/>
</xsl:function>
<xsl:function name="f:imag"
as="xs:double" visibility="public">
<xsl:param name="complex" as="map(xs:integer, xs:double)"/>
<xsl:sequence select="$complex(1)"/>
</xsl:function>
<xsl:function name="f:add"
as="map(xs:integer, xs:double)" visibility="public">
<xsl:param name="x" as="map(xs:integer, xs:double)"/>
<xsl:param name="y" as="map(xs:integer, xs:double)"/>
<xsl:sequence select="
f:complex-number(
f:real($x) + f:real($y),
f:imag($x) + f:imag($y))"/>
</xsl:function>
<xsl:function name="f:multiply"
as="map(xs:integer, xs:double)" visibility="public">
<xsl:param name="x" as="map(xs:integer, xs:double)"/>
<xsl:param name="y" as="map(xs:integer, xs:double)"/>
<xsl:sequence select="
f:complex-number(
f:real($x)*f:real($y) - f:imag($x)*f:imag($y),
f:real($x)*f:imag($y) + f:imag($x)*f:real($y))"/>
</xsl:function>
<!-- etc. -->
</xsl:package>A more complex package might include private or abstract functions as well as public functions; it might expose components other than functions (for example, templates or global variables), and it might contain xsl:use-package elements to allow it to call on the services of other packages.
Note:
In this example, the way in which complex numbers are represented is exposed to users of the package. It would be possible to hide the representation by declaring the types on public functions simply as item(); but this would be at the cost of type safety.
A package that does not itself expose any components may be written using a simplified syntax: the xsl:package element is omitted, and the xsl:stylesheet or xsl:transform element is now the outermost element of the stylesheet module. For compatibility reasons, all the named templates and modes declared in the package are made public. More formally, the principal stylesheet module of the top-level package may be expressed as an xsl:stylesheet or xsl:transform element, which is equivalent to the package represented by the output of the following transformation, preserving the base URI of the source:
<xsl:transform version="3.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:t="http://www.w3.org/1999/XSL/TransformAlias">
<xsl:namespace-alias stylesheet-prefix="t" result-prefix="xsl"/>
<xsl:template match="xsl:stylesheet|xsl:transform">
<t:package declared-modes="no">
<xsl:copy-of select="@*"/>
<t:expose component="mode" names="*" visibility="public"/>
<t:expose component="template" names="*" visibility="public"/>
<xsl:copy-of select="node()"/>
</t:package>
</xsl:template>
</xsl:transform>The effect of the input-type-annotations attribute is defined in 4.2.1 Stripping Type Annotations from a Source Tree.
A more extensive example of a package, illustrating how components in a package can be overridden in a client package, is given in 3.4.8 Worked Example of a Library Package.
If a package has a version number, the version number must conform to the grammar:
PackageVersion ::= NumericPart ( "-" NamePart )?
NumericPart ::= IntegerLiteral ( "." IntegerLiteral )*
NamePart ::= NCNameHere IntegerLiteralXP and NCName are as defined in the XPath 4.0 grammar productions of the same name (including rules on limits). Leading and trailing whitespace is ignored; no other whitespace is allowed.
Examples of valid version numbers are 2.0.5 or 3.10-alpha.
[Definition: [Definition: The integer literals and the optional NamePart within the version number are referred to as the portions of the version number.]
Note:
This means that 1-alpha-2 is a valid version number, with two portions: 1 and alpha-2. The second hyphen is part of the NCName, it does not act as a portion separator.
Versions are ordered. When comparing two versions:
Trailing zero portions (that is, any zero-valued integer that is not followed by another integer) are discarded.
Comparison proceeds by comparing portions pairwise from the left.
If both versions have the same number of portions and all portions compare equal (under the rules of the XPath eq operator using the Unicode codepoint collation), then the versions compare equal.
If the number of portions in the two versions V1 and V2 is N1 and N2, with N1<N2, and if all portions in positions 1 to N compare equal, then V1 is less than V2 if the portion of V2 in position N1 is an integer, and is greater than V2 if this portion is an NCName. For example, 1.2 is less than 1.2.5, while 2.0 is greater than 2.0-rc1.
Portions are compared as follows:
If both portions are integers, they are compared using the rules of XPath value comparisons.
If both portions are NCNames, they are compared using the rules of XPath value comparisons, using the Unicode Codepoint Collation.
If one portion is an integer and the other is an NCName, the NCName comes first.
For example, the following shows a possible ordered sequence of version numbers:
0-rc1 < 0-rc2 < 0 < 1 = 1.0 < 1.0.2 < 1.0.3-rc1 < 1.0.3 < 1.0.3.2 < 1.0.10
Note:
The version number format defined here is designed to be general enough to accommodate a variety of conventions in common use, and to allow useful semantics for matching of versions and ranges of versions, without being over-prescriptive. It is influenced by [SemVer], but is not as prescriptive, and it imposes no assumptions about backwards compatibility of packages between successive versions.
Implementations may impose limits on the values used in a version number (or a version range: see below). Such limits are implementation-defined. As a minimum, a processor must accept version numbers including:
A numeric part containing four integers;
Each integer being in the range 0 to 999999;
An NCName of up to 100 characters
Dependencies between packages may specify a version range (see 3.4.2 Dependencies between Packages). A version range represents a set of accepted versions. The syntax of a version range is shown below. Whitespace is permitted only where indicated, using the terminal symbol S.
PackageVersionRange ::= AnyVersion | VersionRanges
AnyVersion ::= "*"
VersionRanges ::= VersionRange (S? "," S? VersionRange)*
VersionRange ::= PackageVersion | VersionPrefix |
VersionFrom | VersionTo | VersionFromTo
VersionPrefix ::= PackageVersion ".*"
VersionFrom ::= PackageVersion "+"
VersionTo ::= "to" S (PackageVersion | VersionPrefix)
VersionFromTo ::= PackageVersion S
"to" S (PackageVersion | VersionPrefix)The meanings of the various forms of version range are defined below:
The range AnyVersion matches any version.
The range VersionRanges matches a version if any constituent VersionRange matches that version.
For example, 9.5.0.8, 9.6.1.2 matches those specific versions only, while 9.5.0.8, 9.6+ matches either version 9.5.0.8 or any version from 9.6 onwards.
A range that is a PackageVersion matches that version only.
The range VersionPrefix matches any version whose leading portions are the same as the portions in the PackageVersion part of the VersionPrefix.
For example, 1.3.* matches 1.3, 1.3.5, 1.3.10.2, and 1.3-beta (but not 1 or 1.4).
Note:
The .* indicates that additional portions may follow; it does not indicate a substring match on the final portion. So 1.3.* does not match 1.35, and 3.3-beta.* does not match 3.3-beta12. Also, 3.3-beta.* does not match 3.3-beta.5: this is because the last dot is not a portion separator, but is part of the final NCName. In fact, using .* after a version number that includes an NCName portion is pointless, because an NCName portion can never be followed by further portions.
The range VersionFrom matches any version that is greater than or equal to the version supplied.
For example 1.3+ matches 1.3, 1.3.2, 1.4, and 2.1 (but not 1.3-beta or 1.2). And 1.3-beta+ matches 1.3-beta, 1.3-gamma, 1.3.0, 1.4, and 8.0, but not 1.3-alpha or 1.2.
The range VersionTo matches any version that is less than or equal to some version that matches the supplied PackageVersion or VersionPrefix.
For example, to 4.0 matches 1.5, 2.3, 3.8, 4.0, and 4.0-beta (but not 4.0.1), while to 3.3.* matches 1.5 or 2.0.6 or 3.3.4621, but not 3.4.0 or 3.4.0-beta.
The range VersionFromTo matches any version that is greater than or equal to the starting PackageVersion, and less than or equal to some version that matches the ending PackageVersion or VersionPrefix.
For example, 1 to 5 matches 1.1, 2.1, 3.1, or 5.0 (but not 5.1), while 1 to 5.* matches all of these, plus versions such as 5.7.2 (but not 6.0 or 6.0-beta). Similarly, 1.0-beta to 1.0 matches 1.0-beta, 1.0-beta.2, 1.0-gamma, and 1.0, but not 1.0-alpha or 1.0.1.
When components in one package reference components in another, the dependency of the first package on the second must be represented by an xsl:use-package element. This may appear in the principal stylesheet module of the first package (which may be a package manifest), or it may appear in a stylesheet module that is referenced from the principal stylesheet module via one or more xsl:include declarations; however it must not be referenced via xsl:import declarations (this is to avoid complications caused by multiple xsl:use-package declarations with different import precedence).
[Definition: [Definition: 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.]
The phrase directly uses is synonymous with uses as defined above, while directly or indirectly uses refers to the transitive closure of this relationship.
<!-- Category: declaration -->
<xsl:use-package
name = uri
package-version? = string〔'*'〕 >
<!-- Content: (xsl:package-location | xsl:accept | xsl:override)* -->
</xsl:use-package>
A package may be used by more than one other package, but the relationship must not be cyclic. It is possible, but by no means inevitable, that using the same package in more than one place within a stylesheet will cause static errors due to the presence of conflicting components according to the above rules. Where a package is successfully used by more than one other package, its components may be overridden in different ways by different using packages.
The name and package-version attributes together identify the used package. The value of the package-version attribute, if present, must conform to the rules for a PackageVersionRange given in 3.4.1 Versions of a Package; if omitted the value * is assumed, which matches any version. The used package must have a name that is an exact match for the name in the name attribute (using codepoint comparison), and its explicit or implicit package-version must match the version range given in the package-version attribute.
Rules for determining the location of the package are described at 3.4.3 Locating Packages.
[ERR XTSE3005] It is a static error if a package is dependent on itself, where package A is defined as being dependent on package B if A contains an xsl:use-package declaration that references B, or if A contains an xsl:use-package declaration that references a package C that is itself dependent on B.
[ERR XTSE3008] It is a static error if an xsl:use-package declaration appears in a stylesheet module that is not in the same stylesheet level as the principal stylesheet module of the package.
The xsl:accept and xsl:override elements are used to modify the visibility or behavior of components acquired from the used package; they are described in 3.4.4.2 Accepting Components below.
Note:
It is not intrinsically an error to have two xsl:use-package declarations that identify the same package (or different versions of the same package). This has the same effect as having two declarations that identify packages with different names but identical content. In most cases it will result in an error ([see ERR XTSE3050]) due to the presence of multiple components with the same name; but no error would occur, for example, if the used package is empty, or if the two xsl:use-package declarations use xsl:accept to accept non-overlapping subsets of the components in the used package.
A package may be located either explicitly, through one or more xsl:use-package elements, or implicitly, in an implementation-defined mechanism. Providing multiple package locations allows a developer to create fallback mechanisms or perform diagnostics.
<xsl:package-location
href = uri
path-in-archive? = string
archive-type? = string
is-priority? = boolean〔true()〕
format? = string />
A xsl:package-location points to a resource that may or may not be an archive. If the target resource is an archive, then xsl:package-location:
must have an attribute path-in-archive, specifying the location of the package manifest within the archive. The value of path-in-archive is normalized such that it always begins with the string !/ (the result of replace(., "^(!/)?(.+)", "!/$2")).
may have an attribute archive-type, specifying the type of archive. Implementations must support the ZIP file format, as defined by [ISO 21320], the default archive format if the attribute is missing or the explicit format if the attribute has the value zip. All other values of this attribute are implementation-defined.
It is a static error if the attribute archive-type is present without the attribute path-in-archive, or if it does not have the value zip or an implementation-defined value.
The attribute href takes an absolute or relative URI reference, which is resolved as described in 5.8 URI References, to locate the resource that is the package manifest or is the archive that contains the package manifest.
The URI scheme for archive resources is currently only provisionally defined ([RFC 7595]), with the syntax jar:<url>!/[<entry>], but variations on this syntax are known (such as using zip instead of jar). The entry is already accommodated by the attribute archive-type, so the following adjustments must be made to the value of href that points to an archive:
Remove "zip:" or "jar:" from the beginning of the value.
Remove !/ and any string text that follows.
The attribute format takes a string, default value xslt if the attribute is absent, specifying the format of the package manifest. The value xslt indicates that the package manifest is a standard XML resource as described in these specifications. All other values are implementation-defined, allowing implementers to support optimized formats for a package manifest, be it a compiled binary resource or a different XML format.
[Definition: [Definition: A xsl:package-location without the attribute is-priority, or with is-priority set to true is a high priority package location.][Definition: [Definition: A xsl:package-location with is-priority set to false is a low priority package location.]
Each high priority package location is processed in document order, followed by implementation-defined package locations, followed by each low priority package location in document order. [Definition: [Definition: 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.] Once an optimal package location is found, no other package locations are checked.
If the returned resource is an archive, the archive entry is to be treated as the package manifest, otherwise the resource itself is to be treated as the package manifest. The package manifest returned from the optimal package location is checked against the implicit or explicit value of the attribute format. If the resource does not conform to the rules for the format type a static error is raised.
The package manifest is then checked against the the package name and version specified in the xsl:use-package declaration. If the resource does not conform to the rules for the name and version, a static error is raised.
[ERR XTSE3000] It is a static error if after evaluating each xsl:package-location declaration and implementation-defined package location, no priority package location is found.
[ERR XTSE3002] It is a static error if the package manifest returned by the priority package location does not conform to the rules of the implicit or explicit value of attribute format.
[ERR XTSE3003] It is a static error if the package manifest returned by the priority package location does not conform to the name and version specified in an xsl:use-package declaration.
[ERR XTSE3004] It is a static error if the attribute archive-type is present without the attribute path-in-archive, or if it does not have the value zip or an implementation-defined value.
Note:
Use of the package name as a dereferenceable URI is not recommended, because the intent of the packaging feature is to allow a package to be distributed as reusable code and therefore to exist in many different locations.
Note:
Depending on the implementation architecture, there may be a need to locate used packages both during static analysis (for example, to get information about the names and type signatures of the components exposed by the used package), and also at evaluation time (to link to the implementation of these components so they can be invoked). A failure to locate a package may cause an error at either stage.
Consider a using package Q, invoked as follows:
<xsl:use-package name="Q" version="3.0" xmlns:saxon="http://saxon.sf.net/"/>
<package-location href="q-dev.xsl" use-when="$diagnostics-on"/>
<package-location _href="file:/{$prod-path}/q.zip" path-in-archive="q.sef"
is-priority="true" format="saxon:sef"/>
<package-location href="file:/D:/fallback/q.xsl" format="xslt" is-priority="false"/>
</xsl:package>The first xsl:package-location will be the first to be evaluated only if the static parameter $diagnostics-on is true, in which case the local file q-dev.xsl, if it exists, will be the priority package location. The next xsl:package-location to be checked points to the archive resource located by the path file:/{$prod-path}/q.zip (which depends upon the value of static parameter $prod-path), and the entry q.sef at the root of the archive (assumed to be a ZIP file for lack of a archive-type). Next will be any implementation-defined package locations. Last will be the last xsl:package-location, a low priority package location, which serves as a local fallback.
Each of these package locations will be evaluated in turn. If no priority package location is found, an error is raised. Only the first resource to qualify as the priority package location will be checked, to ensure it conforms to the file format and the package name and version.
This section discusses the use of named components in packages.
The components which can be declared in one package and referenced in another are: functions, named templates, attribute sets, modes, and global variables and parameters.
In addition, keys and accumulators are classified as named components because they can contain references to components in another package, even though they cannot themselves be referenced from outside the package.
Named and unnamed modes come within the scope of this section, but there are differences noted in 3.4.5 Overriding Template Rules from a Used Package.
Not all declarations result in components:
Named declarations that can neither be referenced from outside their containing package, nor can contain references to components in other packages (examples are xsl:output, xsl:character-map, and xsl:decimal-format) are not considered to be components and are therefore outside the scope of this section.
Some declarations, such as xsl:decimal-format and xsl:strip-space, declare aspects of the processing context which are not considered to be components as defined here.
Template rules (xsl:template with a match attribute) are also not considered to be components for the purposes of this section, which is concerned only with components that are bound by name. However, when an xsl:template has both a match attribute and a name attribute, then it establishes both a template rule and a named template, and in its role as a named template it comes within the scope of this discussion.
A named declaration, for example a named template, a function, or a global variable, may be overridden within the same package by another like-named declaration having higher import precedence. When a declaration is overridden in this way it cannot be referenced by name either from within its containing package or from outside that package.
In the case of xsl:attribute-set and xsl:key declarations, several declarations combine to form a single component.
The section is largely concerned with details of the rules that affect references from one component to another by name, whether the components are in the same package or in different packages. The rules are designed to meet a number of requirements:
A component defined in one package can be overridden by a component in another package, provided the signatures are type-compatible.
The author of a package can declare whether the components in the package are public or private (that is, whether or not they can be used from outside the package) and whether they are final, overridable, or abstract (that is whether they can or must be overridden by the using package).
Within an application, two packages can make use of a common library and override its components in different ways.
Visibility of components can be defined either as part of the declaration of the component, or in the package manifest.
An application that wishes to make use of a library package can be selective about which components from the library it acquires, perhaps to avoid name clashes between components acquired from different libraries.
[Definition: [Definition: The term component is used to refer to any of the following: a stylesheet function, a named template, a mode, an accumulator, an attribute set, a key, global variable, or a mode.]
[Definition: [Definition: The symbolic identifier of a component is a composite name used to identify the component uniquely within a package. The symbolic identifier comprises the kind of component (stylesheet function, named template, accumulator, attribute set, global variable, key, or mode), the expanded QName of the component (namespace URI plus local name), and in the case of stylesheet functions, the upper bound of the arity range.]
Note:
In the case of the unnamed mode, the expanded QName of the component may be considered to be some system-allocated name different from any user-defined mode name.
[Definition: [Definition: Two components are said to be homonymous if they have the same symbolic identifier.]
Every component has a declaration in some stylesheet module and therefore within some package. In the case of attribute sets and keys, there may be several declarations. The declaration is an element in an XDM tree representing the stylesheet module. Declarations therefore have identity, based on XDM node identity.
[Definition: [Definition: The declaring package of a component is the package that contains the declaration (or, in the case of xsl:attribute-set and xsl:key, multiple declarations) of the component.]
When a component declared in one package is made available in another, the using package will contain a separate component that can be regarded as a modified copy of the original. The new component shares the same symbolic identifier as the original, and it has the same declaration, but it has other properties such as its visibility that may differ from the original.
[Definition: [Definition: A component declaration results in multiple components, one in the package in which the declaration appears, and potentially one in each package that uses the declaring package, directly or indirectly, subject to the visibility of the component. Each of these multiple components has the same declaring package, but each has a different containing package. For the original component, the declaring package and the containing package are the same; for a copy of a component made as a result of an xsl:use-package declaration, the declaring package will be the original package, and the containing package will be the package in which the xsl:use-package declaration appears.]
Note:
Within this specification, we generally use the notation CP for a component named C whose declaring package and containing package are both P; and the notation CPQ for a component whose containing package is P and whose declaring package is Q (that is, a component in P that is derived from a component CQ in the used package Q).
The properties of a component are as follows:
The original declaration of the component.
The package to which the component belongs (called its containing package, not to be confused with the declaring package).
The symbolic identifier of the component.
The visibility of the component, which determines the way in which the component is seen by other components within the same package and within using packages. This is one of public, private, abstract, final, or hidden. The visibility of components is discussed further in 3.4.4.1 Visibility of Components.
A set of bindings for the symbolic references in the component. The way in which these bindings are established is discussed further in 3.4.4.5 Binding References to Components.
Note:
When a function F defined in a package P is acquired by two using packages Q and R, we may think of P, Q, and R as all providing access to the “same” function. The detailed semantics, however, demand an understanding that there is one function declaration, but three components. The three components representing the function F within packages P, Q, and R have some properties in common (the same symbolic identifier, the same declaration), but other properties (the visibility and the bindings of symbolic references) that may vary from one of these components to another.
[Definition: [Definition: The declaration of a component includes constructs that can be interpreted as references to other components by means of their symbolic identifiers. These constructs are generically referred to as symbolic references. Examples of constructs that give rise to symbolic references are the name attribute of xsl:call-template; the [xsl:]use-attribute-sets attribute of xsl:copy, xsl:element, and literal result elements; the explicit or implicit mode attribute of xsl:apply-templates; XPath variable references referring to global variables; XPath static function calls (including partial function applications) referring to stylesheet functions; and named function references (example: my:f#1) referring to stylesheet functions. ]
Symbolic references exist as properties of the declaration of a component. The symbolic identifier being referred to can be determined straightforwardly from the syntactic form and context of the reference: for example, the instruction <xsl:value-of select="f:price($o)" xmlns:f="http://f.com/"/> contains a symbolic reference to a function with expanded name {http://f.com/}price and with arity=1. However, because there may be several (homonymous) function components with this symbolic identifier, translating this symbolic reference into a reference to a specific component (a process called “binding”) is less straightforward, and is described in the text that follows.
The process of assembling a stylesheet from its constituent packages is primarily a process of binding these symbolic references to actual components. Within any component whose declaration is D, there is a set of bindings; each binding is an association between a symbolic reference in D and a component whose symbolic identifier matches the outward reference. Outward references for which a component C contains a binding are said to be bound in C; those for which C contains no binding are said to be unbound.
For example, suppose that in some package Q, function A calls B, which in turn calls C, and that B is private. Now suppose that in some package P which uses Q, C is overridden. The effect of the binding process is that P will contain three components corresponding to A, B, and C, which we might call AP, BP, and CP. The declarations of AP and BP are in package Q, but the declaration of CP is in P. The internal visibility of BP will be hidden (meaning that it cannot be referenced from within P), and BP will contain a binding for the component CP that corresponds to the outward reference from B to C. The effect is that when A calls B and B calls C, it is the overriding version of C that is executed.
In another package R that uses Q without overriding C, there will be three different components AR, BR, and CR. This time the declaration of all three components is in the original package Q. Component BR will contain a binding to CR, so in this package, the original version of C is executed. The fact that one package P overrides C thus has no effect on R, which does not override it.
The binding process outlined above is described in more detail in 3.4.4.5 Binding References to Components.
Template rules are not components in their own right; unlike named templates, they are never referenced by name. Component references within a template rule (for example, references to functions, global variables, or named templates) are treated as occurring within the component that represents the containing mode. This includes component references within the match patterns of template rules. If a template rule lists several modes, it is treated as if there were multiple template rules one in each mode.
An xsl:apply-templates instruction with no mode attribute is treated as a reference to the default mode defined for that instruction (see 3.6.3 The default-mode Attribute), which in turn defaults to the unnamed mode. An implicit reference to the unnamed made is treated in the same way as any other symbolic reference. Note that there is an unnamed mode in every package, and the unnamed mode always has private visibility.
Where an xsl:template element has both a name and a match attribute, it is treated as if there were two separate xsl:template elements, one with a name attribute and one with a match attribute.
Keys and accumulators behave rather differently from other components. Their visibility is always private, which means they can only be used within their declaring package. In addition, the component binding is generally made dynamically rather than statically, by virtue of a string passed as an argument to the function key, accumulator-before, or accumulator-after. (In the case of accumulators, there can also be static references: see the use-accumulators attribute of xsl:source-document, xsl:merge-source, and xsl:mode.) However, outward references from key definitions and accumulators to other components (such as global variables and functions) behave in the same way as component references contained in any other private component, in that they may be re-bound to an overriding declaration of the target component.
[Definition: [Definition: The visibility of a component is one of: private, public, abstract, final, or hidden.]
The meanings of these visibility values is as follows:
The component can be referenced from other components in this package or in any using package; it can be overridden by a different component in any using package.
The component can be referenced from other components in this package; it cannot be referenced or overridden within a using package.
The component can be referenced from other components in this package or in any using package; in a using package it can either remain abstract or be overridden by a different component.
The component can be referenced from other components in this package or in any using package; it cannot be overridden by a different component in any using package.
The component cannot be referenced from other components in this package; it cannot be referenced or overridden within a using package.
Note:
The visibility of a component in a package P primarily affects how the component can be used in other packages, specifically, packages that use P. There is one exception: if the visibility is hidden, it also affects how the component can be used within P.
When a component is declared within a particular package, its visibility, which affects how it can be used in other (using) packages, depends on two factors: the value of the visibility declaration on the declaration itself (if present), and the rules given in the xsl:expose declarations of the package manifest.
The xsl:function, xsl:template, xsl:attribute-set, xsl:variable, xsl:mode, xsl:item-type, and xsl:record-typedeclarations each have an optional visibility attribute. The permitted value is some subset of private, public, abstract, or final (never hidden). In the case of an xsl:param element there is no explicit visibility attribute; rather the declaration has the implicit attribute visibility="public".
Any xsl:expose declarations that appear as children of xsl:package define the visibility of components whose declaration has no explicit visibility attribute, and can also be used to reduce the visibility of components where this attribute is present.
<xsl:expose
component = "template" | "function" | "attribute-set" | "variable" | "mode" | "item-type" | "record-type" | "*"
names = tokens
visibility = "public" | "private" | "final" | "abstract" />
The xsl:expose element allows the visibility of selected components within a package to be defined.
The components in question are identified using their symbolic identifiers. The component attribute defines the kind of component that is selected. The value * means “all component kinds”; in this case the value of the names attribute must be a WildcardXP.
An xsl:expose declaration has no effect on the unnamed mode, which is always private to a package.
The names attribute selects a subset of these components by name (and in the case of functions, arity); its value is a whitespace-separated sequence of tokens each of which is either a NameTestXP or a NamedFunctionRefXP. (Examples are *, p:*, *:local, p:local, and p:local#2.)
The value may be a NamedFunctionRef only in the case of stylesheet functions, and distinguishes functions with the same name and different arity. A NameTestXP on its own (that is, with no arity) cannot be used to identify a function.
The visibility of a named template, function, variable, attribute set, mode, named item type, or named record type declared within a package is the first of the following that applies, subject to consistency constraints which are defined below:
The visibility of a variable declared using an xsl:param element is always public. No xsl:expose element ever matches an xsl:param component.
Note:
Attempting to match an xsl:param with an explicit EQName will therefore always give an error, while using a wildcard has no effect.
If the package manifest contains an xsl:expose element that matches this component by virtue of an explicit EQName or NamedFunctionRef (that is, not by virtue of a wildcard match), then the value of the visibility attribute of the last such xsl:expose element in document order (call this the explicit exposed visibility).
If the declaration of the component has a visibility attribute, then the value of this attribute (call this the declared visibility).
If the package manifest contains an xsl:expose element that matches this component by virtue of a wildcard match that specifies either the namespace part of the component name or the local part of the name (for example, prefix:* or *:local or Q{uri}*), then the value of the visibility attribute of the last such xsl:expose element in document order.
If the package manifest contains an xsl:expose element that matches this component by virtue of a wildcard match that matches all names (that is, *), then the value of the visibility attribute of the last such xsl:expose element in document order.
Otherwise, private.
Note:
In the above rules, no distinction is made between declarations that specify a specific component kind, and those that specify component="*". If both match, the value of the component attribute plays no role in deciding which declaration wins.
If both a declared visibility and an explicit exposed visibility exist for the same component, then as mentioned above, they must be consistent. This is determined by reference to the following table, where the entry N/P means “not permitted”. (In cases where the combination is permitted, the actual visibility is always the same as the visibility determined by xsl:expose.)
| Explicit exposed visibility | Declared visibility | |||
|---|---|---|---|---|
| public | private | final | abstract | |
| public | public | N/P | N/P | N/P |
| private | private | private | private | N/P |
| final | final | N/P | final | N/P |
| abstract | N/P | N/P | N/P | abstract |
[ERR XTSE3010] It is a static error if the explicit exposed visibility of a component is inconsistent with its declared visibility, as defined in the above table. (This error occurs only when the component declaration has an explicit visibility attribute, and the component is also listed explicitly by name in an xsl:expose declaration.)
[ERR XTSE3020] It is a static error if a token in the names attribute of xsl:expose, other than a wildcard, matches no component in the containing package.
[ERR XTSE3022] It is a static error if the component attribute of xsl:expose specifies * (meaning all component kinds) and the names attribute is not a wildcard.
Note:
There is no ambiguity, and no error, if several tokens within the same xsl:expose element match the same component.
If the visibility of a component as established by the above rules is abstract, then the component must have a declared visibility of abstract.
Note:
In other words, the xsl:expose declaration cannot be used to make a component abstract unless it was declared as abstract to start with.
[ERR XTSE3025] It is a static error if the effect of an xsl:expose declaration would be to make a component abstract, unless the component is already abstract in the absence of the xsl:expose declaration.
For a component accepted into a package P from another package Q, the visibility of the component in P (which primarily affects how it can be used in a package R that uses P) depends on the visibility declared in the relevant xsl:accept or xsl:override element in P (see 3.4.4.2 Accepting Components); this in turn has a default that depends on the visibility of the corresponding component in Q. In this case the visibility is unaffected by any xsl:expose declaration in P.
[Definition: [Definition: A component in a using package may override a component in a used package, provided that the visibility of the component in the used package is either abstract or public. The overriding declaration is written as a child of the xsl:override element, which in turn appears as a child of xsl:use-package.]
<xsl:override>
<!-- Content: (xsl:template | xsl:function | xsl:variable | xsl:param | xsl:attribute-set)* -->
</xsl:override>
Note:
This mechanism is distinct from the mechanism for overriding declarations within the same package by relying on import precedence. It imposes stricter rules: the overriding component is required to be type-compatible with the component that it overrides.
If the used package Q contains a componentCQ and the xsl:use-package element contains an xsl:override element which contains a declaration D whose symbolic identifier matches the symbolic identifier of CQ, then the using package P will contain a component CP whose declaration is D, whose symbolic identifier is that of D, and whose visibility is equal to the value of the visibility attribute of D, or private if this is absent, except in the case of xsl:param, which is implicitly public.
The using package P will also contain a component CPQ whose body is the same as the body of CQ and whose visibility is hidden. This component is used as the target of a binding for the symbolic reference xsl:original described below.
Other than its appearance as a child of xsl:override, the overriding declaration is a normal xsl:function, xsl:template, xsl:variable, xsl:param, or xsl:attribute-set element. In the case of xsl:variable and xsl:param, the variable that is declared is a global variable.
The rules in the remainder of this section apply to components having a name attribute (named components). The only element with no name attribute that can appear as a child of xsl:override is an xsl:template declaration having a match attribute (that is, a template rule). The rules for overriding of template rules appear in 3.4.5 Overriding Template Rules from a Used Package. If an xsl:template element has both a name attribute and a match attribute, then it defines both a named component and a template rule, and both sections apply.
[ERR XTSE3055] It is a static error if a component declaration appearing as a child of xsl:override is homonymous with any other declaration in the using package, regardless of import precedence, including any other overriding declaration in the package manifest of the using package.
Note:
When an attribute set is overridden, the overriding attribute set must be defined using a single xsl:attribute-set element. Attribute sets defined in different packages are never merged by virtue of having the same name, though they may be merged explicitly by using the use-attribute-sets attribute.
[ERR XTSE3058] It is a static error if a component declaration appearing as a child of xsl:override does not match (is not homonymous with) some component in the used package.
[ERR XTSE3060] It is a static error if the component referenced by an xsl:override declaration has visibility other than public or abstract
A package is executable if and only if it contains no component whose visibility is abstract. A package that is not executable is not a stylesheet, and therefore cannot be nominated as the stylesheet to be used when initiating a transformation.
Note:
In other words, if a component is declared as abstract, then some package that uses the declaring package of that component directly or indirectly must override that component with one that is not abstract. It is not necessary for the override to happen in the immediately using package.
[ERR XTSE3070] It is a static error if the signature of an overriding component is not compatible with the signature of the component that it is overriding.
[Definition: [Definition: The signatures of two components are compatible if they present the same interface to the user of the component. The additional rules depend on the kind of component.]
Compatibility is only relevant when comparing two components that have the same symbolic identifier. The compatibility rules for each kind of component are as follows:
Two attribute sets with the same name are compatible if and only if they satisfy the following rule:
If the overridden attribute set specifies streamable="yes" then the overriding attribute set also specifies streamable="yes".
Two functions with the same symbolic identifier are compatible if and only if they satisfy all the following rules:
They have the same arity range (which implies they have the same number of required and optional parameters)
The declared types of the parameters (defaulting to item()*) are pairwise identical.
The declared return types (defaulting to item()*) are identical.
The effective value of the new-each-time attribute on the overriding function is the same as its value on the overridden function.
If the overridden function has a streamability attribute with a value other than unspecified, then the overriding function has a streamability attribute with the same value.
It is recommended that the parameter names on the overriding function should be the same as on the overridden function. (However, in order to maintain backwards compatibility with XSLT 3.0, this is not required.) If the parameter names are not the same, then the parameter names on the overriding function are effectively replaced with the names declared on the overridden function, so that any static function calls using keyword arguments to set the values of arguments must use the names defined on the overridden function.
Two named templates with the same name are compatible if and only if they satisfy all the following rules:
Their return types are identical.
For every non-tunnel parameter on the overridden template, there is a non-tunnel parameter on the overriding template that has the same name, an identical required type, and the same effective value for the required attributes.
For every tunnel parameter P on the overridden template, if there is a parameter Q on the overriding template that has the same name as P then Q is also a tunnel parameter, and P and Q have identical required types.
Any parameter on the overriding template for which there is no corresponding parameter on the overridden template specifies required="no".
The two templates have equivalent xsl:context-item children, where equivalence means that the use attributes are the same and the required types are identical; an absent xsl:context-item is equivalent to one that specifies use="optional" and as="item()".
Two variables (including parameters) with the same name are compatible if and only if they satisfy all the following rules:
Their declared types are identical. For this purpose, the declared type is the first of the following that applies:
If there is an as attribute, then the type defined by that attribute.
If there is a select attribute, then item()*.
If there is a non-empty sequence constructor, then document-node().
Otherwise, xs:string.
Note:
A variable may override a parameter or vice-versa, and the initial value may differ.
Because static variables and parameters are constrained to have visibility private , they cannot be overridden in another package. The compatibility rules therefore do not arise. The reason that such variables cannot be overridden is that they are typically used during stylesheet compilation (for example, in [xsl:]use-when expressions and shadow attributes) and it is a design goal that packages should be capable of independent compilation.
[Definition: [Definition: Types S and T are considered identical for the purpose of these rules if and only if subtype(S, T) and subtype(T, S) both hold, where the subtype relation is defined in [XPath 4.0] section 3.3.1 Subtypes of Sequence Types.]
Note:
One consequence of this rule is that two plain union types are considered identical if they have the same set of member types, even if the union types have different names or the ordering of the member types is different.
Consider a function that accepts an argument whose declared type is a union type with member types xs:double and xs:decimal, in that order (we might write this as (xs:double | xs:decimal)). Using the same notation, this can be overridden by a function that declares the argument type as (xs:decimal | xs:double). This does not affect type checking: a function call that passes the type checking rules with one signature will also pass the type checking rules with the other. It does however affect the way that the function conversion rules work: a call that passes the xs:untypedAtomic item "93.7" (or an untyped node with this as its string value) will be converted to an xs:decimal in one case and an xs:double in the other.
While this rule may appear formal, it is not as straightforward as might be supposed, because the subtype relation in XPath has a dependency on the “Type derivation OK (Simple)” relation in XML Schema, which itself appeals to a judgement as to whether the two type definitions being compared “are the same type definition”. Both XSD 1.0 and XSD 1.1 add the note “The wording of [this rule] appeals to a notion of component identity which is only incompletely defined by this version of this specification.” However, they go on to say that component identity is well defined if the components are named simple type definitions, which will always apply in this case. For named atomic types, the final result of these rules is that two atomic types are identical if and only if they have the same name.
A named item type (declared in an xsl:item-type declaration) is considered identical to its expansion.
Two named record types are compared by name, not by content. This is because named record types may potentially be recursive, so the name cannot always be expanded to an expressible record type designator. By implication, the named record type must itself be declared or exposed with visibility="public".
Modes, named item types, and named record type are not overridable, so xsl:mode, xsl:item-type, and xsl:record-type declarations cannot appear as children of xsl:override. However, the constructor function implicitly created from an xsl:record-type declaration may be overridden in an xsl:function declaration.
[Definition: [Definition: The process of identifying the component to which a symbolic reference applies (possibly chosen from several homonymous alternatives) is called reference binding.]
The process of reference binding in the presence of overriding declarations is best illustrated by an example. The formal rules follow later in the section.
Consider a package Q defined as follows:
<xsl:package name="Q"
version="3.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:variable name="A" visibility="final" select="$B + 1"/>
<xsl:variable name="B" visibility="private" select="$C * 2"/>
<xsl:variable name="C" visibility="public" select="22"/>
</xsl:package>(The process is illustrated here using variables as the components, but the logic would be the same if the example used functions, named templates, or attribute sets.)
There are three components in this package, and their properties are illustrated in the following table. (The ID column is an arbitrary component identifier used only for the purposes of this exposition.)
| ID | Symbolic Name | Declaring Package | Containing Package | Visibility | Body | Bindings |
|---|---|---|---|---|---|---|
| AQ | variable A | Q | Q | final | $B + 1 | $B → BQ |
| BQ | variable B | Q | Q | private | $C * 2 | $C → CQ |
| CQ | variable C | Q | Q | public | 22 | none |
Now consider a package P that uses Q, and that overrides one of the variables declared in Q:
<xsl:package name="P"
version="3.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:use-package name="Q">
<xsl:override>
<xsl:variable name="C" visibility="private" select="$xsl:original + 3"/>
</xsl:override>
</xsl:use-package>
<xsl:template name="T" visibility="public">
<xsl:value-of select="$A"/>
</xsl:template>
</xsl:package>Package P has five components, whose properties are shown in the following table:
| ID | Symbolic Name | Declaring Package | Containing Package | Visibility | Body | Bindings |
|---|---|---|---|---|---|---|
| APQ | variable A | Q | P | final | $B + 1 | $B → BPQ |
| BPQ | variable B | Q | P | hidden | $C * 2 | $C → CP |
| CPQ | variable C | Q | P | hidden | 22 | none |
| CP | variable C | P | P | private | $xsl:original + 3 | $xsl:original → CPQ |
| TP | template T | P | P | public | value-of select="$A | $A → APQ |
The effect of these bindings is that when template T is called, the result is 51. This is why:
The result of T is the value of APQ.
The value of APQ is the value of BPQ plus 1.
The value of BPQ is the value of CP times 2.
The value of CP is the value of CPQ plus 3.
The value of CPQ is 22.
So the final result is ((22 + 3) * 2) + 1
In this example, the components of P are established in three different ways:
Components APQ, BPQ, and CPQ are modified copies of the corresponding component AQ, BQ, and CQ in the used package Q. The properties of these components are modified as follows:
The symbolic identifier, declaring package, and body are unchanged.
The containing package is changed to P.
The visibility is changed according to the rules in 3.4.4.2 Accepting Components: in particular, visibility="private" changes to visibility="hidden".
The references to other components are rebound as described in this section.
Component CP is the overriding component. Its properties are exactly as if it were declared as a top-level component in P (outside the xsl:use-package element), except that (a) it must adhere to the constraints on overriding components (see 3.4.4.3 Overriding Components from a Used Package), (b) it is allowed to use the variable reference $xsl:original, and (c) the fact that it overrides CQ affects the way that references from other components are rebound.
Component TP is a new component declared locally in P.
The general rules for reference binding can now be stated:
If the containing package of a component CP is P, then all symbolic references in CP are bound to components whose containing package is P.
When a package P uses a package Q, then for every component CQ in Q, there is a corresponding componentCP in P, as described in 3.4.4.2 Accepting Components.
Given a component CP whose containing package and declaring package are the same package P, then (as a consequence of rules elsewhere in this specification) for every symbolic referenceD within CP, other than a reference using the name xsl:original, there will always be exactly one non-hidden component DP whose containing package is P and whose symbolic identifier matches D (otherwise a static error will have been raised). The reference is then bound to DP.
In the case of a component reference using the name xsl:original, this will in general appear within a component CP that overrides a component CQ whose corresponding component in P is CPQ, and the xsl:original reference is bound to CPQ.
Given a component CP whose containing packageP is a different package from its declaring packageR (that is, CP is present in P by virtue of an xsl:use-package declaration referencing package Q, which may or may not be the same as R), then the component bindings in CP are derived from the component bindings in the corresponding component CQ as follows: if the component binding within CQ is to a component DQ, then:
If DQ is overridden within P by a component DP, then the reference is bound to DP;
Otherwise, the reference is bound to the component DPQ in P whose corresponding component in Q is DQ.
When reference resolution is performed on a package that is intended to be used as a stylesheet (that is, for the top-level package), there must be no symbolic references referring to components whose visibility is abstract (that is, an implementation must be provided for every abstract component).
[ERR XTSE3080] It is a static error if a top-level package (as distinct from a library package) contains components whose visibility is abstract.
Note:
Abstract components in a used package by default become hidden in the using package, which means that a reference to the component in the top-level package will fail to resolve (resulting in a different static error). This particular error occurs only if the abstract component is declared within the top-level package.
Note:
Unresolved references are allowed at the module level but not at the package level. A stylesheet module can contain references to components that are satisfied only when the module is imported into another module that declares the missing component.
Note:
The process of resolving references (or linking) is critical to an implementation that uses separate compilation. One of the aims of these rules is to ensure that when compiling a package, it is always possible to determine the signature of called functions, templates, and other components. A further aim is to establish unambiguously in what circumstances components can be overridden, so that compilers know when it is possible to perform optimizations such as inlining of function and variable references.
Suppose a public template T calls a private function F. When the package containing these two components is referenced by a using package, the template remains public, while the function becomes hidden. Because the function becomes hidden, it can no longer conflict with any other function of the same name, or be overridden by any other function; at this stage the compiler knows exactly which function T will be calling, and can perform optimizations based on this knowledge.
The mechanism for resolving component references described in this section is consistent with the mechanism used for binding function and variable references described in the XPath specification. XPath requires these variable and function names to be present in the static context for an XPath expression. XSLT ensures that all the non-hidden functions, global variables, and global parameters in a package are present in the static context for every XPath expression that appears in that package, along with required information such as the type of a variable and the signature of a function.
Named component references within inline functions follow the standard rules, but the rules need to be interpreted with care. Suppose that in package P we find the declarations:
<xsl:variable name="v" as="xs:integer" visibility="public" select="3"/>
<xsl:function name="f:factory" as="fn(*)" visibility="final">
<xsl:sequence select="fn() { $v }"/>
</xsl:function>and that in a using package Q we find:
<xsl:use-package name="P">
<xsl:override>
<xsl:variable name="v" as="xs:integer" select="4"/>
</xsl:override>
</xsl:use-package>
<xsl:template name="xsl:initial-template">
<v value="{f:factory()()}"/>
</xsl:template>The correct output here is <v value="4"/>.
The explanation for this is as follows. Package Q contains a function f:factoryQP whose declaring package is P and whose containing package is Q. The symbolic reference $v within the body of this function is resolved in the normal way; since the containing package is Q, it is resolved to the global variable vQ: that is, the overriding declaration of $v that appears within the xsl:override element within package Q, whose value is 4.
In terms of internal implementation, one way of looking at this is that the anonymous function returned by f:factory contains within its closure bindings for the global variables and functions that the anonymous function references; these bindings are inherited from the component bindings of the component that lexically contains these symbolic references, which in this case is f:factory, and more specifically the version of the f:factory component in package Q.
[Definition: [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 package manifest, as described in 3.4 Packages, which is a subtree rooted at an xsl:package element
An implicit package, which is a subtree rooted at an xsl:stylesheet or xsl:transform element. This is transformed automatically to a package as described in 3.4 Packages.
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 an implicit package by wrapping it in an xsl:stylesheet element using the transformation described in 3.7 Simplified Stylesheet Modules, and then to an explicit package (rooted at an xsl:package element) using the transformation described in 3.4 Packages.
A stylesheet module other than the principal stylesheet module of a package may take either of two forms:
[Definition: [Definition: A standard stylesheet module, which is a subtree rooted at an xsl:stylesheet or xsl:transform element.]
[Definition: [Definition: 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.]
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: [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.]
Changes in 4.0 (next | previous)
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.11.1 Stripping Whitespace and Commentary from the Stylesheet.)
[Definition: [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: [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:accumulatorxsl:attribute-setxsl:character-mapxsl:decimal-formatxsl:functionxsl:global-context-itemxsl:importxsl:import-schemaxsl:includexsl:item-typexsl:keyxsl:modexsl:namespace-aliasxsl:outputxsl:paramxsl:preserve-spacexsl:record-typexsl:strip-spacexsl:templatexsl:use-packagexsl: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:
As described in 6.6 Conflict Resolution for Template Rules, when two template rules with the same priority match the same nodes, there are situations where the order of the template rules will affect which is chosen.
Forwards references to static variables are not allowed in static expressions.
default-mode Attribute[Definition: [Definition: 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.]
More specifically, when an element E matches the pattern (xsl:template[@match] | xsl:apply-templates)[not(@mode) or normalize-space(@mode) eq "#default"] (using the Unicode codepoint collation), then the effective value of the mode attribute is taken from the value of the [xsl:]default-mode attribute of the innermost ancestor-or-self element of E that has such an attribute. If there is no such element, then the default is the unnamed mode. This is equivalent to specifying #unnamed.
In addition, when the attribute appears on the xsl:package, xsl:stylesheet, or xsl:transform element of the principal stylesheet module of the top-level package, it provides a default value for the initial mode used on stylesheet invocation.
The value of the [xsl:]default-mode attribute must either be an EQName, or the token #unnamed which refers to the unnamed mode.
Note:
This attribute is provided to support an approach to stylesheet modularity in which all the template rules for one mode are collected together into a single stylesheet module. Using this attribute reduces the risk of forgetting to specify the mode in one or more places where it is needed, and it also makes it easier to reuse an existing stylesheet module that does not use modes in an application where modes are needed to avoid conflicts with existing template rules.
It is not necessary for the referenced mode to be explicitly declared in an xsl:mode declaration, unless this is mandated by the declared-modes attribute (which defaults to yes on an xsl:package element).
[Definition: [Definition: 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.]
[ERR XTSE0130] It is a static error if an xsl:stylesheet, xsl:transform, or xsl:package element has a child element whose name has a null namespace URI.
An implementation may attach an implementation-defined meaning to user-defined data elements that appear in particular namespaces. The set of namespaces that are recognized for such data elements is implementation-defined. The presence of a user-defined data element must not change the behavior of XSLT elements and functions defined in this document; for example, it is not permitted for a user-defined data element to specify that xsl:apply-templates should use different rules to resolve conflicts. The constraints on what user-defined data elements can and cannot do are exactly the same as the constraints on extension attributes, described in 24.1 Extension Attributes. Thus, an implementation is always free to ignore user-defined data elements, and must ignore such data elements without giving an error if it does not recognize the namespace URI.
User-defined data elements can provide, for example,
information used by extension instructions or extension functions (see 24 Extensibility and Fallback),
information about what to do with any final result tree,
information about how to construct source trees,
optimization hints for the processor,
metadata about the stylesheet,
structured documentation for the stylesheet.
[Definition: [Definition: The effective version of an element in a stylesheet module or package manifest is the decimal value of the [xsl:]version attribute (see 3.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.]
These rules do not apply to the xsl:output element, whose version attribute has an entirely different purpose: it is used to define the version of the output method to be used for serialization. The effective version of an xsl:output element is the effective version of its parent element.
There are additional rules for an xsl:fallback element: see 3.9 Forwards Compatible Processing.
[Definition: [Definition: An element is processed with backwards compatible behavior if its effective version is less than 4.0.]
Specifically:
If the effective version is equal to 1.0, then the element is processed with XSLT 1.0 behavior as described in 3.8.1 XSLT 1.0 Compatibility Mode.
If the effective version is equal to 2.0, then the element is processed with XSLT 2.0 behavior as described in 3.8.2 XSLT 2.0 Compatibility Mode.
If the effective version is equal to 3.0, then the element is processed with XSLT 3.0 behavior as described in 3.8.3 XSLT 3.0 Compatibility Mode.
If the effective version is any other value less than 4.0, the recommended action is to raise a static error; however, processors may recognize such values and process the element in an implementation-defined way.
Note:
XSLT 1.0 allowed the version attribute to take any decimal value, and invoked forwards compatible processing for any value other than 1.0. XSLT 2.0 allowed the attribute to take any decimal value, and invoked backwards compatible (i.e. 1.0-compatible) processing for any value less than 2.0. Some stylesheets may therefore be encountered that use values other than 1.0 or 2.0. In particular, the value 1.1 is sometimes encountered, as it was used at one stage in a draft language proposal.
It is implementation-defined whether a particular XSLT 4.0 implementation supports backwards compatible behavior for any XSLT version earlier than XSLT 4.0.
[ERR XTDE0160] It is a dynamic error if an element has an effective version of V (with V < 4.0) when the implementation does not support backwards compatible behavior for XSLT version V.
Note:
By making use of backwards compatible behavior, it is possible to write the stylesheet in a way that ensures that its results when processed with an XSLT 4.0 processor are identical to the effects of processing the same stylesheet using a processor for an earlier version of XSLT. To assist with transition, some parts of a stylesheet may be processed with backwards compatible behavior enabled, and other parts with this behavior disabled.
All data values manipulated by an XSLT 4.0 processor are defined by the XDM data model, whether or not the relevant expressions use backwards compatible behavior. Because the same data model is used in both cases, expressions are fully composable. The result of evaluating instructions or expressions with backwards compatible behavior is fully defined in the XSLT 4.0 and XPath 4.0 specifications, it is not defined by reference to earlier versions of the XSLT and XPath specifications.
To write a stylesheet that makes use of features that are new in version N, while also working with a processor that only supports XSLT version M (M < N), it is necessary to understand both the rules for backwards compatible behavior in XSLT version N, and the rules for forwards compatible behavior in XSLT version M. If the xsl:stylesheet element specifies a version attribute with a value greater than 1.0, then an XSLT 1.0 processor will ignore declarations that were not defined in XSLT 1.0, for example xsl:function, xsl:import-schema, and xsl:mode. If any new XSLT 4.0 instructions are used (for example xsl:switch or xsl:array), or if new XPath 4.0 features are used (for example, keyword arguments in function calls), then the stylesheet must provide fallback behavior that relies only on facilities available in the earliest XSLT version supported. The fallback behavior can be invoked by using the xsl:fallback instruction, or by testing the results of the function-available or element-available functions, or by testing the value of the xsl:version property returned by the system-property function.
[Definition: [Definition: An element in the stylesheet is processed with XSLT 1.0 behavior if its effective version is equal to 1.0.]
In this mode, if any attribute contains an XPath expression, then the expression is evaluated with XPath 1.0 compatibility mode set to true. For details of this mode, see [XPath 4.0] section 2.2.1 Static Context. Expressions contained in text value templates are always evaluated with XPath 1.0 compatibility mode set to false, since this construct was not available in XSLT 1.0.
Furthermore, in such an expression any function call for which no implementation is available (unless it uses the standard function namespace) is bound to a fallback error function whose effect when evaluated is to raise a dynamic error [see ERR XTDE1425] . The effect is that with backwards compatible behavior enabled, calls on extension functions that are not available in a particular implementation do not cause an error unless the function call is actually evaluated. For further details, see 24.2 Extension Functions.
Note:
This might appear to contradict the specification of XPath 3.0, which states that a static error [XPST0017] is raised when an expression contains a call to a function that is not present (with matching name and arity) in the static context. This apparent contradiction is resolved by specifying that the XSLT processor constructs a static context for the expression in which every possible function name and arity (other than names in the standard function namespace) is present; when no other implementation of the function is available, the function call is bound to a fallback error function whose run-time effect is to raise a dynamic error.
Certain XSLT constructs also produce different results when XSLT 1.0 compatibility mode is enabled. This is described separately for each such construct.
[Definition: [Definition: An element is processed with XSLT 2.0 behavior if its effective version is equal to 2.0.]
In this specification, no differences are defined for XSLT 2.0 behavior. An XSLT 4.0 processor will therefore produce the same results whether the effective version of an element is set to 2.0 or 4.0.
Note:
An XSLT 2.0 processor, by contrast, will in some cases produce different results in the two cases. For example, if the stylesheet contains an xsl:switch instruction with an xsl:fallback child, an XSLT 4.0 processor will process the xsl:switch instruction regardless whether the effective version is 2.0, 3.0, or 4.0, while an XSLT 2.0 processor will raise a static error if the effective version is 2.0, and will take the fallback action if the effective version is 3.0 or 4.0.
[Definition: [Definition: An element is processed with XSLT 3.0 behavior if its effective version is equal to 3.0.]
In this specification, no differences are defined for XSLT 3.0 behavior. An XSLT 4.0 processor will therefore produce the same results whether the effective version of an element is set to 3.0 or 4.0.
Note:
An XSLT 3.0 processor, by contrast, will in some cases produce different results in the two cases. For example, if the stylesheet contains an xsl:switch instruction with an xsl:fallback child, an XSLT 4.0 processor will process the xsl:switch instruction regardless whether the effective version is 2.0, 3.0, or 4.0, while an XSLT 3.0 processor will raise a static error if the effective version is 2.0 or 3.0, and will take the fallback action if the effective version is 4.0.
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.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: [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:
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.
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.
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.
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.
XSLT provides two mechanisms to construct a package from multiple stylesheet modules:
an inclusion mechanism that allows stylesheet modules to be combined without changing the semantics of the modules being combined, and
an import mechanism that allows stylesheet modules to override each other.
Changes in 4.0 (next | previous)
Duplicate xsl:include declarations within a stylesheet level are now ignored, preventing spurious errors caused by the presence of duplicate named components. [Issue 1449 PR 1454 17 September 2024]
<!-- Category: declaration -->
<xsl:include
href = uri />
A stylesheet module may include another stylesheet module using an xsl:include declaration.
The xsl:include declaration has a requiredhref attribute whose value is a URI reference identifying the stylesheet module to be included. This attribute is used as described in 3.10.1 Locating Stylesheet Modules.
[ERR XTSE0170] An xsl:include element must be a top-level element.
[Definition: [Definition: 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.]
Note:
A stylesheet level thus groups the declarations in a package by import precedence: two declarations within a package are in the same stylesheet level if and only if they have the same import precedence.
[Definition: [Definition: 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.] In other respects, however, the effect of xsl:include is not equivalent to the effect that would be obtained by textual inclusion.
If two or more xsl:include declarations within the same stylesheet level reference the same absolute URI, or reference different absolute URIs that are known to refer to the same resource, then the duplicate xsl:include declarations, other than the first in declaration order, are ignored. Similarly, an xsl:include declaration that references the top-level stylesheet module within its stylesheet level is ignored.
Note:
The above rule is new in XSLT 4.0. It can prevent the unwanted errors that can occur when assembling a stylesheet from multiple modules, where each module declares its dependencies using potentially redundant, and potentially circular xsl:include declarations.
In XSLT 3.0 and earlier versions, including the same module more than once would usually lead to errors caused by duplicate definitions of components such as global variables, named templates, or functions. In the rare case where the included module only contains template rules, the new rule could potentially cause a backwards incompatibility. However, it is very unlikely that a stylesheet author would do this intentionally.
The new rule does not apply when multiple xsl:include declarations for the same module appear in different stylesheet levels, that is, at different import precedences.
<!-- Category: declaration -->
<xsl:import
href = uri />
A stylesheet module may import another stylesheet module using an xsl:importdeclaration. Importing a stylesheet module is the same as including it (see 3.10.2 Stylesheet Inclusion) except that template rules and other declarations in the importing module take precedence over template rules and declarations in the imported module; this is described in more detail below.
The xsl:import declaration has a requiredhref attribute whose value is a URI reference identifying the stylesheet module to be included. This attribute is used as described in 3.10.1 Locating Stylesheet Modules.
[ERR XTSE0190] An xsl:import element must be a top-level element.
For example,
<xsl:stylesheet version="3.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:import href="article.xsl"/>
<xsl:import href="bigfont.xsl"/>
<xsl:attribute-set name="note-style">
<xsl:attribute name="font-style">italic</xsl:attribute>
</xsl:attribute-set>
</xsl:stylesheet>[Definition: [Definition: 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.] The ordering of the children is the declaration order of the xsl:import declarations within their stylesheet level.
[Definition: [Definition: 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.]
For example, suppose
stylesheet module A imports stylesheet modules B and C in that order;
stylesheet module B imports stylesheet module D;
stylesheet module C imports stylesheet module E.
Then the import tree has the following structure:
A
B
D
C
E
The order of import precedence (lowest first) is D, B, E, C, A.
In general, a declaration with higher import precedence takes precedence over a declaration with lower import precedence. This is defined in detail for each kind of declaration.
[ERR XTSE0210] It is a static error if a stylesheet module directly or indirectly references itself via a chain of xsl:include and xsl:import declarations that contains at least one xsl:import.
Note:
Under the new XSLT 4.0 rules, a cyclic reference that involves xsl:include only is ignored. A cycle involving xsl:import cannot be ignored, because it makes it impossible to determine which declarations have the highest import precedence.
Note:
The case where a stylesheet module with a particular URI is imported several times is not treated specially. The effect is exactly the same as if several stylesheet modules with different URIs but identical content were imported. This might or might not cause an error, depending on the content of the stylesheet module.
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.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: [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.
Source documents supplied as input to a transformation may be subject to preprocessing. Two kinds of preprocessing are defined: stripping of type annotations (see 4.2.1 Stripping Type Annotations from a Source Tree), and stripping of whitespace text nodes (see 4.2.2 Stripping Whitespace from a Source Tree).
Stripping of type annotations happens before stripping of whitespace text nodes.
The source documents to which this applies are as follows:
The document containing the global context item if it is a node;
Any documents containing a node present in the initial match selection;
Any document containing a node that is returned by the functions document, doc, or collection;
Any document read using xsl:source-document.
Note:
This list excludes documents passed as the values of stylesheet parameters or parameters of the initial named template or initial function, trees created by functions such as parse-xml, parse-xml-fragment, analyze-string, or json-to-xml, and values returned from extension functions.
If a node other than a document node is supplied (for example as the global context item), then the preprocessing is applied to the entire document containing that node. If several nodes within the same document are supplied (for example as nodes in the initial match selection, or as nodes returned by the collection function), then the preprocessing is only applied to that document once. If a whitespace text node is supplied (for example as the global context item) and the rules cause this node to be stripped from its containing tree, then the behavior is as if this node had not been supplied (which may cause an error, for example if a global context item is required.)
The rules determining whether or not stripping of annotations and/or whitespace happens are defined at the level of a package. Declarations within a library package only affect the handling of documents loaded using a call on the document, doc, or collection functions or an evaluation of an xsl:source-document instruction appearing lexically within the same package. Declarations within the top-level package also affect the processing of the global context item and the initial match selection.
The semantics of the document, doc, and collection functions are formally defined in terms of mappings from URIs to document nodes maintained within the dynamic context (see 5.3.3 Initializing the Dynamic Context). The effect of the declarations that control stripping of type annotations and whitespace is therefore to modify this mapping (so it now maps the URI to a stripped document). The modification applies to the dynamic context for calls to these function appearing within a particular package; each package therefore has a different set of mappings. This means that when two calls to the doc function appear in different packages, specifying the same absolute URI, then in general different documents are returned. An implementation may return the same document for two such calls if it is able to determine that the effect of the annotation and whitespace stripping rules in both packages is the same.
The effect of dynamic calls to the document, doc, and collection functions is defined in the same way as for other functions with dependencies on the dynamic context. As described in 5.3.4 Additional Dynamic Context Components used by XSLT, named function references (such as doc#1) and calls on function-lookup (for example, function-lookup("doc", 1)) are defined to retain the XPath static and dynamic context at the point of invocation as part of the closure of the resulting function item, and to use this preserved context when a dynamic function call is subsequently made using the function item.
[Definition: [Definition: The term type annotation is used in this specification to refer to the value returned by the dm:type-name accessor of a node: see [XDM 4.0] section 7.6.13 type-name Accessor.]
There is sometimes a requirement to write stylesheets that produce the same results whether or not the source documents have been validated against a schema. To achieve this, an option is provided to remove any type annotations on element and attribute nodes in a source tree, replacing them with an annotation of xs:untyped in the case of element nodes, and xs:untypedAtomic in the case of attribute nodes.
Such stripping of type annotations can be requested by specifying input-type-annotations="strip" on the xsl:package element. This attribute has three permitted values: strip, preserve, and unspecified. The default value is unspecified. Specifying unspecified has the same effect as omitting the attribute.
The input-type-annotations attribute may also be specified on the xsl:stylesheet element; if it is specified at this level then it must be consistent for all stylesheet modules within the same package.
[ERR XTSE0265] It is a static error if there is a stylesheet module in a package that specifies input-type-annotations="strip" and another stylesheet module that specifies input-type-annotations="preserve", or if a stylesheet module specifies the value strip or preserve and the same value is not specified on the xsl:package element of the containing package.
Type annotations are stripped from relevant source documents if at least one stylesheet module in the stylesheet specifies input-type-annotations="strip" on the xsl:package, xsl:stylesheet, or xsl:transform element.
When type annotations are stripped, the following changes are made to the source tree:
The type annotation of every element node is changed to xs:untyped
The type annotation of every attribute node is changed to xs:untypedAtomic
The typed value of every element and attribute node is set to be the same as its string value, as an instance of xs:untypedAtomic.
The is-nilled property of every element node is set to false.
The values of the is-id and is-idrefs properties are not changed.
Note:
Stripping type annotations does not necessarily return the document to the state it would be in had validation not taken place. In particular, any defaulted elements and attributes that were added to the tree by the validation process will still be present, and elements and attributes validated as IDs will still be accessible using the id function.
Many constructs appearing in a stylesheet, for example named templates, modes, and attribute sets, are named using a qualified name: this consists of a local name and an optional namespace URI.
In most cases where such names are written in a stylesheet, the syntax for expressing the name is given by the production EQNameXP in the XPath specification. In practice, this means that three forms are permitted:
A simple NCName appearing on its own (without any prefix). This represents the local name of the object. The interpretation of unprefixed names is described below.
A lexical QName written in the form NCName ":" NCName where the first part is a namespace prefix and the second part is the local name. The namespace part of the object’s name is then derived from the prefix by examining the applicable static namespaces for the element node in the stylesheet where the name appears.
A URIQualifiedNameXP in the form "Q{" URI? "}" NCName where the two parts of the name, that is the namespace part and the local part, both appear explicitly. If the URI part is omitted (for example Q{}local), the resulting expanded QName is a QName whose namespace part is absent.
The rules for the use of these constructs generally permit leading and trailing whitespace, which is ignored.
Note:
There are a few places where the third form, a URIQualifiedName, is not permitted. These include the name attribute of xsl:element and xsl:attribute (which have a separate namespace attribute for the purpose), and constructs defined by other specifications. For example, names appearing within an embedded xs:schema element must follow the XSD rules.
[Definition: [Definition: An expanded QName is a value in the value space of the xs:QName datatype as defined in the XDM data model (see [XDM 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.]
[Definition: [Definition: An EQName is a string representing an expanded QName where the string, after removing leading and trailing whitespace, is in the form defined by the EQNameXP production in the XPath specification.]
[Definition: [Definition: A lexical QName is a string representing an expanded QName where the string, after removing leading and trailing whitespace, is within the lexical space of the xs:QName datatype as defined in XML Schema (see [XML Schema Part 2]): that is, a local name optionally preceded by a namespace prefix and a colon.]
Note that every lexical QName is an EQName, but the converse is not true.
The following rules are used when interpreting a lexical QName:
[Definition: [Definition: A string in the form of a lexical QName may occur as the value of an attribute node in a stylesheet module, or within an XPath expression contained in an attribute or text node within a stylesheet module, or as the result of evaluating an XPath expression contained in such a node. The element containing this attribute or text node is referred to as the defining element of the lexical QName.]
If the lexical QName has a prefix, then the prefix is expanded into a URI reference using the namespace declarations in effect on its defining element. The expanded QName consisting of the local part of the name and the possibly null URI reference is used as the name of the object. The default namespace of the defining element (see [XDM 4.0] section 7.5.2 Element nodes) is not used for unprefixed names.
[ERR XTSE0280] In the case of a prefixed lexical QName used as the value (or as part of the value) of an attribute in the stylesheet, or appearing within an XPath expression in the stylesheet, it is a static error if the defining element has no namespace node whose name matches the prefix of the lexical QName.
[ERR XTDE0290] Where the result of evaluating an XPath expression (or an attribute value template) is required to be a lexical QName, or if it is permitted to be a lexical QName and the actual value takes the form of a lexical QName, then unless otherwise specified it is a dynamic error if the value has a prefix and the defining element has no namespace node whose name matches that prefix. This error may be raised as a static error if the value of the expression can be determined statically.
If the lexical QName has no prefix, then:
In the case of an unprefixed QName used as a NameTest within an XPath expression (see 5.2 Expressions), and in certain other contexts, the namespace to be used in expanding the QName may be specified by means of the [xsl:]xpath-default-namespace attribute, as specified in 5.1.2 Unprefixed Lexical QNames in Expressions and Patterns.
If the name is in one of the following categories, then the default namespace of the defining element is used:
Where a QName is used to define the name of an element being constructed. This applies both to cases where the name is known statically (that is, the name of a literal result element) and to cases where it is computed dynamically (the value of the name attribute of the xsl:element instruction).
The default namespace is used when expanding the first argument of the function element-available.
The default namespace applies to any unqualified element names appearing in the cdata-section-elements or suppress-indentation attributes of xsl:output or xsl:result-document
In all other cases, a lexical QName with no prefix represents an expanded QName in no namespace (that is, an xs:QName value in which both the prefix and the namespace URI are absent).
[Definition: [Definition: The XSLT namespace, together with certain other namespaces recognized by an XSLT processor, are classified as reserved namespaces and must be used only as specified in this and related specifications.] The reserved namespaces are those listed below.
Each of the reserved namespaces has a conventional prefix. As described in 3.6.1 The fixed-namespaces Attribute, the fixed-namespaces attribute may bind one of the reserved namespaces simply by referring to its conventional prefix. For example, fixed-namespaces="xs" has the effect of binding the prefix xs to the namespace http://www.w3.org/2001/XMLSchema.
The XSLT namespace described in 3.1.1 XSLT Namespace, is reserved, with conventional prefix xsl.
[Definition: [Definition: The standard function namespacehttp://www.w3.org/2005/xpath-functions, with conventional prefix fn, is used for functions in the function library defined in [Functions and Operators 4.0] and for standard functions defined in this specification.]
The namespace http://www.w3.org/2005/xpath-functions/math, with conventional prefix math, is used for mathematical functions in the function library defined in [Functions and Operators 4.0].
The namespace http://www.w3.org/2005/xpath-functions/map, with conventional prefix map, is used for functions defined in this specification relating to the manipulation of maps.
The namespace http://www.w3.org/2005/xpath-functions/array, with conventional prefix array, is reserved for use as described in [Functions and Operators 4.0].
[Definition: [Definition: The XML namespace, defined in [Namespaces in XML] as http://www.w3.org/XML/1998/namespace, is used for attributes such as xml:lang, xml:space, and xml:id.]This namespace is always bound to the prefix xml.
[Definition: [Definition: The schema namespacehttp://www.w3.org/2001/XMLSchema, with conventional prefix xs, is used as defined in [XML Schema Part 1]]. In a stylesheet this namespace may be used to refer to built-in schema datatypes and to the constructor functions associated with those datatypes.
[Definition: [Definition: The schema instance namespacehttp://www.w3.org/2001/XMLSchema-instance, with conventional prefix xsi, is used as defined in [XML Schema Part 1]]. Attributes in this namespace, if they appear in a stylesheet, are treated by the XSLT processor in the same way as any other attributes.
[Definition: [Definition: The standard error namespacehttp://www.w3.org/2005/xqt-errors, with conventional prefix err, is used for error codes defined in this specification and related specifications. It is also used for the names of certain predefined variables accessible within the scope of an xsl:catch element.]
The namespace http://www.w3.org/2000/xmlns/ is reserved for use as described in [Namespaces in XML]. No element or attribute node can have a name in this namespace, and although the prefix xmlns is implicitly bound to this namespace, no namespace node will ever define this binding.
Note:
With the exception of the XML namespace, any of the above namespaces that are used in a stylesheet must be explicitly declared with a namespace declaration. Although conventional prefixes are used for these namespaces in this specification, any prefix may be used in a user stylesheet.
Reserved namespaces may be used without restriction to refer to the names of elements and attributes in source documents and result documents. As far as the XSLT processor is concerned, reserved namespaces other than the XSLT namespace may be used without restriction in the names of literal result elements and user-defined data elements, and in the names of attributes of literal result elements or of XSLT elements: but other processors may impose restrictions or attach special meaning to them. Reserved namespaces must not be used, however, in the names of stylesheet-defined objects such as variables and stylesheet functions, nor in the names of extension functions or extension instructions.
It is not an error to use a reserved namespace in the name of an extension attribute: attributes such as xml:space and xsi:type fall into this category. XSLT processors must not reject such attributes, and must not attach any meaning to them other than any meaning defined by the relevant specification.
[ERR XTSE0080] It is a static error to use a reserved namespace in the name of a named template, a mode, an attribute set, a key, a decimal-format, a variable or parameter, a stylesheet function, a named output definition, an accumulator, or a character map; except that the name xsl:initial-template is permitted as a template name.
Note:
The name xsl:original is used within xsl:override to refer to a component that is being overridden. Although the name xsl:original is used to refer to the component, the component has its own name, and no component ever has the name xsl:original.
XSLT uses the expression language defined by XPath 4.0 [XPath 4.0]. Expressions are used in XSLT for a variety of purposes including:
selecting nodes for processing;
specifying conditions for different ways of processing a node;
generating text to be inserted in a result tree.
[Definition: [Definition: Within this specification, the term XPath expression, or simply expression, means a string that matches the production ExprXP defined in [XPath 4.0].]
XPath expressions may occur:
As the value of certain attributes on XSLT-defined instructions (for example, the select attribute of the xsl:apply-templates instruction)
Within curly brackets in attribute value templates and text value templates.
As the content of a text node within an xsl:select instruction.
In the above cases, the static processing (compilation) of XPath expressions takes place at the same time as the static processing of the stylesheet itself, while evaluation of the XPath expressions takes place dynamically during stylesheet evaluation. There are also, however:
XPath expressions where both the static processing and dynamic evaluation of the XPath expression takes place during static processing of the stylesheet. These are referred to as static expressions, and they perform the same function as preprocessing directives in other languages.
XPath expressions that are dynamically constructed (as character strings): both the static processing and dynamic evaluation of these expressions occurs during stylesheet evaluation. See 10.5 Dynamic XPath Evaluation.
In general:
It is a static error if an XPath expression does not match the XPath production ExprXP, or if it fails to satisfy other static constraints defined in the XPath specification, for example that all variable references must refer to variables that are in scope. Error codes are defined in [XPath 4.0].
The transformation fails with a dynamic error if any XPath expression is evaluated and raises a dynamic error. Error codes are defined in [XPath 4.0].
The transformation fails with a type error if an XPath expression raises a type error, or if the result of evaluating the XPath expression is evaluated and raises a type error, or if the XPath processor raises a type error during static analysis of an expression. Error codes are defined in [XPath 4.0].
There are some exceptions to these rules, for example:
Static errors may be suppressed where forwards compatible behavior is enabled (see 3.9 Forwards Compatible Processing).
Dynamic errors evaluating a predicate within a pattern do not cause the transformation to fail, they merely cause the pattern not to match.
[Definition: [Definition: The context within a stylesheet where an XPath expression appears may specify the required type of the expression. The required type indicates the type of the value that the expression is expected to return.] If no required type is specified, the expression may return any value: in effect, the required type is then item()*.
[Definition: [Definition: The term coercion rules means the coercion rules defined in [XPath 4.0], applied unless otherwise specified with XPath 1.0 compatibility mode set to false.]
Note:
In earlier versions of this specification, the coercion rules were referred to as the function conversion rules.
Note:
These are the rules defined in [XPath 4.0] for converting the supplied argument of a function call to the required type of that argument, as defined in the function signature. The same rules are used in XSLT for converting the value of a variable to the declared type of the variable, or the result of evaluating a function or template body to the declared type of the function or template. They are also used when parameters are supplied to a template using xsl:with-param. In all such cases, the rules that apply are the XPath 4.0 rules without XPath 1.0 compatibility mode. The rules with XPath 1.0 compatibility mode set to true are used only for XPath function calls, and for the operands of certain XPath operators.
This specification also invokes the XPath coercion rules to convert the result of evaluating an XSLT sequence constructor to a required type (for example, the sequence constructor enclosed in an xsl:variable, xsl:template, or xsl:function element).
Any dynamic error or type error that occurs when applying the coercion rules to convert a value to a required type results in the transformation failing, in the same way as if the error had occurred while evaluating an expression.
Note:
Note the distinction between the two kinds of error that may occur. Attempting to convert an integer to a date is a type error, because such a conversion is never possible. Type errors can be raised statically if they can be detected statically, whether or not the construct in question is ever evaluated. Attempting to convert the xs:untypedAtomic item 2003-02-29 to a date is a dynamic error rather than a type error, because the problem is with this particular value, not with its type. Dynamic errors are raised only if the instructions or expressions that cause them are actually evaluated.
The XPath specification states (see [XPath 4.0] section A.3.3 End-of-Line Handling) that the host language must specify whether the XPath processor normalizes all line breaks on input, before parsing, and if it does so, whether it uses the rules of [XML 1.0] or [XML 1.1]. In the case of XSLT, all handling of line breaks is the responsibility of the XML parser (which may support either XML 1.0 or XML 1.1); the XSLT and XPath processors perform no further changes.
Note:
Most XPath expressions in a stylesheet appear within XML attributes. They are therefore subject to XML line-ending normalization (for example, a CRLF sequence is normalized to LF) and also to XML attribute-value normalization, which replaces tabs and newlines by spaces. Normalization of whitespace can be prevented by using character references such as 	.
XPath expressions appearing in text nodes, (specifically, in text value templates — see 5.6.2 Text Value Templates, or in the xsl:select instruction) are subject to line-ending normalization but not attribute-value normalization.
In both cases it is unwise to include the characters U+0009 (TAB) , U+000A (NEWLINE) , and U+000D (CARRIAGE RETURN) , as literal characters within string literals. Instead they should be escaped as 	, 
, and 
 respectively, or constructed dynamically by a call on the char function. This can be conveniently embedded within a string template delimited by backticks: for example `Width:{char(9)}8mm`. (The advantage of using this form in preference to XML character references is that they are more likely to survive when the stylesheet is processed using tools such as XML editors.)
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
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.11.3 Conditional Element Inclusion.
[Definition: [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.
[Definition: [Definition: When a sequence constructor is evaluated, the processor keeps track of which items are being processed by means of a set of implicit variables referred to collectively as the focus.] More specifically, the focus consists of the following three values:
[Definition: [Definition: 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.] The context item is returned by the XPath expression. (dot).
Note:
Although XPath 4.0 allows the context value to be an arbitrary sequence, at the interface between XSLT 4.0 and XPath 4.0 it is always either a single item, or absent. XSLT 4.0 therefore continues to use the term context item rather than context valueXP.
[Definition: [Definition: The context position is the position of the context item within the sequence of items currently being processed. It changes whenever the context item changes. When an instruction such as xsl:apply-templates or xsl:for-each is used to process a sequence of items, the first item in the sequence is processed with a context position of 1, the second item with a context position of 2, and so on.] The context position is returned by the XPath expressionposition().
[Definition: [Definition: The context size is the number of items in the sequence of items currently being processed. It changes whenever instructions such as xsl:apply-templates and xsl:for-each are used to process a sequence of items; during the processing of each one of those items, the context size is set to the count of the number of items in the sequence (or equivalently, the position of the last item in the sequence).] The context size is returned by the XPath expressionlast().
[Definition: [Definition: If the context item is a node (as distinct from an atomic item such as an integer), then it is also referred to as the context node. The context node is not an independent variable, it changes whenever the context item changes. When the context item is an atomic item or a function item, there is no context node.] The context node is returned by the XPath expressionself::node(), and it is used as the starting node for all relative path expressions.
Where the containing element of an XPath expression is an instruction or a literal result element, the initial context item, context position, and context size for the XPath expression are the same as the context item, context position, and context size for the evaluation of the containing instruction or literal result element.
The context valueXP for evaluating global variables declared in the top-level package is set to the global context item supplied when the transformation is invoked (see 2.3 Initiating a Transformation). For global variables declared in a library package, the context value is absent.
For an XPath expression contained in a value template, the initial context item, context position, and context size for the XPath expression are the same as the context item, context position, and context size for the evaluation of the containing sequence constructor.
In other cases (for example, where the containing element is xsl:sort, xsl:with-param, or xsl:key), the rules are given in the specification of the containing element.
The current function can be used within any XPath expression to select the item that was supplied as the context item to the XPath expression by the XSLT processor. Unlike . (dot) this is unaffected by changes to the context item that occur within the XPath expression. The current function is described in 20.5.1 fn:current.
On completion of an instruction that changes the focus (such as xsl:apply-templates or xsl:for-each), the focus reverts to its previous value.
When a stylesheet function is called, the focus within the body of the function is initially absent.
When the focus is absent, evaluation of any expression that references the context item, context position, or context size results in a type error[ERR XPDY0002] XP40
The description above gives an outline of the way the focus works. Detailed rules for the effect of each instruction are given separately with the description of that instruction. In the absence of specific rules, an instruction uses the same focus as its parent instruction.
[Definition: [Definition: A singleton focus based on an item J has the context item (and therefore the context node, if J is a node) set to J, and the context position and context size both set to 1 (one).]
The previous section explained how the focus for an XPath expression appearing in an XSLT stylesheet is initialized. This section explains how the other components of the dynamic contextXP of an XPath expression are initialized.
The dynamic variablesXP are the current values of the in-scope variable binding elements.
The dynamically known function definitionsXP (representing the functions accessible using function-available or function-lookup) include all the functions available in the static context, and may also include an additional implementation-defined set of functions that are available dynamically but not statically.
Note:
This set therefore includes some functions that are not available for dynamic calling using xsl:evaluate, for example stylesheet functions whose visibility is private, and XSLT-defined functions such as current and key.
Note:
The rule that all functions present in the static context must always be present in the dynamic context is a consistency constraint. The effect of violating a consistency constraint is implementation-defined: it does not necessarily lead to an error. For example, if the version of a used package that is available at evaluation time does not include all public user-defined functions that were available in the version that was used at analysis time, then a processor may recover by raising an error only if the function is actually called. Conversely, if the evaluation-time version of the package includes additional public functions, these may be included in the dynamic context even though they were absent from the static context. Dynamic calling of functions using function-lookup may therefore be an effective strategy for coping with variations between versions of a library package on which a stylesheet depends.
The default collationXP is defined by the value of the [xsl:]default-collation attribute on the innermost enclosing element that has such an attribute. For details, see 3.6.2 The default-collation Attribute.
[Definition: [Definition: 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.]
This collation is also used by default when comparing strings in the evaluation of the xsl:key and xsl:for-each-group elements. This may also (but need not necessarily) be the same as the default collation used for xsl:sort elements within the stylesheet. Collations used by xsl:sort are described in 13.1.3 Sorting Using Collations.
Note:
The default collation is usually known statically. One notable exception is when the function call default-collation() appears in the initializing expression of an optional xsl:function parameter, for example:
<xsl:function name="f:myfunc"> <xsl:param name="collation" required="no" select="default-collation()"/> </xsl:function>
In this situation the call on default-collation() returns the default collation from the context of the function call, which may differ from the default collation of the function declaration.
The available documentsXP are defined as part of the XPath 3.0 dynamic context to support the doc function, but this component is also referenced by the similar XSLT document function: see 20.1 fn:document. This variable defines a mapping between URIs passed to the doc or document function and the document nodes that are returned.
The mapping from URIs to document nodes is affected by xsl:strip-space declarations and by the input-type-annotations attribute, and may therefore vary from one package to another.
Note:
Defining this as part of the evaluation context is a formal way of specifying that the way in which URIs get turned into document nodes is outside the control of the language specification, and depends entirely on the run-time environment in which the transformation takes place.
The XSLT-defined document function allows the use of URI references containing fragment identifiers. The interpretation of a fragment identifier depends on the media type of the resource representation. Therefore, the information supplied in available documentsXP for XSLT processing must provide not only a mapping from URIs to document nodes as required by XPath, but also a mapping from URIs to media types.
All other aspects of the dynamic context (for example, the current date and time, the implicit timezone, the default language, calendar, and place, the available documents, text resources, and collections, and the default collection) are implementation-defined, and do not change in the course of a single transformation, except to the extent that they may be different from one package to another.
In addition to the values that make up the focus, an XSLT processor maintains a number of other dynamic context components that reflect aspects of the evaluation context. These components are fully described in the sections of the specification that maintain and use them. They are:
The current template rule, which is the template rule most recently invoked by an xsl:apply-templates, xsl:apply-imports, or xsl:next-match instruction: see 6.9 Overriding Template Rules;
The current mode, which is the mode set by the most recent call of xsl:apply-templates (for a full definition see 6.7 Modes);
The current group and current grouping key, which provide information about the collection of items currently being processed by an xsl:for-each-group instruction: see 14.2.1 fn:current-group and 14.2.2 fn:current-grouping-key;
Note:
In XSLT 3.0 the initial value of these two properties is “absent”, which means that any reference to their values causes a dynamic error. Previously, the initial value was the empty sequence.
The current merge group and current merge key, which provide information about the collection of items currently being processed by an xsl:merge instruction.
The current captured groups: this is maintained when a string is matched against a regular expression using the xsl:analyze-string instruction. It is a map from integer group numbers (reflecting the ordering of capturing parentheses with the regular expression) to string segments: a string segment is a contiguous substring of the input string being matched, characterized by the position of the first and last characters of the substring within the input. The current captured groups are accessible to applications using the regex-groups and regex-group functions: see 17.2.2 fn:regex-group.
The output state: this is a flag whose two possible values are final output state and temporary output state. The initial setting when the stylesheet is invoked by executing a template is final output state, and it is switched to temporary output state by instructions such as xsl:variable. For more details, see 25.2 Restrictions on the use of xsl:result-document.
The current output URI: this is the URI associated with the result tree to which instructions are currently writing. The current output URI is initially the same as the base output URI. During the evaluation of an xsl:result-document instruction, the current output URI is set to the absolute URI identified by the href attribute of that instruction.
The following non-normative table summarizes the initial state of each of the components in the evaluation context, and the instructions which cause the state of the component to change.
[Definition: [Definition: The initial setting of a component of the dynamic context is used when evaluating global variables and stylesheet parameters, when evaluating the use and match attributes of xsl:key, and when evaluating the initial-value of xsl:accumulator and the select expressions or contained sequence constructors of xsl:accumulator-rule].
[Definition: [Definition: The term non-contextual function call is used to refer to function calls that do not pass the dynamic context to the called function. This includes all calls on stylesheet functions and all dynamic function callsXP, (that is calls to function items). It excludes calls to some functions in the namespace http://www.w3.org/2005/xpath-functions, in particular those that explicitly depend on the context, such as the current-group and regex-group functions. It is implementation-defined whether, and under what circumstances, calls to extension functions are non-contextual.]
Named function references (such as position#0) and calls on function-lookup (for example, function-lookup("position", 0)) are defined to retain the XPath static and dynamic context at the point of invocation as part of the closure of the resulting function item, and to use this preserved context when a dynamic function call is subsequently made using the function item. In XSLT 4.0 this rule extends to the XSLT extensions to the dynamic context defined in this section. For example the call regex-group#1) delivers a function item that holds a snapshot of the in its closure, and subsequent evaluation of that function item will return the relevant value from that snapshot.
The definition of the format-number function is now in [Functions and Operators 4.0]. This section is a specification of the xsl:decimal-format declaration, which provides the context for this function when used in an XSLT stylesheet.
<!-- Category: declaration -->
<xsl:decimal-format
name? = eqname
decimal-separator? = string〔'.'〕
grouping-separator? = string〔','〕
infinity? = string〔'Infinity'〕
minus-sign? = string〔'-'〕
exponent-separator? = string〔'e'〕
NaN? = string〔'NaN'〕
percent? = string〔'%'〕
per-mille? = string〔'‰'〕
zero-digit? = char〔'0'〕
digit? = char〔'#'〕
pattern-separator? = char〔';'〕 />
The xsl:decimal-format element sets the statically known decimal formats component of the static context for XPath expressions, which controls the interpretation of a picture string used by the format-number function.
[Definition: [Definition: The picture string is the string supplied as the second argument of the format-number function.]
A package may contain multiple xsl:decimal-format declarations and may include or import stylesheet modules that also contain xsl:decimal-format declarations. The name of an xsl:decimal-format declaration is the value of its name attribute, if any.
[Definition: [Definition: 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.]
The attributes of the xsl:decimal-format declaration define the value of the corresponding property in the relevant decimal format in the statically known decimal formatsXP component of the static context for all XPath expressions in the package. The attribute names used in the XSLT 4.0 syntax are the same as the property names used in the definition of the static context.
The scope of an xsl:decimal-format name is the package in which it is declared; the name is available for use only in calls to format-number that appear within the same package.
If a package does not contain a declaration of the unnamed decimal format, a declaration equivalent to an xsl:decimal-format element with no attributes is implied.
The attributes of the xsl:decimal-format declaration establish values for a number of variables used as input to the algorithm followed by the format-number function. An outline of the purpose of each attribute is given below; however, the definitive explanations are given as part of the specification of format-number.
For any named decimal format, the effective value of each attribute is taken from an xsl:decimal-format declaration that has that name, and that specifies an explicit value for the required attribute. If there is no such declaration, the default value of the attribute is used. If there is more than one such declaration, the one with highest import precedence is used.
For any unnamed decimal format, the effective value of each attribute is taken from an xsl:decimal-format declaration that is unnamed, and that specifies an explicit value for the required attribute. If there is no such declaration, the default value of the attribute is used. If there is more than one such declaration, the one with highest import precedence is used.
[ERR XTSE1290] It is a static error if a named or unnamed decimal format contains two conflicting values for the same attribute in different xsl:decimal-format declarations having the same import precedence, unless there is another definition of the same attribute with higher import precedence.
The following attributes control the interpretation of characters in the picture string supplied to the format-number function, and also specify characters that may appear in the result of formatting the number. In each case the value must either be a single character, or a string in the form m:r where m is a single character (the marker) used to represent the property in the picture string, and r (the rendition) is an arbitrary string used to represent the property in the formatted result: [see ERR XTSE0020].
decimal-separator specifies the string used to separate the integer part from the fractional part of the formatted number; the default value is U+002E (FULL STOP, PERIOD, .) .
exponent-separator specifies the string used to separate the mantissa from the exponent in scientific notation; the default value is U+0065 (LATIN SMALL LETTER E, e) .
grouping-separator specifies the string typically used as a thousands separator; the default value is U+002C (COMMA, ,) .
percent specifies the string used to indicate that the number is represented as a per-hundred fraction; the default value is U+0025 (PERCENT SIGN, %) .
per-mille specifies the string used to indicate that the number is represented as a per-thousand fraction; the default value is U+2030 (PER MILLE SIGN, ‰) .
[ERR XTSE1295] It is a static error if the character specified in the zero-digit attribute is not a digit or is a digit that does not have the numeric value zero.
The following attributes control the interpretation of characters in the picture string supplied to the format-number function. In each case the value must be a single character [see ERR XTSE0020]. The zero-digit property also affects the characters used to render digits in the formatted result:
zero-digit specifies the character used to represent the digit zero; the default value is U+0030 (DIGIT ZERO, 0) . This character must be a digit (category Nd in the Unicode property database), and it must have the numeric value zero. This attribute implicitly defines the Unicode character that is used to represent each of the values 0 to 9 in the final result string: Unicode is organized so that each set of decimal digits forms a contiguous block of characters in numerical sequence.
digit specifies the character used in the picture string as a place-holder for an optional digit; the default value is U+0023 (NUMBER SIGN, #) .
pattern-separator specifies the character used to separate positive and negative sub-pictures in a picture string; the default value is U+003B (SEMICOLON, ;) .
The following attributes specify strings that may appear in the result of formatting the number:
infinity specifies the string used to represent the xs:double value INF; the default value is the string Infinity
NaN specifies the string used to represent the xs:double value NaN (not-a-number); the default value is the string NaN
minus-sign specifies the string used to indicate a negative number; the default value is U+002D (HYPHEN-MINUS, -) .
[ERR XTSE1300] It is a static error if, for any named or unnamed decimal format, the properties identifying marker characters to be used in a picture string do not identify distinct values. These properties are decimal-separator, grouping-separator, exponent-separator, percent, per-mille, zero-digit, digit, and pattern-separator.
Every (named or unnamed) decimal format defined in a package is added to the statically known decimal formatsXP in the static contextXP of every expression in the package, excluding expressions appearing in [xsl:]use-when attributes.
The string value of an attribute or text node in the stylesheet may in particular circumstances contain embedded expressions enclosed between curly brackets. Attributes and text nodes that use (or are permitted to use) this mechanism are referred to respectively as attribute value templates and text value templates.
[Definition: [Definition: Collectively, attribute value templates and text value templates are referred to as value templates.]
A value template is a string consisting of an alternating sequence of fixed parts and variable parts:
A variable part consists of an optional XPath expression enclosed in curly brackets ({}): more specifically, a string conforming to the XPath production Expr?.
Note:
An expression within a variable part may contain an unescaped curly bracket within a StringLiteralXP or within a comment.
Currently no XPath expression starts with an opening curly bracket, so the use of {{ creates no ambiguity. If an enclosed expression ends with a closing curly bracket, no whitespace is required between this and the closing delimiter.
The fact that the expression is optional means that the string contained between the curly brackets may be zero-length, may comprise whitespace only, or may contain XPath comments. The effective value in this case is a zero-length string, which is equivalent to omitting the variable part entirely, together with its curly-bracket delimiters.
A fixed part may contain any characters, except that a left curly bracket must be written as {{ and a right curly bracket must be written as }}.
[ERR XTSE0350] It is a static error if an unescaped left curly bracket appears in a fixed part of a value template without a matching right curly bracket.
It is a static error if the string contained between matching curly brackets in a value template does not match the XPath production Expr?XP, or if it contains other XPath static errors. The error is raised using the appropriate XPath error code.
[ERR XTSE0370] It is a static error if an unescaped right curly bracket occurs in a fixed part of a value template.
The result of evaluating a value template is referred to as its effective value. The effective value is the string obtained by concatenating the expansions of the fixed and variable parts:
The expansion of a fixed part is obtained by replacing any double curly brackets ({{ or }}) by the corresponding single curly bracket.
The expansion of a variable part is as follows:
If an expression is present, the result of evaluating the enclosed XPath expression and converting the resulting value to a string. This conversion is done using the rules given in 5.7.2 Constructing Simple Content.
If the expression is omitted, a zero-length string.
Note:
This process can raise dynamic errors, for example if the sequence contains an element with a complex content type (which cannot be atomized).
In the case of an attribute value template, the effective value becomes the string value of the new attribute node. In the case of a text value template, the effective value becomes the string value of the new text node.
[Definition: [Definition: 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].
Curly brackets are not treated specially in an attribute value in an XSLT stylesheet unless the attribute is specifically designated as one that permits an attribute value template; in an element syntax summary, the value of such attributes is surrounded by curly brackets.
Note:
Not all attributes are designated as attribute value templates. Attributes whose value is an expression or pattern, attributes of declaration elements and attributes that refer to named XSLT objects are generally not designated as attribute value templates (an exception is the format attribute of xsl:result-document). Namespace declarations are not XDM attribute nodes and are therefore never treated as attribute value templates.
If the element containing the attribute is processed with XSLT 1.0 behavior, then the rules for converting the value of the expression to a string (given in 5.6 Value Templates) are modified as follows. After atomizing the result of the expression, all items other than the first item in the resulting sequence are discarded, and the effective value is obtained by converting the first item in the sequence to a string. If the atomized sequence is empty, the result is a zero-length string.
Note:
The above rule applies to attribute value templates but not to text value templates, since the latter were not available in XSLT 1.0.
The following example creates an img result element from a photograph element in the source; the value of the src and width attributes are computed using XPath expressions enclosed in attribute value templates:
<xsl:variable name="image-dir" select="'/images'"/>
<xsl:template match="photograph">
<img src="{ $image-dir }/{ href }" width="{ size/@width }"/>
</xsl:template>With this source
<photograph> <href>headquarters.jpg</href> <size width="300"/> </photograph>
the result would be
<img src="/images/headquarters.jpg" width="300"/>
The following example shows how the values in a sequence are output as a space-separated list. The following literal result element:
<temperature readings="{10.32, 5.50, 8.31}"/>produces the output node:
<temperature readings="10.32 5.5 8.31"/>
Curly brackets are not recognized recursively inside expressions.
The standard attribute[xsl:]expand-text may appear on any element in the stylesheet, and determines whether descendant text nodes of that element are treated as text value templates. A text node in the stylesheet is treated as a text value template if (a) it is part of a sequence constructor, (b) there is an ancestor element with an [xsl:]expand-text attribute, and (c) on the innermost ancestor element that has such an attribute, the value of the attribute is yes. The attribute is boolean and must therefore take one of the values yes (synonyms true or 1) or no (synonyms false or 0).
This section describes how text nodes are processed when the effective value is yes. Such text nodes are referred to as text value templates.
[Definition: [Definition: In a text node that is designated as a text value template, expressions can be used by surrounding each expression with curly brackets ({}).]
The rules for text value templates are given in 5.6 Value Templates. A text node whose value is a text value template results in the construction of a text node in the result of the containing sequence constructor. The string value of that text node is obtained by computing the effective value of the value template.
Note:
The result of evaluating a text value template is a (possibly zero-length) text node. This text node becomes part of the result of the containing sequence constructor, and is thereafter handled exactly as if the value had appeared explicitly as a text node in the stylesheet.
The way in which the effective value is computed does not depend on any separator attribute on a containing xsl:text, xsl:value-of or xsl:attribute instruction. The separator attribute only affects how the text node is combined with adjacent items in the result of the containing sequence constructor.
Fixed parts consisting entirely of whitespace are significant and are handled in the same way as any other fixed part. This is different from the default treatment of “boundary space” in XQuery.
<xsl:variable name="id" select="'A123'"/>
<xsl:variable name="step" select="5"/>
<xsl:message expand-text="yes"
>Processing id={ $id }, step={ $step }</xsl:message>This will typically output the message text Processing id=A123, step=5.
<xsl:function name="f:sum" expand-text="yes" as="xs:integer">
<xsl:param name="x" as="xs:integer"/>
<xsl:param name="y" as="xs:integer"/>
{ $x + $y }
</xsl:function>Note that although this is a very readable way of expressing the computation performed by the function, the semantics are somewhat complex, and this could mean that execution is inefficient. The function computes the value of $x + $y as an integer, and then constructs a text node containing the string representation of this integer (preceded and followed by whitespace). Because the declared result type of the function is xs:integer, this text node is then atomized, giving an xs:untypedAtomic item, and the xs:untypedAtomic item is then cast to an xs:integer.
Note:
The main motivations for adding text value templates to the XSLT language are firstly, to make it easier to construct parameterized text in contexts such as xsl:text, xsl:value-of, and xsl:message, and secondly, to allow use of complex multi-line XPath expressions where maintaining correct indentation is important for readability. The fact that XML processors are required to normalize whitespace in attribute values means that writing such expressions within a select attribute is not ideal.
The facility is only present if enabled using the [xsl:]expand-text attribute. This is partly for backwards compatibility, and partly to avoid creating difficulties when constructing content that is rich in curly brackets, for example JavaScript code or CSS style sheets.
[Definition: [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:
A Text node appearing in the stylesheet (if it has not been removed in the process of whitespace stripping: see 3.11.1 Stripping Whitespace and Commentary from the Stylesheet) is processed as follows:
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.
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.
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.
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.
An extension instruction (see 24.3 Extension Instructions) also produces a sequence of items as its result.
[Definition: [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:
For the effect of the xsl:fallback instruction, see 24.3.3 Fallback.
For the effect of the xsl:on-empty and xsl:on-non-empty instructions, see 8.5 Conditional Content Construction.
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:
The immediate result may be bound to a variable or delivered as the result of a stylesheet function. In this case the as attribute of the containing xsl:variable or xsl:function element may be used to declare its required type, and the immediate result is then converted to the required type by applying the coercion rules.
Note:
In the absence of an as attribute, the result of a function is the immediate result of the sequence constructor; but the value of a variable (for backwards compatibility reasons) is a document node whose content is formed by applying the rules in 5.7.1 Constructing Complex Content to the immediate result.
The coercion rules do not merge adjacent text nodes or insert separators between adjacent items. This means it is often inappropriate to use xsl:value-of in the body of xsl:variable or xsl:function, especially when the intent is to return an atomic result. The xsl:sequence instruction is designed for this purpose, and is usually a better choice.
The result of a function, or the value of a variable, may contain nodes (such as elements, attributes, and text nodes) that are not attached to any parent node in a result tree. The semantics of XPath expressions when applied to parentless nodes are well-defined; however, such expressions should be used with care. For example, the expression / causes a type error if the root of the tree containing the context node is not a document node.
Parentless attribute nodes require particular care because they have no namespace nodes associated with them. A parentless attribute node is not permitted to contain namespace-sensitive content (for example, a QName or an XPath expression) because there is no information enabling the prefix to be resolved to a namespace URI. Parentless attributes can be useful in an application (for example, they provide an alternative to the use of attribute sets: see 10.2 Named Attribute Sets) but they need to be handled with care.
The sequence may be returned as the result of the containing element. This happens, for example, when the element containing the sequence constructor is xsl:break, xsl:catch, xsl:fallback, xsl:for-each, xsl:for-each-group, xsl:fork, xsl:if, xsl:iterate, xsl:matching-substring, xsl:non-matching-substring, xsl:on-completion, xsl:otherwise, xsl:perform-sort, xsl:sequence, xsl:try, or xsl:when.
The sequence may be used to construct the content of a new element or document node. This happens when the sequence constructor appears as the content of a literal result element, or of one of the instructions xsl:copy, xsl:element, xsl:document, xsl:result-document, xsl:assert, or xsl:message. It also happens when the sequence constructor is contained in one of the elements xsl:variable, xsl:param, or xsl:with-param, when this instruction has no as attribute. For details, see 5.7.1 Constructing Complex Content.
The sequence may be used to construct the string value of an attribute node, text node, namespace node, comment node, or processing instruction node. This happens when the sequence constructor is contained in one of the elements xsl:attribute, xsl:text, xsl:value-of, xsl:namespace, xsl:comment, or xsl:processing-instruction. For details, see 5.7.2 Constructing Simple Content.
In a tree supplied to or constructed by an XSLT processor, the constraints relating to namespace nodes that are specified in [XDM 4.0]must be satisfied. For example:
If an element node has an expanded QName with a non-null namespace URI, then that element node must have at least one namespace node whose string value is the same as that namespace URI.
If an element node has an attribute node whose expanded QName has a non-null namespace URI, then the element must have at least one namespace node whose string value is the same as that namespace URI and whose name is non-empty.
Every element must have a namespace node whose expanded QName has local-part xml and whose string value is http://www.w3.org/XML/1998/namespace. The namespace prefix xmlmust not be associated with any other namespace URI, and the namespace URI http://www.w3.org/XML/1998/namespacemust not be associated with any other prefix.
A namespace node must not have the name xmlns or the string value http://www.w3.org/2000/xmlns/.
[Definition: [Definition: The rules for the individual XSLT instructions that construct a result tree (see 11 Creating Nodes) prescribe some of the situations in which namespace nodes are written to the tree. These rules, however, are not sufficient to ensure that the prescribed constraints are always satisfied. The XSLT processor must therefore add additional namespace nodes to satisfy these constraints. This process is referred to as namespace fixup.]
The actual namespace nodes that are added to the tree by the namespace fixup process are implementation-dependent, provided firstly, that at the end of the process the above constraints must all be satisfied, and secondly, that a namespace node must not be added to the tree unless the namespace node is necessary either to satisfy these constraints, or to enable the tree to be serialized using the original namespace prefixes from the source document or stylesheet.
Namespace fixup must not result in an element having multiple namespace nodes with the same name.
Namespace fixup may, if necessary to resolve conflicts, change the namespace prefix contained in the QName value that holds the name of an element or attribute node. This includes the option to add or remove a prefix. However, namespace fixup must not change the prefix component contained in a value of type xs:QName or xs:NOTATION that forms the typed value of an element or attribute node.
Note:
Namespace fixup is not used to create namespace declarations for xs:QName or xs:NOTATION values appearing in the content of an element or attribute.
Where values acquire such types as the result of validation, namespace fixup does not come into play, because namespace fixup happens before validation: in this situation, it is the user’s responsibility to ensure that the element being validated has the required namespace nodes to enable validation to succeed.
Where existing elements are copied along with their existing type annotations (validation="preserve") the rules require that existing namespace nodes are also copied, so that any namespace-sensitive values remain valid.
Where existing attributes are copied along with their existing type annotations, the rules of the XDM data model require that a parentless attribute node cannot contain a namespace-sensitive typed value; this means that it is an error to copy an attribute using validation="preserve" if it contains namespace-sensitive content.
Namespace fixup is applied to every element that is constructed using a literal result element, or one of the instructions xsl:element, xsl:copy, or xsl:copy-of. An implementation is not required to perform namespace fixup for elements in any source document, that is, for a document in the initial match selection, documents loaded using the document, doc or collection function, documents supplied as the value of a stylesheet parameter, or documents returned by an extension function or extension instruction.
Note:
A source document (an input document, a document returned by the document, doc or collection functions, a document returned by an extension function or extension instruction, or a document supplied as a stylesheet parameter) is required to satisfy the constraints described in [XDM 4.0], including the constraints imposed by the namespace fixup process. The effect of supplying a pseudo-document that does not meet these constraints is implementation-dependent.
In an Infoset (see [XML Information Set]) created from a document conforming to [Namespaces in XML], it will always be true that if a parent element has an in-scope namespace with a non-empty namespace prefix, then its child elements will also have an in-scope namespace with the same namespace prefix, though possibly with a different namespace URI. This constraint is removed in [Namespaces in XML 1.1]. XSLT 4.0 supports the creation of result trees that do not satisfy this constraint: the namespace fixup process does not add a namespace node to an element merely because its parent node in the result tree has such a namespace node. However, the process of constructing the children of a new element, which is described in 5.7.1 Constructing Complex Content, does cause the namespaces of a parent element to be inherited by its children unless this is prevented using [xsl:]inherit-namespaces="no" on the instruction that creates the parent element.
Note:
This has implications on serialization, defined in [Serialization 4.0]. It means that it is possible to create final result trees that cannot be faithfully serialized as XML 1.0 documents. When such a result tree is serialized as XML 1.0, namespace declarations written for the parent element will be inherited by its child elements as if the corresponding namespace nodes were present on the child element, except in the case of the default namespace, which can be undeclared using the construct xmlns="". When the same result tree is serialized as XML 1.1, however, it is possible to undeclare any namespace on the child element (for example, xmlns:foo="") to prevent this inheritance taking place.
[Definition: [Definition: Within this specification, the term URI Reference, unless otherwise stated, refers to a string in the lexical space of the xs:anyURI datatype as defined in [XML Schema Part 2].] Note that this is a wider definition than that in [RFC3986]: in particular, it is designed to accommodate Internationalized Resource Identifiers (IRIs) as described in [RFC3987], and thus allows the use of non-ASCII characters without escaping.
URI References are used in XSLT with three main roles:
As namespace URIs
As collation URIs
As identifiers for resources such as stylesheet modules; these resources are typically accessible using a protocol such as HTTP. Examples of such identifiers are the URIs used in the href attributes of xsl:import, xsl:include, xsl:result-document, and xsl:package-location.
The rules for namespace URIs are given in [Namespaces in XML] and [Namespaces in XML 1.1]. Those specifications deprecate the use of relative URI references as namespace URIs.
The rules for collation URIs are given in [Functions and Operators 4.0] section 5.3.1 Collations.
URI references used to identify external resources must conform to the same rules as the locator attribute (href) defined in section 5.4 of [XLink]. If the URI reference is relative, then it is resolved (unless otherwise specified) against the base URI of the containing element node, according to the rules of [RFC3986], after first escaping all characters that need to be escaped to make it a valid RFC3986 URI reference. (But a relative URI reference in the href attribute of xsl:result-document is resolved against the Base Output URI.)
Other URI references appearing in an XSLT stylesheet document, for example the system identifiers of external entities or the value of the xml:base attribute, must follow the rules in their respective specifications.
The base URI of an element node in the stylesheet is determined as defined in [XDM 4.0] section 7.6.2 base-uri Accessor. Some implementations may allow the output of the static analysis phase of stylesheet processing (a “compiled stylesheet”) to be evaluated in a different location from that where static analysis took place. Furthermore, stylesheet authors may in such cases wish to avoid exposing the location of resources that are private to the development environment. If the base URI of an element in the stylesheet is defined by an absolute URI appearing in an xml:base attribute within the stylesheet, this value must be used as the static base URI. In other cases where processing depends on the static base URI of a stylesheet module, implementations may use different values for the static base URI during static analysis and during dynamic evaluation (for example, an implementation may use different base URIs for resolving xsl:import module references and for resolving a relative reference used as an argument to the doc function). In such cases an implementation must document how the static base URI is computed for each situation in which it is required.
Template rules define the processing that can be applied to items that match a particular pattern.
<!-- Category: declaration -->
<xsl:template
match? = pattern
name? = eqname
priority? = decimal
mode? = tokens
as? = sequence-type〔'item()*'〕
visibility? = "public" | "private" | "final" | "abstract" >
<!-- Content: (xsl:context-item?, xsl:param*, sequence-constructor) -->
</xsl:template>
[Definition: [Definition: 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.]
[ERR XTSE0500] An xsl:template element must have either a match attribute or a name attribute, or both. An xsl:template element that has no match attribute must have no mode attribute and no priority attribute. An xsl:template element that has no name attribute must have no visibility attribute.
If an xsl:template element has a match attribute, then it is a template rule. If it has a name attribute, then it is a named template.
A template may be invoked in a number of ways, depending on whether it is a template rule, a named template, or both. The result of invoking the template is the result of evaluating the sequence constructor contained in the xsl:template element (see 5.7 Sequence Constructors).
For details of the optional xsl:context-item child element, see 10.1.4 Declaring the Context Item for a Template.
If an as attribute of the xsl:template element is present, the as attribute defines the required type of the result. The result of evaluating the sequence constructor is then converted to the required type using the coercion rules. If no as attribute is specified, the default value is item()*, which permits any value. No conversion then takes place.
[ERR XTTE0505] It is a type error if the result of evaluating the sequence constructor cannot be coerced to the required type.
If the visibility attribute is present with the value abstract then (a) the sequence constructor defining the template body must be empty: that is, the only permitted children are xsl:context-item and xsl:param, and (b) there must be no match attribute.
If the parent of the xsl:template element is an xsl:override element, then either or both of the following conditions must be true:
There is a name attribute, and the package identified by the containing xsl:use-package element contains among its components a named template whose symbolic identifier is the same as that of this named template, and which has a compatible signature.
Both the following conditions are true:
There is a match attribute.
The value of the mode attribute, or in its absence the string #default, is a whitespace-separated sequence of tokens in which each token satisfies one of the following conditions:
The token is an EQName representing the name of a mode that is exposed, with visibility equal to public, by the package identified by the containing xsl:use-package element.
The token is #default, and there is an ancestor-or-self element with a default-mode attribute whose value is an EQName representing the name of a mode that is exposed, with visibility equal to public, by the package identified by the containing xsl:use-package element.
Note:
The token #unnamed is not allowed because the unnamed mode never has public visibility. The token #all is not allowed because its intended meaning would not be obvious.
In XSLT 4.0, patterns can match any kind of item: atomic items and function items as well as nodes.
A template rule identifies the items to which it applies by means of a pattern. As well as being used in template rules, patterns are used for numbering (see 12 Numbering), for grouping (see 14 Grouping), and for declaring keys (see 20.2 Keys).
[Definition: [Definition: A pattern specifies a set of conditions on an item. An item that satisfies the conditions matches the pattern; an item that does not satisfy the conditions does not match the pattern.]
There are several kinds of pattern:
[Definition: [Definition: A predicate pattern is written as . (dot) followed by zero or more predicates in square brackets, and it matches any item for which each of the predicates evaluates to true.]
The detailed semantics are given in 6.3.2.1 Predicate Patterns. This construct can be used to match items of any kind (nodes, atomic items, and function items). For example, the pattern .[starts-with(., '$')] matches any string that starts with the character $, or a node whose atomized value starts with $. This example shows a predicate pattern with a single predicate, but the grammar allows any number of predicates (zero or more).
[Definition: [Definition: 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 that is coercible to type T for which each of the predicates evaluates to true.]
The parameter T can also be a choice item type[TERMDEF IN XP40]XP, consisting of a parenthesized sequence of item types separated by "|". For example, ~(array(*) | map(*)) matches arrays and maps, while ~(text() | comment()) matches text nodes and comment nodes.
The type pattern match="~(text() | comment())" has almost the same effect as the GNode patternmatch="text() | comment()", but the rules for calculating a default priority are different: see 6.3.3 Default Priority for Patterns.
[Definition: [Definition: An GNode pattern uses a subset of the syntax for path expressions, and is defined to match a GNode if the corresponding path expression would select the GNode.]
The syntax for GNode patterns (GNodePattern in the grammar: see 6.3.2 Syntax of Patterns) is a subset of the syntax for expressions. GNode patterns are used only for matching nodes, and the same syntax may match either an XNode or a JNode. As explained in detail below, a GNode matches a GNode pattern if the equivalent XPath expression selects the GNode when evaluated with respect to some appropriate context.
Note:
The specification uses the phrases an item matches a pattern and a pattern matches an item interchangeably. They are equivalent: an item matches a pattern if and only if the pattern matches the item.
[ERR XTSE0340] Where an attribute is defined to contain a pattern, it is a static error if the pattern does not match the production Pattern.
The complete grammar for patterns is listed in E Pattern Syntax Summary. It uses the notation defined in [XPath 4.0] section A.1.1 Notation.
The lexical rules for patterns are the same as the lexical rules for XPath expressions, as defined in [XPath 4.0] section A.3 Lexical structure. Comments are permitted between tokens, using the syntax (: ... :). All other provisions of the XPath grammar apply where relevant, for example the rules for whitespace handling and extra-grammatical constraints.
Pattern | ::= | PredicatePattern | TypePattern | GNodePattern |
PredicatePattern | ::= | "." PredicateXP* |
TypePattern | ::= | "~" ItemTypeXPPredicateXP* |
GNodePattern | ::= | UnionExprP |
Patterns fall into three groups:
A PredicatePattern matches items according to conditions that the item must satisfy: for example .[. castable as xs:integer] matches any value (it might be an atomic item, a node, or an array) that is castable as an integer.
A TypePattern matches items according to their type. For example ~xs:integer matches an atomic item that is an instance of xs:integer, while ~record(longitude, latitude) matches a map that has exactly two entries, with keys "longitude" and "latitude"
An GNodePattern matches GNodes in a GTree (for example, a tree representing the contents of an XML or JSON document), by specifying a path that can be used to locate the nodes: for example order matches an element node named order within an XTree, or a JNode with ·selector· "order" within a JTree; similarly, billing-address/city matches an element node named city whose parent node is an element named billing-address, or a JNode with ·selector· "city" whose parent is a JNode with ·selector· "billing-address".
The following sections define the rules for each of these groups.
Changes in 4.0 (next | previous)
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. [Issues 1375 1522 PR 1378 15 October 2024]
GNodePattern | ::= | UnionExprP |
UnionExprP | ::= | IntersectExceptExprP (("union" | "|") IntersectExceptExprP)* |
IntersectExceptExprP | ::= | PathExprP (("intersect" | "except") PathExprP)* |
PathExprP | ::= | RootedPath |
| /* xgs: leading-lone-slash */ | ||
RootedPath | ::= | VarRefXPPredicateXP* (("/" | "//") RelativePathExprP)? |
VarRef | ::= | "$" EQNameXP |
Predicate | ::= | "[" ExprXP "]" |
RelativePathExprP | ::= | StepExprP (("/" | "//") StepExprP)* |
StepExprP | ::= | PostfixExprP | AxisStepP |
GNode patterns are used to match GNodes: that is, XNodes or JNodes.
Many of the constructs within a GNode pattern have names that are chosen to align with the XPath 4.0 grammar. Constructs whose names are suffixed with P are restricted forms of the corresponding XPath 4.0 construct without the suffix: for example, StepExprP is a restricted form of StepExpr. Constructs labeled with the subpercript “XP” are defined in [XPath 4.0].
The syntax of a GNodePattern is a subset of the syntax of an XPath path expression, and the semantics are defined by reference to the semantics of XPath expressions.
In a FunctionCallP, the EQName used for the function name must bind to one of the functions fn:doc#1, fn:id#1, fn:id#2, fn:element-with-id#1, fn:element-with-id#2fn:key#2, fn:key#3 or fn:root#0, and the arguments (if any) must either be variable references or constants.
Note:
In the case of a call to the fn:root function, the argument list must be empty: that is, only the zero-arity form of the function is allowed.
Note:
As with XPath expressions, the pattern / union /* can be parsed in two different ways, and the chosen interpretation is to treat union as an element name rather than as an operator. The other interpretation can be achieved by writing (/) union (/*)
This section defines the formal meaning of a GNodePattern.
The process for determining whether a GNode matches a GNodePattern is as follows:
The GNodePattern is converted to an expression, called the equivalent expression. The equivalent expression to a GNodePattern is the XPath expression that takes the same lexical form as the GNodePattern as written, except that two adjustments are made to any AxisStepP that is a leading step.
[Definition: [Definition: An AxisStepP within a pattern is a leading step if (a) it is not the right-hand operand of a / or // operator, and (b) it is not contained (directly or indirectly) within a ParenthesizedPattern that is the right-hand operand of a / or // operator].
The adjustments that are made to a leading step are:
The NodeTest is adjusted to ensure that the pattern will (in most cases) match XNodes or JNodes but not both. Specifically, if the principal node kind of the axis is element, then any Selector within the NodeTest that takes the form of an EQName or Wildcard is wrapped in an ElementTest so it only selects element nodes. For example, match="*" is interpreted as match="element(*)", and match="employee" is interpreted as match="element(employee)".
Note:
The rationale for this is firstly, that it improves the clarity of the code if it is clear whether patterns are intended to match XNodes or JNodes; and secondly, that it enables pattern matching to be optimized and simplifies streamability analysis.
In addition, the axis is adjusted to allow the step to match a parentless GNode. The adjustment depends on the axis used in this step, whether it appears explicitly or implicitly (according to the rules of [XPath 4.0] section 4.7.8 Abbreviated Syntax), and is made as follows:
If the NodeTest in PS is document-node() (optionally with arguments), and if no explicit axis is specified, then the axis in step PS is taken as self rather than child.
If PS uses the child axis (explicitly or implicitly), and if the NodeTest in PS is not document-node() (optionally with arguments), then the axis in step PS is replaced by child-or-top, which is defined as follows. If the context node is a parentless element, comment, processing instruction, or text node then the child-or-top axis selects the context node; otherwise it selects the children of the context node. It is a forwards axis whose principal node kind is element.
If PS uses the attribute axis (explicitly or implicitly), then the axis in step PS is replaced by attribute-or-top, which is defined as follows. If the context node is an attribute node with no parent, then the attribute-or-top axis selects the context node; otherwise it selects the attributes of the context node. It is a forwards axis whose principal node kind is attribute.
If PS uses the namespace axis (explicitly or implicitly), then the axis in step PS is replaced by namespace-or-top, which is defined as follows. If the context node is a namespace node with no parent, then the namespace-or-top axis selects the context node; otherwise it selects the namespace nodes of the context node. It is a forwards axis whose principal node kind is namespace.
The axes child-or-top, attribute-or-top, and namespace-or-top are introduced only for definitional purposes. They cannot be used explicitly in a user-written pattern or expression.
Note:
The purpose of this adjustment is to ensure that a pattern such as person matches any element named person, even if it has no parent; and similarly, that the pattern @width matches any attribute named width, even a parentless attribute. The rule also ensures that a pattern using a NodeTest of the form document-node(...) matches a document node. The pattern node() will match any element, text node, comment, or processing instruction, whether or not it has a parent. For backwards compatibility reasons, the pattern node(), when used without an explicit axis, does not match document nodes, attribute nodes, or namespace nodes. The rules are also phrased to ensure that positional patterns of the form para[1] continue to count nodes relative to their parent, if they have one. To match any XNode at all, XSLT 4.0 allows the pattern ~node() to be used.
The adjustment is not necessary in the case of JNodes, because a JNode with ·selector· value "person" will necessarily have a parent JNode.
The meaning of the pattern is then defined in terms of the semantics of the equivalent expression, denoted below as EE.
Specifically, an item N matches a GNodePatternP if and only if the following applies, where EE is the equivalent expression to P:
N is a GNode, and the result of evaluating the expression root(.)//(EE) with a singleton focus based on N is a sequence that includes the GNode N.
If a pattern appears in an attribute of an XSLT element that is processed with XSLT 1.0 behavior (see 3.8 Backwards Compatible Processing), then the semantics of the pattern are defined on the basis that the equivalent XPath expression is evaluated with XPath 1.0 compatibility mode set to true.
The GNode patternp matches any p element. The equivalent expression, after adjustment, is child-or-top::element(p), and the pattern matches because a p element will always be present in the result of evaluating the equivalent expressionroot(.)//(child-or-top::element(p)).
Similarly, / matches a document node, and only a document node. The equivalent expression, after adjustment, is self::document-node(), and the pattern matches because the result of the equivalent expressionroot(.)//(self::document-node()) returns the root node of the tree containing the context node if and only if it is a document node.
The GNode patternnode() matches all XNodes selected by the expression root(.)//(child-or-top::node()), that is, all element, text, comment, and processing instruction nodes, whether or not they have a parent. It does not match attribute or namespace nodes because the expression does not select nodes using the attribute or namespace axes. It does not match document nodes because for backwards compatibility reasons the child-or-top axis does not match a document node.
Note:
The pattern ~node() matches all XNodes.
The GNode pattern$V matches all XNodes selected by the expression root(.)//($V), that is, all XNodes in the value of $V (which will typically be a global variable, though when the pattern is used in contexts such as the xsl:number or xsl:for-each-group instructions, it can also be a local variable).
The GNode patterndoc('product.xml')//product matches all XNodes selected by the expression root(.)//(doc('product.xml')//product), that is, all product elements in the document whose URI is product.xml.
The GNode patternroot(.)/self::E matches an E element that is the root of a tree (that is, an E element with no parent node).
Although the semantics of GNode patterns are specified formally in terms of expression evaluation, it is possible to understand pattern matching using a different model. A GNode pattern such as book/chapter/section can be examined from right to left. A node will only match this pattern if it is a section element; and then, only if its parent is a chapter; and then, only if the parent of that chapter is a book. When the pattern uses the // operator, one can still read it from right to left, but this time testing the ancestors of a node rather than its parent. For example appendix//section matches every section element that has an ancestor appendix element.
The formal definition, however, is useful for understanding the meaning of a pattern such as para[1]. This matches any node selected by the expression root(.)//(child-or-top::para[1]): that is, any para element that is the first para child of its parent, or a para element that has no parent.
The pattern jnode(code, xs:string) matches any JNode whose ·selector· is the string "code" and whose ·content· is an instance of xs:string.
The pattern jnode("date of birth", xs:date) matches any JNode whose ·selector· is the string "date of birth" and whose ·content· is an instance of xs:date.
The pattern jnode(*, array(*)) matches any JNode whose ·content· is an array, regardless of its ·selector· property.
The pattern jnode(*, record(Author, Title))[ancestor::books] matches any JNode whose ·content· is an instance of the type record(Author, Title), provided it has an ancestor with the ·selector· value "books".
The pattern jnode(*, record(Author as enum("Dickens"), Title)) matches any JNode whose ·content· is a map having an Author entry with the value "Dickens", a Title entry with any value, and optionally other entries.
The pattern jnode(*, *)[jnode-selector() = current-date()] matches any JNode whose ·selector· property is an xs:date value equal to the current date. The comparison uses the implicit timezone from the dynamic context. The rules for error handling in patterns ensure that any JNode whose ·selector· value is of a type other than xs:date does not match, because evaluation of the predicate raises an error.
Note:
The intersect and except operators do not always have the intuitive meaning. Simple cases such as * except A, or @* except (@code, @name) are unproblematic, but expressions using the descendant axis can be surprising.
Consider the pattern para except appendix//para. Perhaps unexpectedly, this matches the para element in the XML tree shown below:
<appendix>
<section>
<para/>
</section>
</appendix>This is because there is an element $S (specifically, the section element), such that the expression $S//(para except appendix//para) selects this para element.
Note:
An implementation, of course, may use any algorithm it wishes for evaluating patterns, so long as the result corresponds with the formal definition above. An implementation that followed the formal definition by evaluating the equivalent expression and then testing the membership of a specific node in the result would probably be very inefficient.
Changes in 4.0 (next | previous)
Default priorities are added for new forms of ElementTest and AttributeTest, for example element(p:*) and element(a|b). [Issue 1394 PR 1442 15 September 2024]
The default priority for a template rule using a union pattern has changed. This change may cause incompatible behavior. [Issue 1770 PR 1772 11 February 2025]
[Definition: [Definition: 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.] The default priority of a pattern is always greater than or equal to −1 (minus one), and less than 1 (plus one). The rules are as follows.
Unless otherwise specified, the default priority for a pattern is +0.5. For some simple patterns, listed below, there is a lower default priority in the range -1 (minus one) to +0.5.
It is possible for a selected item to match more than one template rule with a given modeM. When this happens, only one template rule is evaluated for the item. The template rule to be used is determined as follows:
First, only the matching template rule or rules with the highest import precedence are considered. Other matching template rules with lower precedence are eliminated from consideration.
Next, of the remaining matching rules, only those with the highest priority are considered. Other matching template rules with lower priority are eliminated from consideration.
[Definition: [Definition: 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.]
[ERR XTSE0530] The value of the priority attribute must conform to the rules for the xs:decimal type defined in [XML Schema Part 2]. Negative values are permitted.
If this leaves more than one matching template rule, then:
If the modeM has an xsl:mode declaration, and the attribute value on-multiple-match="fail" is specified in the mode declaration, a dynamic error is raised. The error is treated as occurring in the xsl:apply-templates instruction, and can be recovered by wrapping that instruction in an xsl:try instruction.
[ERR XTDE0540] It is a dynamic error if the conflict resolution algorithm for template rules leaves more than one matching template rule when the declaration of the relevant mode has an on-multiple-match attribute with the value fail.
Otherwise, of the matching template rules that remain, the one that occurs last in declaration order is used.
Note:
This was a recoverable error in XSLT 2.0, meaning that it was implementation-defined whether the error was raised, or whether the ambiguity was resolved by taking the last matching rule in declaration order. In XSLT 3.0 and 4.0 this situation is not an error unless the attribute value on-multiple-match="fail" is specified in the mode declaration. It is also possible to request warnings when this condition arises, by means of the attribute warning-on-multiple-match="yes".
[Definition: [Definition: A mode is a set of template rules; when the xsl:apply-templates instruction selects a set of items for processing, it identifies the rules to be used for processing those items by nominating a mode, explicitly or implicitly.] Modes allow a node in a source tree (for example) to be processed multiple times, each time producing a different result. They also allow different sets of template rules to be active when processing different trees, for example when processing documents loaded using the document function (see 20.1 fn:document).
Modes are identified by an expanded QName; in addition to any named modes, there is always one unnamed mode available. Whether a mode is named or unnamed, its properties may be defined in an xsl:mode declaration. If a mode name is used (for example in an xsl:template declaration or an xsl:apply-templates instruction) and no declaration of that mode appears in the stylesheet, the mode is implicitly declared with default properties.
Changes in 4.0 (next | previous)
The xsl:mode declaration acquires an attribute as="sequence-type" which declares the return type of all template rules in that mode. [Issue 750 PR 751 16 October 2023]
The xsl:mode declaration acquires an attribute copy-namespaces which determines whether or not the built-in template rule copies unused namespace bindings. [Issue 1724 PR 1929 13 April 2025]
<!-- Category: declaration -->
<xsl:mode
name? = eqname
as? = sequence-type〔'item()*'〕
streamable? = boolean〔'no'〕
use-accumulators? = tokens〔''〕
on-no-match? = "deep-copy" | "shallow-copy" | "shallow-copy-all" | "deep-skip" | "shallow-skip" | "text-only-copy" | "fail"〔'text-only-copy'〕
on-multiple-match? = "use-last" | "fail"〔'use-last'〕
warning-on-no-match? = boolean
warning-on-multiple-match? = boolean
typed? = string〔'unspecified'〕
copy-namespaces? = boolean〔'yes'〕
visibility? = "public" | "private" | "final"〔'private'〕 >
<!-- Content: (xsl:template*) -->
</xsl:mode>
[Definition: [Definition: The unnamed mode is the default mode used when no mode attribute is specified on an xsl:apply-templates instruction or xsl:template declaration, unless a different default mode has been specified using the [xsl:]default-mode attribute of a containing element.]
Every mode other than the unnamed mode is identified by an expanded QName.
A stylesheet may contain multiple xsl:mode declarations and may include or import stylesheet modules that also contain xsl:mode declarations. The name of an xsl:mode declaration is the value of its name attribute, if any.
[Definition: [Definition: All the xsl:mode declarations in a package that share the same name are grouped into a named mode definition; those that have no name are grouped into a single unnamed mode definition.]
The declared-modes attribute of the xsl:package element determines whether implicit mode declarations are allowed, as described in 3.4.5.1 Requiring Explicit Mode Declarations. If the package allows implicit mode declarations, then if a stylesheet does not contain a declaration of the unnamed mode, a declaration is implied equivalent to an xsl:mode element with no attributes. Similarly, if there is a mode that is named in an xsl:template or xsl:apply-templates element, or in the [xsl:]default-mode attribute of a containing element, and the stylesheet does not contain a declaration of that mode, then a declaration is implied comprising an xsl:mode element with a name attribute equal to that mode name, plus the attribute visibility="private".
The attributes of the xsl:mode declaration establish values for a number of properties of a mode. The allowed values and meanings of the attributes are given in the following table.
| Attribute | Values | Meaning | ||||
|---|---|---|---|---|---|---|
| name | An EQName | Specifies the name of the mode. If omitted, this xsl:mode declaration provides properties of the unnamed mode | ||||
| as | A SequenceType | Declares the type of value returned by all template rules in this mode. If any template rules in this mode declare their return type using an as attribute on xsl:template, the values must be consistent. | ||||
| streamable | yes or no (default no) | Determines whether template rules in this mode are to be capable of being processed using streaming. If the value yes is specified, then the body of any template rule that uses this mode must conform to the rules for streamable templates given in 5 Streamable TemplatesSG. | ||||
| use-accumulators | List of accumulator names, or #all (default is the empty list) | Relevant only when this mode is the initial mode of the transformation, determines which accumulators are applicable to documents containing nodes in the initial match selection. For further details see 19.2 Applicability of Accumulators. | ||||
| on-no-match | One of deep-copy, shallow-copy, deep-skip, shallow-skip, text-only-copy or fail (default text-only-copy) | Determines selection of the built-in template rules that are used to process an item when an xsl:apply-templates instruction selects an item that does not match any user-written template rule in the stylesheet. For details, see 6.8 Built-in Template Rules. | ||||
| on-multiple-match | One of fail or use-last (default use-last) | Defines the action to be taken when xsl:apply-templates is used in this mode and more than one user-written template rule is available to process an item, each having the same import precedence and priority. The value fail indicates that it is a dynamic error if more than one template rule matches an item. The value use-last indicates that the situation is not to be treated as an error (the last template in declaration order is the one that is used). | ||||
| warning-on-no-match | One of yes or no. The default is implementation-defined | Requests the processor to output (or not to output) a warning message in the case where an xsl:apply-templates instruction selects an item that matches no user-written template rule. The form and destination of such warnings is implementation-defined. The processor may ignore this attribute, for example if the environment provides no suitable means of communicating with the user. | ||||
| warning-on-multiple-match | One of yes or no. The default is implementation-defined | Requests the processor to output a warning message in the case where an xsl:apply-templates instruction selects an item that matches multiple template rules having the same import precedence and priority. The form and destination of such warnings is implementation-defined. The processor may ignore this attribute, for example if the environment provides no suitable means of communicating with the user. | ||||
| typed | One of yes, no, strict, lax, or unspecified. The default is unspecified. | See 6.7.4 Declaring the Type of Values Processed by a Mode. | ||||
| copy-namespaces | One of yes or no. The default is yes. | If on-no-match is shallow-copy, shallow-copy-all, or deep-copy, this attribute determines the effective value of the copy-namespaces attribute on the implicit xsl:copy or xsl:copy-of instruction in the built-in template rule (see 6.8 Built-in Template Rules). In other cases it is ignored, apart from checking that its value is valid. | ||||
| visibility | One of public, private, or final. The default is private. | See 3.4.4.1 Visibility of Components. If the mode is unnamed, that is, if the name attribute is absent, then the visibility attribute if present must have the value private.
| ||||
[Definition: [Definition: A streamable mode is a mode that is declared in an xsl:mode declaration with the attribute streamable="yes".]
For any named mode, the effective value of each attribute is taken from an xsl:mode declaration that has a matching name in its name attribute, and that specifies an explicit value for the required attribute. If there is no such declaration, the default value of the attribute is used. If there is more than one such declaration, the one with highest import precedence is used.
For the unnamed mode, the effective value of each attribute is taken from an xsl:mode declaration that has no name attribute, and that specifies an explicit value for the required attribute. If there is no such declaration, the default value of the attribute is used. If there is more than one such declaration, the one with highest import precedence is used.
[ERR XTSE0545] It is a static error if for any named or unnamed mode, a package explicitly specifies two conflicting values for the same attribute in different xsl:mode declarations having the same import precedence, unless there is another definition of the same attribute with higher import precedence. The attributes in question are the attributes other than name on the xsl:mode element.
[Definition: [Definition: 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.]
Each token in the mode attribute must be one of the following:
An EQName, which is expanded as described in 5.1.1 Qualified Names to define the name of the mode
The token #default, to indicate that the template rule is applicable to the default mode that would apply if the mode attribute were absent
The token #unnamed, to indicate that the template rule is applicable to the unnamed mode
The token #all, to indicate that the template rule is applicable to all modes other than enclosing modes (specifically, to the unnamed mode and to every mode that is named explicitly or implicitly in an xsl:apply-templates instruction anywhere in the stylesheet).
More specifically, when a template rule specifies mode="#all" this makes the template rule applicable to:
The unnamed mode.
Every mode, other than an enclosing mode, that is declared using an xsl:mode declaration within the containing package.
Every mode that is implicitly declared within the containing package by virtue of being referenced in an xsl:template or xsl:apply-templates element.
The value mode="#all" cannot be used on a template rule declared within an xsl:overrideor xsl:mode element.
[ERR XTSE0550] It is a static error if the list of modes is empty, if the same token is included more than once in the list, if the list contains an invalid token, or if the token #all appears together with any other value.
[ERR XTSE3440] In the case of a template rule (that is, an xsl:template element having a match attribute) appearing as a child of xsl:override, it is a static error if the list of modes in the mode attribute contains #all or #unnamed, or if it contains #default and the default mode is the unnamed mode, or if the mode attribute is omitted when the default mode is the unnamed mode.
The xsl:apply-templates element also has an optional mode attribute. The value of this attribute must be one of the following:
an EQName, which is expanded as described in 5.1.1 Qualified Names to define the name of a mode
the token #default, to indicate that the default mode from the static context of the instruction is to be used
the token #unnamed, to indicate that the unnamed mode is to be used
the token #current, to indicate that the current mode is to be used
If the attribute is omitted, the default mode from the static context of the instruction is used.
When searching for a template rule to process each item selected by the xsl:apply-templates instruction, only those template rules that are applicable to the selected mode are considered.
[Definition: [Definition: 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.] When a non-contextual function call is made, the current mode is set to the unnamed mode. While evaluating global variables and parameters, and the sequence constructor contained in xsl:key or xsl:sort, the current mode is set to the unnamed mode. No other instruction changes the current mode. The current mode while evaluating an attribute set is the same as the current mode of the caller. On completion of the xsl:apply-templates instruction, or on return from a stylesheet function call, the current mode reverts to its previous value. The current mode is used when an xsl:apply-templates instruction uses the syntax mode="#current"; it is also used by the xsl:apply-imports and xsl:next-match instructions (see 6.9 Overriding Template Rules).
Changes in 4.0 (next | previous)
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. [Issue 82 PR 542 20 June 2023]
[Definition: [Definition: A mode declared by an xsl:mode declaration that has one or more contained xsl:template declarations is referred to as an enclosing mode.]
An enclosing mode ensures that all the template rules for a mode are together in one place, which makes it easier for someone reading the stylesheet to establish what is going to happen when an xsl:apply-templates instruction in that mode is evaluated.
An enclosing mode must satisfy the following rules:
The mode must have a name.
Every contained xsl:template element must have a match attribute and no name attribute.
Every contained xsl:template element must have no mode attribute: the template is implicitly applicable only to the containing mode.
An xsl:mode declaration with one or more xsl:template children effectively has a default-mode attribute whose value is the mode’s name; it must not have a default-mode attribute with any other value.
Note:
This means that xsl:apply-templates instructions within the template rules of the enclosing mode default to using the enclosing mode.
No xsl:template that is in the same package as the containing mode, but not declared within the containing mode, may be applicable to the containing mode.
Note:
Template rules in an enclosing mode may, however, be overridden within an xsl:override element in a using package.
There must be no other xsl:mode declaration in the containing package having the same name and the same import precedence.
These rules give rise to the following error conditions:
[ERR XTSE4005] It is a static error if an xsl:mode declaration with one or more xsl:template children has no name attribute.
[ERR XTSE4010] It is a static error if an xsl:mode declaration has a child xsl:template element with a name attribute, with a mode attribute, or with no match attribute.
[ERR XTSE4015] It is a static error if an xsl:mode declaration having one or more child xsl:template elements has a default-mode attribute whose value differs from its name attribute, or if any of those child xsl:template elements has a default-mode attribute that differs from the name attribute of the xsl:mode declaration.
[ERR XTSE4020] It is a static error if a package contains both (a) an xsl:mode declaration having one or more child xsl:template elements, and (b) an xsl:template declaration that is not one of those children but that references that xsl:mode declaration in its mode attribute.
[ERR XTSE4025] It is a static error if a package contains (a) an xsl:mode declaration having one or more child xsl:template elements, and (b) a second xsl:mode declaration having the same name and the same import precedence.
The following mode might be used for formatting of numbers appearing in text:
<xsl:mode name="numbers-in-text" as="xs:string" visibility="final">
<xsl:template match="type(xs:integer)[. gt 0 and . lt 21]">
<xsl:number value="." format="w"/>
</xsl:template>
<xsl:template match="type(xs:integer)[. lt 10000]">
<xsl:number value="." format="1"/>
</xsl:template>
<xsl:template match="type(xs:integer)">
<xsl:number value="." format="1" grouping-separator="," grouping-size="3"/>
</xsl:template>
</xsl:mode>Changes in 4.0 (next | previous)
The xsl:apply-imports and xsl:next-match instructions automatically pass supplied parameters to the overridden template rule. [Issue 1861 PR 1875 25 March 2025]
<!-- Category: instruction -->
<xsl:apply-imports>
<!-- Content: xsl:with-param* -->
</xsl:apply-imports>
<!-- Category: instruction -->
<xsl:next-match>
<!-- Content: (xsl:with-param | xsl:fallback)* -->
</xsl:next-match>
A template rule that is being used to override another template rule (see 6.6 Conflict Resolution for Template Rules) can use the xsl:apply-imports or xsl:next-match instruction to invoke the overridden template rule. The xsl:apply-imports instruction only considers template rules in imported stylesheet modules; the xsl:next-match instruction considers all template rules that have not already been used. Both instructions will invoke the built-in template rule for the context item (see 6.8 Built-in Template Rules) if no other template rule is found.
[Definition: [Definition: 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.]
The current template rule is cleared (becomes absent) by any instruction that evaluates an operand with changed focus. It is therefore cleared when evaluating instructions contained within:
xsl:copy if and only if there is a select attribute
A global xsl:variable or xsl:param
xsl:template if and only if the called template specifies <xsl:context-item use="absent"/>
Note:
The current template rule is not affected by invoking named attribute sets (see 10.2 Named Attribute Sets), or named templates (see 10.1 Named Templates) unless <xsl:context-item use="absent"/> is specified. While evaluating a global variable or the default value of a stylesheet parameter (see 9.5 Global Variables and Parameters) the current template rule is absent.
These rules ensure that when xsl:apply-imports or xsl:next-match is called, the context item is the same as when the current template rule was invoked.
Both xsl:apply-imports and xsl:next-match search for a template rule that matches the context item, and that is applicable to the current mode (see 6.7 Modes). In choosing a template rule, they use the usual criteria such as the priority and import precedence of the template rules, but they consider as candidates only a subset of the template rules in the stylesheet. This subset differs between the two instructions:
The xsl:apply-imports instruction considers as candidates only those template rules contained in stylesheet levels that are descendants in the import tree of the stylesheet level that contains the current template rule.
Note:
This is not the same as saying that the search considers all template rules whose import precedence is lower than that of the current template rule.
[ERR XTSE3460] It is a static error if an xsl:apply-imports element appears in a template rule declared within an xsl:override element. (To invoke the template rule that is being overridden, xsl:next-match should therefore be used.)
The xsl:next-match instruction considers as candidates all those template rules that come after the current template rule in the ordering of template rules implied by the conflict resolution rules given in 6.6 Conflict Resolution for Template Rules.
Note:
Because a template rule declared as a child of xsl:override has higher precedence than any template rule declared in the used package (see 3.4.5 Overriding Template Rules from a Used Package), the effect of xsl:next-match within such a template rule is to consider as candidates first any other template rules for the same mode within the same xsl:use-package element (taking into account explicit and implicit priority, and document order, in the usual way), and then all template rules in the used package.
If no matching template rule is found, both xsl:apply-imports and xsl:next-match cause the built-in template rule for the mode to be invoked.
If multiple matching template rules with the same explicit or implicit priority are found, both xsl:apply-imports and xsl:next-match respect the on-multiple-match and warning-on-multiple-match attributes of the mode declaration.
Note:
If is entirely possible for xsl:apply-templates to identify a template rule unambiguously, and for xsl:apply-imports or xsl:next-match then to fail because there is no unambiguous second-choice template rule.
If a matching template rule R is found, then the result of the xsl:next-match or xsl:apply-imports instruction is the result of invoking R. The parameters that are passed to R are as follows:
All parameters explicitly set using xsl:with-param child elements (see 9.10 Setting Parameter Values).
If the effective version of the xsl:next-match or xsl:apply-imports instruction is 4.0 or greater, then all non-tunnel parameters that were supplied in the invocation of the current template rule, excluding any whose names match the names of parameters appearing in child xsl:with-param elements.
All tunnel parameters as described in 10.1.6 Tunnel Parameters.
Note:
The implicit passing of non-tunnel parameters is new in XSLT 4.0, and happens only if [xsl:]version is set to 4.0 (or greater) on the instruction, or on some ancestor element in the stylesheet. There may be cases where this change introduces a backward incompatibility: specifically, if the invoked template rule declares a default value for an optional parameter, it will now take the implicitly passed value rather than the default value. The 3.0 behavior can be therefore be retained by setting version="3.0" on the xsl:next-match or xsl:apply-imports instruction.
The template rule R is evaluated with the same focus as the xsl:next-match or xsl:apply-imports instruction. The current template rule changes to be R. The current mode does not change.
Note:
In the case where the current template rule T is declared within an xsl:override element in a using package P, while the selected rule R is declared within a different package Q, and where the current mode is MP (mode M in package P), the effect is that the current mode for evaluation of R remains MP rather than reverting to its corresponding mode MQ (mode M in package Q). If R contains an xsl:apply-templates instruction that uses mode="#current", then the set of template rules considered by this instruction will therefore include any overriding template rules declared in P as well as the original rules declared in Q.
If no matching template rule is found that satisfies these criteria, the built-in template rule for the context item is used (see 6.8 Built-in Template Rules).
[ERR XTDE0560] It is a dynamic error if xsl:apply-imports or xsl:next-match is evaluated when the current template rule is absent.
For example, suppose the stylesheet doc.xsl contains a template rule for example elements:
<xsl:template match="example"> <pre><xsl:apply-templates/></pre> </xsl:template>
Another stylesheet could import doc.xsl and modify the treatment of example elements as follows:
<xsl:import href="doc.xsl"/>
<xsl:template match="example">
<div style="border: solid red">
<xsl:apply-imports/>
</div>
</xsl:template>The combined effect would be to transform an example into an element of the form:
<div style="border: solid red"><pre>...</pre></div>
An xsl:fallback instruction appearing as a child of an xsl:next-match instruction is ignored by an XSLT 2.0, 3.0, or 4.0 processor, but can be used to define fallback behavior when the stylesheet is processed by an XSLT 1.0 processor with forwards compatible behavior.
This example shows how an input element such as:
<phrase upper-case="true" italic="true" bold="false" underscore="true">Hannover</phrase>
might be transformed into:
<italic><underscore>HANNOVER</underscore></italic>
The following template rules achieve the required effect:
<xsl:template match="phrase" priority="10">
<xsl:next-match>
<xsl:with-param name="upper-case" select="xs:boolean(@upper-case)"/>
</xsl:next-match>
</xsl:template>
<xsl:template match="phrase[xs:boolean(@italic)]" priority="8">
<italic>
<xsl:next-match/>
</italic>
</xsl:template>
<xsl:template match="phrase[xs:boolean(@bold)]" priority="6">
<bold>
<xsl:next-match/>
</bold>
</xsl:template>
<xsl:template match="phrase[xs:boolean(@underscore)]" priority="4">
<underscore>
<xsl:next-match/>
</underscore>
</xsl:template>
<xsl:template match="phrase" priority="2">
<xsl:param name="upper-case" as="xs:boolean?"/>
<xsl:if test="$upper-case" then="upper-case(.)" else="string(.)"/>
</xsl:template>Note how the $upper-case parameter is passed implicitly through the chain of template rules.
XSLT offers two constructs for processing each entry in a collection: xsl:for-each and xsl:iterate.
Both instructions can be used to process the items in a sequence, the elements in an array, or the entries in a map. Arrays and maps are processed by reducing them to a sequence of items, so in what follows, the terms item and sequence are used generically.
The main difference between the two constructs is that with xsl:for-each, the processing applied to each item in the sequence is independent of the processing applied to any other item; this means that the items may be processed in any order or in parallel, though the order of the output sequence is well defined and corresponds to the order of the input (sorted if so requested). By contrast, with xsl:iterate, the processing is explicitly sequential: while one item is being processed, values may be computed which are then available for use while the next item is being processed. This makes xsl:iterate suitable for tasks such as creating a running total over a sequence of financial transactions.
A further difference is that xsl:for-each permits sorting of the input sequence, while xsl:iterate does not.
xsl:iterate InstructionThe xsl:iterate instruction processes the items in a sequence in order; unlike xsl:for-each, the result of processing one item can affect the way that subsequent items are processed.
<!-- Category: instruction -->
<xsl:iterate
select = expression >
<!-- Content: (xsl:param*, xsl:on-completion?, sequence-constructor) -->
</xsl:iterate>
<!-- Category: instruction -->
<xsl:next-iteration>
<!-- Content: (xsl:with-param*) -->
</xsl:next-iteration>
<!-- Category: instruction -->
<xsl:break
select? = expression >
<!-- Content: sequence-constructor -->
</xsl:break>
<xsl:on-completion
select? = expression >
<!-- Content: sequence-constructor -->
</xsl:on-completion>
Consider the following JSON document representing transactions in a bank account:
[
{ "date": "2008-09-01", credit: 12.00 },
{ "date": "2008-09-01", credit: 8.00 },
{ "date": "2008-09-02", debit: 2.00 },
{ "date": "2008-09-02", credit: 12.00 }
]The following code converts this to an XML representation that includes a running balance:
<xsl:iterate select="json-doc('account.json') => array:members()">
<xsl:param name="balance" as="xs:decimal" select="0"/>
<xsl:variable name="delta" select="?value?credit otherwise -?value?debit"/>
<entry date="{ ?value?date }"
amount="{ $delta }"
balance="{ $balance + $delta }"/>
<xsl:next-iteration>
<xsl:with-param name="balance" select="$balance + $delta"/>
</xsl:next-iteration>
</xsl:iterate>Using array:members() in this way makes it possible to process any array, including one whose members are arbitrary sequences rather than single items. In this particular case, if it is known that the JSON array will not contain any null entries, or if any null entries are to be ignored, it becomes possible to simplify the code as follows:
<xsl:iterate select="json-doc('account.json')?*">
<xsl:param name="balance" as="xs:decimal" select="0"/>
<xsl:variable name="delta" select="?credit otherwise -?debit"/>
<entry date="{ ?date }"
amount="{ $delta }"
balance="{ $balance + $delta }"/>
<xsl:next-iteration>
<xsl:with-param name="balance" select="$balance + $delta"/>
</xsl:next-iteration>
</xsl:iterate>The select attribute contains an expression which is evaluated to produce a sequence, called the input sequence.
The sequence constructor contained in the xsl:iterate instruction is evaluated once for each item in the input sequence, in order, or until the loop exits by evaluating an xsl:break instruction, whichever is earlier. Within the sequence constructor that forms the body of the xsl:iterate instruction, the context item is set to each item from the value of the select expression in turn; the context position reflects the position of this item in the input sequence, and the context size is the number of items in the input sequence (which may be greater than the number of iterations, if the loop exits prematurely using xsl:break).
Note:
If xsl:iterate is used in conjunction with xsl:source-document to achieve streaming, calls on the function last will be disallowed.
The xsl:break and xsl:on-completion elements may have either a select attribute or a non-empty contained sequence constructor but not both. The effect of the element in both cases is obtained by evaluating the select expression if present or the contained sequence constructor otherwise; if neither is present, the value is the empty sequence.
Note:
The xsl:on-completion element appears before other children of xsl:iterate to ensure that variables declared in the sequence constructor are not in scope within xsl:on-completion, since such variables do not have a defined value within xsl:on-completion especially in the case where the value of the select attribute is the empty sequence.
The effect of xsl:next-iteration is to cause the iteration to continue by processing the next item in the input sequence, potentially with different values for the iteration parameters. The effect of xsl:break is to cause the iteration to finish, whether or not all the items in the input sequence have been processed. In both cases the affected iteration is the one controlled by the innermost ancestor xsl:iterate element.
The instructions xsl:next-iteration and xsl:break are allowed only as descendants of an xsl:iterate instruction, and only in a tail position within the sequence constructor forming the body of the xsl:iterate instruction.
[Definition: [Definition: An instructionJ is in a tail position within a sequence constructorSC if it satisfies one of the following conditions:
J is the last instruction in SC, ignoring any xsl:fallback instructions.
J is in a tail position within the sequence constructor that forms the body of an xsl:if instruction that is itself in a tail position within SC.
J is in a tail position within the sequence constructor that forms the body of an xsl:when or xsl:otherwise branch of an xsl:chooseor xsl:switch instruction that is itself in a tail position within SC.
J is in a tail position within the sequence constructor that forms the body of an xsl:try instruction that is itself in a tail position within SC (that is, it is immediately followed by an xsl:catch element, ignoring any xsl:fallback elements).
J is in a tail position within the sequence constructor that forms the body of an xsl:catch element within an xsl:try instruction that is itself in a tail position within SC.
]
[ERR XTSE3120] It is a static error if an xsl:break or xsl:next-iteration element appears other than in a tail position within the sequence constructor forming the body of an xsl:iterate instruction.
[ERR XTSE3125] It is a static error if the select attribute of xsl:break or xsl:on-completion is present and the instruction has children.
[ERR XTSE3130] It is a static error if the name attribute of an xsl:with-param child of an xsl:next-iteration element does not match the name attribute of an xsl:param child of the innermost containing xsl:iterate instruction.
Parameter names in xsl:with-param must be unique: [see ERR XTSE0670].
The result of the xsl:iterate instruction is the concatenation of the sequences that result from the repeated evaluation of the contained sequence constructor, followed by the sequence that results from evaluating the xsl:break or xsl:on-completion element if any.
Any xsl:param element that appears as a child of xsl:iterate declares a parameter whose value may vary from one iteration to the next. The initial value of the parameter is the value obtained according to the rules given in 9.3 Values of Variables and Parameters. The dynamic context for evaluating the initial value of an xsl:param element is the same as the dynamic context for evaluating the select expression of the xsl:iterate instruction (the context item is thus not the first item in the input sequence).
On the first iteration a parameter always takes its initial value (which may depend on variables or other aspects of the dynamic context). Subsequently:
If an xsl:next-iteration instruction is evaluated, then parameter values for processing the next item in the input sequence can be set in the xsl:with-param children of that instruction; in the absence of an xsl:with-param element that names a particular parameter, that parameter will retain its value from the previous iteration.
If an xsl:break instruction is evaluated, no further items in the input sequence are processed.
If neither an xsl:next-iteration nor an xsl:break instruction is evaluated, then the next item in the input sequence is processed using parameter values that are unchanged from the previous iteration.
The xsl:next-iteration instruction contributes nothing to the result sequence (technically, it returns the empty sequence). The instruction supplies parameter values for the next iteration, which are evaluated according to the rules given in 9.10 Setting Parameter Values; if there are no further items in the input sequence then it supplies parameter values for use while evaluating the body of the xsl:on-completion element if any.
The xsl:break instruction indicates that the iteration should terminate without processing any remaining items from the input sequence. The select expression or contained sequence constructor is evaluated using the same context item, position, and size as the xsl:break instruction itself, and the result is appended to the result of the xsl:iterate instruction as a whole.
If neither an xsl:next-iteration nor an xsl:break instruction is evaluated, the next item in the input sequence is processed with parameter values unchanged from the previous iteration; if there are no further items in the input sequence, the iteration terminates.
The optional xsl:on-completion element (which is not technically an instruction and is not technically part of the sequence constructor) is evaluated when the input sequence is exhausted. It is not evaluated if the evaluation is terminated using xsl:break. During evaluation of its select expression or sequence constructor the context item, position, and size are absent (that is, any reference to these values is an error). However, the values of the parameters to xsl:iterate are available, and take the values supplied by the xsl:next-iteration instruction evaluated while processing the last item in the sequence.
If the input sequence is empty, then the result of the xsl:iterate instruction is the result of evaluating the select attribute or sequence constructor forming the body of the xsl:on-completion element, using the initial values of the xsl:param elements. If there is no xsl:on-completion element, the result is the empty sequence.
Note:
Conceptually, xsl:iterate behaves like a tail-recursive function. The xsl:next-iteration instruction then represents the recursive call, supplying the tail of the input sequence as an implicit parameter. There are two main reasons for providing the xsl:iterate instruction. One is that many XSLT users find writing recursive functions to be a difficult skill, and this construct promises to be easier to learn. The other is that recursive function calls are difficult for an optimizer to analyze. Because xsl:iterate is more constrained than a general-purpose head-tail recursive function, it should be more amenable to optimization. In particular, when the instruction is used in conjunction with xsl:source-document, it is designed to make it easy for the implementation to use streaming techniques, processing the nodes in an input document sequentially as they are read, without building the entire document tree in memory.
Note:
One of the motivations for introducing the xsl:iterate instruction was to enable information to be retained while processing a streamed sequence of sibling nodes. For examples illustrating this, see 6 Streaming withSG.
There are several instructions in XSLT that support conditional processing: xsl:if, xsl:choose, and xsl:switch. The xsl:if instruction provides simple if-then-else conditionality; the xsl:choose instruction supports selection of one choice when there are several possibilities, and xsl:switch allows a branch to be selected based on the value of a given expression.
XSLT 3.0 also supports xsl:try and xsl:catch which define conditional processing to handle dynamic errors.
Note:
XSLT offers a number of ways of expressing conditional logic.
XSLT 1.0 offered the xsl:if instruction for cases where output was to be produced only if a condition was true, with xsl:choose available for multi-way branches where different output was to be produced under different input conditions. In addition, of course, XSLT 1.0 also offered the option of rule-based processing using templates and match patterns.
XSLT 2.0 added the XPath conditional expression providing two-way branches for use at a finer-grained level where xsl:choose could be excessively verbose: it allowed constructs such as <xsl:value-of select="if ($x) then 'red' else 'green'/> to be reduced from eight lines of code to one.
XSLT 4.0 introduces the then and else attributes for xsl:if, which are particularly useful in contexts such as the body of an xsl:function declaration where the alternative results are conveniently evaluated using XPath expressions rather than XSLT instructions: for example a recursive function might have as its body the instruction <xsl:if test="empty($seq)" then="1" else="head($seq) * my:f(tail($seq))"/>. The select attribute of xsl:when and xsl:otherwise is introduced for similar reasons: XSLT instructions are most useful when contructing node trees, whereas XPath expressions are more convenient when computing atomic items. Again, the main contribution of these enhancements is to reduce visual clutter, making the code more concise and more easily readable.
The xsl:switch instruction is introduced in XSLT 4.0 as an alternative to xsl:choose for the common use case where the conditions test for multiple different values of some common expression. By avoiding repetition of the common expression whose value is being tested, the logic becomes self-explanatory both to the human reader of the code and to an optimizing compiler, making it easier to generate efficient branching code.
The facilities described in this section are designed to make it easier to generate result trees conditionally depending on what is found in the input, without violating the rules for streamability. Although these facilities were introduced to the language specifically to make streaming easier, they are available whether or not streaming is in use, and users have often found them convenient in non-streaming applications.
The facilities are introduced first by example:
The following example generates an events element if and only if there are one or more event elements. The code could be written like this:
<xsl:if test="exists(event)">
<events>
<xsl:copy-of select="event"/>
</events>
</xsl:if>However, the above code would not be guaranteed-streamableSG, because it processes the child event elements more than once. To make it streamable, it can be rewritten as:
<xsl:where-populated>
<events>
<xsl:copy-of select="event"/>
</events>
</xsl:where-populated>The effect of the xsl:where-populated instruction, as explained later, is to avoid outputting the events element if it would have no children. A streaming implementation will typically hold the start tag of the events element in a buffer, to be sent to the output destination only if and when a child node is generated.
The following example generates an h3 element and a summary paragraph only if a list of items is non-empty. The code could be written like this:
<xsl:if test="exists(item-for-sale)">
<h1>Items for Sale</h1>
</xsl:if>
<xsl:apply-templates select="item-for-sale"/>
<xsl:if test="exists(item-for-sale)">
<p>Total value: {accumulator-before('total-value')}</p>
</xsl:if>However, the above code would not be guaranteed-streamableSG, because it processes the child item-for-sale elements more than once. To make it streamable, it can be rewritten as:
<xsl:sequence>
<xsl:on-non-empty>
<h1>Items for Sale</h1>
</xsl:on-non-empty>
<xsl:apply-templates select="item-for-sale"/>
<xsl:on-non-empty>
<p>Total value: {accumulator-before('total-value')}</p>
</xsl:on-non-empty>
</xsl:sequence>The effect of the xsl:on-non-empty instruction, as explained later, is to output the enclosed content only if the containing sequence constructor also generates “ordinary” content, that is, if there is content generated by instructions other than xsl:on-empty and xsl:on-non-empty instructions.
The following example generates a summary paragraph only if a list of items is empty. The code could be written like this:
<xsl:apply-templates select="item-for-sale"/> <xsl:if test="empty(item-for-sale)"> <p>There are no items for sale.</p> </xsl:if>
However, the above code would not be guaranteed-streamableSG, because it processes the child item-for-sale elements more than once (the fact that the list is empty is irrelevant, because streamability is determined statically). To make the code streamable, it can be rewritten as:
<xsl:sequence>
<xsl:apply-templates select="item-for-sale"/>
<xsl:on-empty>
<p>There are no items for sale.</p>
</xsl:on-empty>
</xsl:sequence>The effect of the xsl:on-empty instruction, as explained later, is to output the enclosed content only if the containing sequence constructor generates no “ordinary” content, that is, if there is no content generated by instructions other than xsl:on-empty and xsl:on-non-empty instructions.
For further examples showing the use of these instructions when streaming, see 7 Handling Empty InputSG.
xsl:on-empty instruction<!-- Category: instruction -->
<xsl:on-empty
select? = expression >
<!-- Content: sequence-constructor -->
</xsl:on-empty>
The xsl:on-empty instruction has the same content model as xsl:sequence, and when it is evaluated, the same rules apply. In particular, the select attribute and the contained sequence constructor are mutually exclusive [see ERR XTSE3185].
When an xsl:on-empty instruction appears in a sequence constructor, then:
It must be the only xsl:on-empty instruction in the sequence constructor, and
It must not be followed in the sequence constructor by any other instruction, other than xsl:fallback, or by a significant text node (that is, a text node that has not been discarded under the provisions of 3.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: [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 the 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 the empty sequence, or a sequence consisting entirely of vacuous items.
If an xsl:on-empty instruction is triggered, then the result of the containing sequence constructor is the result of the xsl:on-empty instruction.
Note:
This means that the (vacuous) results produced by other instructions in the sequence constructor are discarded. This is relevant mainly when the result of the sequence constructor is used for something other than constructing a node: for example if it forms the result of a function, or the value of a variable, and the function or variable specifies a required type.
When streaming, it may be necessary to buffer vacuous items in the result sequence until it is known whether the result will contain items that are non-vacuous. In many common situations, however — in particular, when the sequence constructor is being used to create the content of a node — vacuous items can be discarded immediately because they do not affect the content of the node being constructed.
Note:
In nearly all cases, the rules for xsl:on-empty are aligned with the rules for constructing complex content. If the sequence constructor within a literal result element or an xsl:element instruction includes an xsl:on-empty instruction, then the content of the element will be the value delivered by the xsl:on-empty instruction if and only if the content would otherwise be empty.
There is one minor exception to this rule: if the sequence constructor delivers multiple zero-length strings, then in the absence of the xsl:on-empty instruction the new element would contain whitespace, made up of the separators between these zero-length strings; but xsl:on-empty takes no account of these separators.
Note:
Attribute and namespace nodes created by the sequence constructor are significant; the xsl:on-empty instruction will not be triggered if such nodes are present. If this is not the desired effect, it is possible to partition the sequence constructor to change the scope of xsl:on-empty, for example:
<ol>
<xsl:attribute name="class" select="numbered-list"/>
<xsl:sequence>
<xsl:value-of select="xyz"/>
<xsl:on-empty select="'The list is empty'"/>
</xsl:sequence>
</ol>Note:
Where the sequence constructor is a child of an instruction with an [xsl:]use-attribute-sets attribute, any attribute nodes created by expanding the referenced attribute set(s) are not part of the result of the sequence constructor and therefore play no role in determining whether an xsl:on-empty or xsl:on-non-empty instruction is triggered. Equally, when the sequence constructor is a child of a literal result element, attribute nodes generated by expanding the attributes of the literal result element are not taken into account.
Note:
If xsl:on-empty is the only instruction in a sequence constructor then it is always evaluated.
If xsl:on-empty and xsl:on-non-empty appear in the same sequence constructor, then the rules ensure that only one of them will be evaluated.
[Definition: [Definition: The two elements xsl:variable and xsl:param are referred to as variable-binding elements.]
[Definition: [Definition: The xsl:variable element declares a variable, which may be a global variable or a local variable.]
[Definition: [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: [Definition: A variable is a binding between a name and a value. The value of a variable is any sequence (of nodes, atomic items, and/or function items), as defined in [XDM 4.0].]
<!-- Category: declaration -->
<!-- Category: instruction -->
<xsl:variable
name = eqname
select? = expression
as? = sequence-type
static? = boolean〔'no'〕
visibility? = "public" | "private" | "final" | "abstract" >
<!-- Content: sequence-constructor -->
</xsl:variable>
The xsl:variable element has a requiredname attribute, which specifies the name of the variable. The value of the name attribute is an EQName, which is expanded as described in 5.1.1 Qualified Names.
The xsl:variable element has an optional as attribute, which specifies the required type of the variable. The value of the as attribute is a SequenceType.
[Definition: [Definition: 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.] If the xsl:variable element has a select attribute, then the sequence constructor must be empty.
If the as attribute is specified, then the supplied value of the variable is converted to the required type, using the coercion rules.
[ERR XTTE0570] It is a type error if the supplied value of a variable cannot be converted to the required type.
If the as attribute is omitted, the supplied value of the variable is used directly, and no conversion takes place.
For the effect of the static attribute, see 9.6 Static Variables and Parameters.
The visibility attribute must not be specified for a local variable: that is, it is allowed only when the parent element is xsl:stylesheet, xsl:transform, xsl:package or xsl:override.
If the visibility attribute is present with the value abstract then the select attribute must be absent and the contained sequence constructormust be empty. In this situation there is no supplied value, and therefore the constraint that the supplied value is consistent with the required type does not apply.
<!-- Category: declaration -->
<xsl:param
name = eqname
select? = expression
as? = sequence-type
required? = boolean
tunnel? = boolean〔'no'〕
static? = boolean〔'no'〕 >
<!-- Content: sequence-constructor -->
</xsl:param>
The xsl:param element may be used:
As a child of xsl:stylesheet or xsl:package, to define a parameter to the transformation. Stylesheet parameters are set by the calling application: see 2.3.2 Priming a Stylesheet.
As a child of xsl:template to define a parameter to a template, which may be supplied when the template is invoked using xsl:call-template, xsl:apply-templates, xsl:apply-imports or xsl:next-match. Template parameters are set by means of an xsl:with-param child element of the invoking instruction, as described in 9.10 Setting Parameter Values.
As a child of xsl:function to define a parameter to a stylesheet function, which may be supplied when the function is called from an XPath expression. Function parameters are set either positionally or by keyword by means of the argument list in an XPath function call.
As a child of xsl:iterate to define a parameter that can vary from one iteration to the next. Iteration parameters always take their default values for the first iteration, and in subsequent iterations are set using an xsl:with-param child of the xsl:next-iteration instruction.
The attributes applicable to xsl:param depend on its parent element in the stylesheet, as defined by the following table:
| Parent Element | name | select | as | required | tunnel | static |
|---|---|---|---|---|---|---|
xsl:package | mandatory | optional | optional | yes|no | no | yes|no |
xsl:stylesheet | mandatory | optional | optional | yes|no | no | yes|no |
xsl:template | mandatory | optional | optional | yes|no | yes|no | no |
xsl:function | mandatory | optional | optional | yes|no | no | no |
xsl:iterate | mandatory | mandatory | optional | no | no | no |
In the table, the entries for the name, select, and as attributes indicate whether the attribute must appear, is optional, or must be absent; the entries for the required, tunnel, and static attributes indicate the values that are permitted if the attribute is present, with the default value shown in bold. (The value yes can also be written true or 1, while no can also be written false or 0.)
The name attribute is mandatory: it specifies the name of the parameter. The value of the name attribute is an EQName, which is expanded as described in 5.1.1 Qualified Names.
[ERR XTSE0580] It is a static error if the values of the name attribute of two sibling xsl:param elements represent the same expanded QName.
If the xsl:param element has a select attribute, then the sequence constructor must be empty.
The static attribute can take the value yes only on stylesheet parameters, and is explained in 9.5 Global Variables and Parameters.
Note:
Local variables may shadow template parameters and function parameters: see 9.9 Scope of Variables.
The optional tunnel attribute may be used to indicate that a parameter is a tunnel parameter. The default is no; the value yes may be specified only for template parameters. Tunnel parameters are described in 10.1.6 Tunnel Parameters
Changes in 4.0 (next | previous)
Parameters on functions declared using xsl:function can now be defined as optional, with a default value supplied. [Issue 155 PR 159 30 September 2022]
The optional required attribute of xsl:param may be used to indicate whether a stylesheet parameter, template parameter, or function parameter is mandatory or optional. The only value permitted for a parameter to xsl:iterate is no (these are always initialized to a default value).
The default value for a function parameter is required="yes"; in all other cases it is required="no".
[Definition: [Definition: 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.] If a parameter is explicitly mandatory, then the xsl:param element must be empty and must not have a select attribute.
The static context for evaluating the default value depends on where the relevant expression appears in the stylesheet, in the usual way. Note however that for xsl:param elements defining function parameters, the static context does not include variables bound in preceding-sibling xsl:param elements.
The dynamic context is different for different kinds of parameter:
For stylesheet parameters, the context is the same as the context for evaluating global variables.
For template parameters, the context is that of the called template. This means that the evaluation of the default has access to the other parameters supplied in the call, provided they are declared earlier. It also means, for example, that if the evaluation of the default value invokes xsl:next-match, the current template rule is the called template rather than the calling template.
For function parameters, the dynamic context for evaluating defaults is the dynamic context of the caller, except that no local variables are in scope. This means that it is possible to declare a parameter with <xsl:param name="dot" required="no" select="."/> to take its default value from the context item of the caller.
If a parameter is not explicitly mandatory, then it may have a default value. The default value is obtained by evaluating the expression given in the select attribute or the contained sequence constructor, as described in 9.3 Values of Variables and Parameters.
Note:
This specification does not dictate whether and when the default value of a parameter is evaluated. For example, if the default is specified as <xsl:param name="p"><foo/></xsl:param>, then it is not specified whether a distinct foo element node will be created on each invocation of the template, or whether the same foo element node will be used for each invocation. However, it is permissible for the default value to depend on the values of other parameters, or on the evaluation context, in which case the default must effectively be evaluated on each invocation.
[Definition: [Definition: An explicit default for a parameter is indicated by the presence of either a select attribute or a non-empty sequence constructor.]
[Definition: [Definition: 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.]
[Definition: [Definition: 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.]
Note:
The effect of these rules is that specifying <xsl:param name="p" as="xs:date" select="2"/> is an error, but if the default value of the parameter is never used, then the processor has discretion whether or not to raise the error. By contrast, <xsl:param name="p" as="xs:date"/> is treated as if required="yes" had been specified: the empty sequence is not a valid instance of xs:date, so in effect there is no default value and the parameter is therefore treated as being mandatory.
Various errors can arise with regard to mandatory parameters when no value is supplied. In the rules below, non-tunnel means: not having a tunnel attribute with the value yes.
[ERR XTSE3520] It is a static error if a parameter to xsl:iterate is implicitly mandatory.
[ERR XTSE0690] It is a static error if a package contains both (a) a named template named T that is not overridden by another named template of higher import precedence and that has an explicitly mandatory non-tunnel parameter named P, and (b) an xsl:call-template instruction whose name attribute equals T and that has no non-tunnel xsl:with-param child element whose name attribute equals P. (All names are compared as QNames.)
[ERR XTDE0700] It is a dynamic error if a template that has an explicitly mandatory or implicitly mandatory parameter is invoked without supplying a value for that parameter.
This includes the following cases:
The template is invoked using xsl:apply-templates, xsl:apply-imports, or xsl:next-match and there is no xsl:with-param child whose name and tunnel attributes match the corresponding attributes of the mandatory parameter.
The mandatory parameter is a tunnel parameter, and the template is invoked using xsl:call-template, and there is no xsl:with-param child whose name and tunnel attributes match the corresponding attributes of the mandatory parameter.
The template is invoked as the entry point to the transformation, either by invoking an initial mode (2.3.3 Apply-Templates Invocation) or by invoking an initial template (2.3.4 Call-Template Invocation) and no value is supplied for the mandatory parameter by the calling application.
A document node is created implicitly when evaluating an xsl:variable, xsl:param, or xsl:with-param element that has non-empty content and that has no as attribute, unless the children of this element include a disqualifying element. The value of the variable is this newly constructed document node. The content of the document node is formed from the result of evaluating the sequence constructor contained within the variable-binding element, as described in 5.7.1 Constructing Complex Content.
[Definition: [Definition: 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.]
Note:
Most of the disqualifying elements return maps or arrays, and wrapping a map or array in a document node makes no sense. For xsl:select, the justification is that this instruction should be as closely as possible an equivalent to the select attribute on the containing xsl:variable or xsl:param element.
Note:
The construct:
<xsl:variable name="tree"> <a/> </xsl:variable>
can be regarded as a shorthand for:
<xsl:variable name="tree" as="document-node()">
<xsl:document validation="preserve">
<a/>
</xsl:document>
</xsl:variable>The base URI of the document node is taken from the base URI of the variable binding element in the stylesheet. (See [XDM 4.0] section 7.6.2 base-uri Accessor)
No document-level validation takes place (which means, for example, that there is no checking that ID values are unique). However, type annotations on nodes within the new tree are copied unchanged.
Note:
The base URI of other nodes in the tree is determined by the rules for constructing complex content (see 5.7.1 Constructing Complex Content). The effect of these rules is that the base URI of a node in the temporary tree is determined as if all the nodes in the temporary tree came from a single entity whose URI was the base URI of the variable-binding element. Thus, the base URI of the document node will be equal to the base URI of the variable-binding element, while an xml:base attribute within the temporary tree will change the base URI for its parent element and that element’s descendants, just as it would within a document constructed by parsing.
The document-uri and unparsed-entities properties of the new document node are set to empty.
A temporary tree is available for processing in exactly the same way as any source document. For example, its nodes are accessible using path expressions, and they can be processed using instructions such as xsl:apply-templates and xsl:for-each. Also, the key and id functions can be used to find nodes within a temporary tree, by supplying the document node at the root of the tree as an argument to the function or by making it the context node.
The following stylesheet uses a temporary tree as the intermediate result of a two-phase transformation, using different modes for the two phases (see 6.7 Modes). Typically, the template rules in module phase1.xsl will be declared with mode="phase1", while those in module phase2.xsl will be declared with mode="phase2":
<xsl:stylesheet version="3.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> <xsl:import href="phase1.xsl"/> <xsl:import href="phase2.xsl"/> <xsl:variable name="intermediate"> <xsl:apply-templates select="/" mode="phase1"/> </xsl:variable> <xsl:template match="/"> <xsl:apply-templates select="$intermediate" mode="phase2"/> </xsl:template> </xsl:stylesheet>
Note:
The algorithm for matching nodes against template rules is exactly the same regardless which tree the nodes come from. If different template rules are to be used when processing different trees, then unless nodes from different trees can be distinguished by means of patterns, it is a good idea to use modes to ensure that each tree is processed using the appropriate set of template rules.
Changes in 4.0 (next | previous)
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. [Issue 1540 PR 1544 12 November 2024]
Both xsl:variable and xsl:param are allowed as declaration elements: that is, they may appear as children of the xsl:package or xsl:stylesheet element.
[Definition: [Definition: 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.]
[Definition: [Definition: 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.] As described in 9.2 Parameters, a stylesheet parameter may be declared as being mandatory, or may have a default value specified for use when no value is supplied by the caller. The mechanism by which the caller supplies a value for a stylesheet parameter is implementation-defined. An XSLT processormust provide such a mechanism.
It is an error if no value is supplied for a mandatory stylesheet parameter [see ERR XTDE0050].
If a stylesheet contains more than one binding for a global variable of a particular name, then the binding with the highest import precedence is used.
[ERR XTSE0630] It is a static error if a package contains more than one non-hidden binding of a global variable with the same name and same import precedence, unless it also contains another binding with the same name and higher import precedence.
For a global variable or the default value of a stylesheet parameter, the expression or sequence constructor specifying the variable value is evaluated with a singleton focus as follows:
If the declaration appears within the top-level package (including within an xsl:override element in the top-level package), then the focus is based on the global context item if supplied, or absent otherwise.
If the declaration appears within a library package, then the focus is absent.
An XPath error will be raised if the evaluation of a global variable or parameter references the context item, context position, or context size when the focus is absent. The values of other components of the dynamic context are the initial values as defined in 5.3.3 Initializing the Dynamic Context and 5.3.4 Additional Dynamic Context Components used by XSLT.
The visibility of a stylesheet parameter is always (implicitly) private if the parameter is static, or public if the parameter is non-static.
Note:
This rule has the effect that after combining all the packages making up a stylesheet, the non-static stylesheet parameters whose values are required necessarily have distinct names, which simplifies the design of APIs.
For the effect of the static attribute, see 9.6 Static Variables and Parameters.
The visibility attribute must not be specified for a local variable: that is, it is allowed only when the parent element is xsl:package, xsl:stylesheet, xsl:transform, or xsl:override.
If the visibility attribute is present with the value abstract then the select attribute must be absent and the contained sequence constructormust be empty. In this situation there is no supplied value, and therefore the constraint that the supplied value is consistent with the required type does not apply.
The following example declares a global parameter para-font-size, which is referenced in an attribute value template.
<xsl:param name="para-font-size" as="xs:string">12pt</xsl:param>
<xsl:template match="para">
<fo:block font-size="{ $para-font-size }">
<xsl:apply-templates/>
</fo:block>
</xsl:template>The implementation must provide a mechanism allowing the user to supply a value for the parameter para-font-size when invoking the stylesheet; the value 12pt acts as a default.
Note:
In XSLT 4.0, a global variable is in scope within its own definition. Trivial self-references such as <xsl:variable name="x" select="$x+1"/> are prevented by the general rules on circularities: see 9.11 Circular Definitions. However, there are other cases where self-reference makes perfect sense. The obvious example is where the value of the variable is a recursive inline function, such as:
<xsl:variable name="max-depth"
select="fn($node as node()) {
if (has-children($node))
then 1 + max($node/* ! $max-depth(.))
else 0}"/>Static variables and parameters are global variables and can be used in the same way as other global variables. In addition, they can be used in [xsl:]use-when expressions and in shadow attributes.
[Definition: [Definition: 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.]
[Definition: [Definition: A static variable declared using an xsl:param element is referred to as a static parameter.]
The static attribute must not take the value yes on an xsl:variable or xsl:param element unless it is a top-level element.
When the static attribute is present with the value yes, the visibility attribute must not have a value other than private.
Note:
This rule prevents static variables being overridden in another package. Since the values of such variables may be used at compile time (for example, during processing of [xsl:]use-when expressions), the rule is necessary to ensure that packages can be independently compiled.
It is possible to make the value of a static variable or parameter available in a using package by binding a non-static public variable to its value, for example:
<xsl:param name="DEBUG" static="yes" select="true()"/>
<xsl:variable name="tracing" static="no" visibility="public" select="$DEBUG"/>When the attribute static="yes" is specified, the xsl:variable or xsl:param element must have empty content. In the case of xsl:variable the select attribute must be present to define the value of the variable [see ERR XTSE0010].
If the select attribute is present, then it is evaluated using the rules for static expressions.
The rules for the scope of static variables, and the handling of duplicate declarations, are similar to the rules for non-static variables, but with additional constraints designed to disallow forwards references. The reason for disallowing forwards references is to ensure that use-when attributes can always be evaluated as early as possible, and in particular to ensure that the value of a use-when attribute never has circular dependencies. The additional constraints are as follows:
The static context for evaluation of a static expression only contains those 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.
If two static variables declared within the same package have the same name, the one that has higher import precedence is used (it is a consequence of rules defined elsewhere that there cannot be more than one declaration with highest import precedence). However, if the declaration with higher import precedence occurs after the one with lower import precedence in stylesheet tree order, then the two declarations must be consistent. For this purpose two declarations are consistent if (a) they are either both xsl:variable elements, or both xsl:param elements, and (b) if the variables are initialized (that is, if the elements are xsl:variable elements, or if they are xsl:param elements and no value for the parameter is externally supplied) then the values of both variables must be identicalFO, and must not contain function items.
Note:
This rule ensures that when a static variable reference is encountered, the value of the most recently declared static variable with that name can be used, knowing that this value cannot be overridden by a subsequent declaration having higher import precedence.
[ERR XTSE3450] It is a static error if a variable declared with static="yes" is inconsistent with another static variable of the same name that is declared earlier in stylesheet tree order and that has lower import precedence.
Note:
It is not an error to have two global variables or parameters with the same name, one static and one non-static, provided that they have different import precedence. If the static variable has higher precedence, then it will be used as the selected binding for all global variable references with this name, whether or not they appear in static expressions. If the non-static variable has higher precedence, then the static variable will be used as the selected binding for variable references appearing in static expressions, while the non-static variable will be used for variable references in non-static expressions. The two variables may have different values. In the case of global parameters, however, a transformation API may restrict them to have the same value.
If the two variable declarations have the same import precedence, and there is no declaration with higher import precedence, then error condition [see ERR XTSE0630] applies.
[Definition: [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:
In [xsl:]use-when attributes (see 3.11.3 Conditional Element Inclusion);
In the select attribute of static variable declarations (xsl:variable or xsl:param with static="yes");
In shadow attributes (see 3.11.4 Shadow Attributes).
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:
| Component | Value |
|---|---|
| XPath 1.0 compatibility mode | false |
| Statically known namespaces | the applicable static namespaces for the containing element in the stylesheet |
| Default namespace for elements and types | determined by the xpath-default-namespace attribute if present (see 5.1.2 Unprefixed Lexical QNames in Expressions and Patterns); otherwise absent |
| Default function namespace | the standard function namespace. |
| In-scope schema types | The type definitions that would be available in the absence of any xsl:import-schema declaration |
| In-scope element declarations | None |
| In-scope attribute declarations | None |
| In-scope variables | The 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 type | Absent |
| In-scope named item types | None |
| Statically known function definitions | The functions defined in [Functions and Operators 4.0] in the fnmath, map, and array namespaces, together with:
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 collations | Implementation-defined |
| Default collation | The Unicode Codepoint Collation |
| Static Base URI | The base URI of the containing element in the stylesheet document (see [XDM 4.0] section 7.6.2 base-uri Accessor) |
| Statically known documents | Implementation-defined |
| Statically known collections | Implementation-defined |
| Statically known default collection type | Implementation-defined |
| Statically known decimal formats | A single unnamed decimal format equivalent to the decimal format that is created by an xsl:decimal-format declaration with no attributes. |
| Component | Value |
|---|---|
| Context item, position, and size | Absent |
| Variable values | A 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 definitions | The same as the statically known function definitions |
| Current dateTime | Implementation-defined |
| Implicit timezone | Implementation-defined |
| Executable Base URI | The same as the Static Base URI |
| Default collation | The Unicode Codepoint Collation |
| Default language | Implementation-defined |
| Default calendar | Implementation-defined |
| Default place | Implementation-defined |
| Available documents | Implementation-defined |
| Available text resources | Implementation-defined |
| Available collections | Implementation-defined |
| Default collection | Implementation-defined |
| Available URI collections | Implementation-defined |
| Default URI collection | Implementation-defined |
| Environment variables | Implementation-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.
[Definition: [Definition: As well as being allowed as a declaration, the xsl:variable element is also allowed in sequence constructors. Such a variable is known as a local variable.]
An xsl:param element may also be used to create a variable binding with local scope:
[Definition: [Definition: An xsl:param element may appear as a child of an xsl:template element, before any non-xsl:param children of that element. Such a parameter is known as a template parameter. A template parameter is a local variable with the additional property that its value can be set when the template is called, using any of the instructions xsl:call-template, xsl:apply-templates, xsl:apply-imports, or xsl:next-match.]
[Definition: [Definition: An xsl:param element may appear as a child of an xsl:function element, before any non-xsl:param children of that element. Such a parameter is known as a function parameter. A function parameter is a local variable with the additional property that its value can be set when the function is called, using a function call in an XPath expression.]
An xsl:param element may appear as a child of an xsl:iterate instruction, before any non-xsl:param children of that element. This defines a parameter whose value may be initialized on entry to the iteration, and which may be varied each time round the iteration by use of an xsl:with-param element in the xsl:next-iteration instruction.
The result of evaluating a local xsl:variable or xsl:param element (that is, the contribution it makes to the result of the sequence constructor it is part of) is the empty sequence.
For any variable-binding element, there is a region (more specifically, a set of nodes) of the stylesheet within which the binding is visible. The set of variable bindings in scope for an XPath expression consists of those bindings that are visible at the point in the stylesheet where the expression occurs.
A global variable binding element is visible everywhere in the containing package (including other stylesheet modules) except within the xsl:variable or xsl:param element itself and any region where it is shadowed by another variable binding. (For rules regarding the visibility of the variable in other packages, see 3.4.4.1 Visibility of Components.)
A local variable binding element is visible for all following siblings and their descendants, with the following exceptions:
It is not visible in any region where it is shadowed by another variable binding.
It is not visible within the subtree rooted at an xsl:fallback instruction that is a sibling of the variable binding element.
It is not visible within the subtree rooted at an xsl:catch instruction that is a sibling of the variable binding element.
Within an xsl:function declaration, a function parameter is not visible within sibling xsl:param elements.
The binding is not visible for the xsl:variable or xsl:param element itself.
If a binding is visible for an element then it is visible for every attribute of that element and for every text node child of that element.
An xsl:param element specifying tunnel="yes" is also visible in the test attribute of the containing xsl:template element.
[Definition: [Definition: 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.]
The following is allowed:
<xsl:param name="x" select="1"/> <xsl:template name="foo"> <xsl:variable name="x" select="2"/> </xsl:template>
It is also not an error if a binding established by a local xsl:variable element shadows a binding established by another local xsl:variable or xsl:param.
The following is not an error, but the effect is probably not what was intended. The template outputs <x value="1"/>, because the declaration of the inner variable named $x has no effect on the value of the outer variable named $x.
<xsl:variable name="x" select="1"/>
<xsl:template name="foo">
<xsl:for-each select="1 to 5">
<xsl:variable name="x" select="$x+1"/>
</xsl:for-each>
<x value="{ $x }"/>
</xsl:template>Note:
Once a variable has been given a value, the value cannot subsequently be changed. XSLT does not provide an equivalent to the assignment operator available in many procedural programming languages.
This is because an assignment operator would make it harder to create an implementation that processes a document other than in a batch-like way, starting at the beginning and continuing through to the end.
As well as global variables and local variables, an XPath expression may also declare range variables for use locally within an expression. For details, see [XPath 4.0].
Where a reference to a variable occurs in an XPath expression, it is resolved first by reference to range variables that are in scope, then by reference to local variables and parameters, and finally by reference to global variables and parameters. A range variable may shadow a local variable or a global variable. XPath also allows a range variable to shadow another range variable.
[Definition: [Definition: A circularity is said to exist if a construct such as a global variable, an attribute set, or a key, cannot be evaluated without reference to its own value. For example, if the expression or sequence constructor specifying the value of a global variableX references a global variable Y, then the value for Ymust be computed before the value of X. A circularity exists if it is impossible to do this for all global variable definitions.]
The following two declarations create a circularity:
<xsl:variable name="x" select="$y+1"/> <xsl:variable name="y" select="$x+1"/>
The definition of a global variable can be circular even if no other variable is involved. For example the following two declarations (see 10.3 Stylesheet Functions for an explanation of the xsl:function element) also create a circularity:
<xsl:variable name="x" select="my:f()"/> <xsl:function name="my:f"> <xsl:sequence select="$x"/> </xsl:function>
The definition of a variable is also circular if the evaluation of the variable invokes an xsl:apply-templates instruction and the variable is referenced in the pattern used in the match attribute of any template rule in the stylesheet. For example the following definition is circular:
<xsl:variable name="x"> <xsl:apply-templates select="//param[1]"/> </xsl:variable> <xsl:template match="param[$x]">1</xsl:template>
Similarly, a variable definition is circular if it causes a call on the key function, and the definition of that key refers to that variable in its match or use attributes. So the following definition is circular:
<xsl:variable name="x" select="my:f(10, /)"/>
<xsl:function name="my:f">
<xsl:param name="arg1"/>
<xsl:param name="top"/>
<xsl:sequence select="key('k', $arg1, $top)"/>
</xsl:function>
<xsl:key name="k" match="item[@code=$x]" use="@desc"/>
An attribute set is circular if its use-attribute-sets attribute references itself, directly or indirectly. So the following definitions establish a circularity:
<xsl:attribute-set name="a" use-attribute-sets="b"/> <xsl:attribute-set name="b" use-attribute-sets="a"/>
Because attribute sets can invoke functions, global variables, or templates, and can also include instructions such as literal result elements that themselves invoke attribute sets, examples of circularity involving attribute sets can be more complex than this simple example illustrates. It is also possible to construct examples in which self-reference among attribute sets could be regarded as (terminating or non-terminating) recursion. However, because such self-references have no practical utility, any requirement to evaluate an attribute set in the course of its own evaluation is considered an error.
Note:
In previous versions of this specification, self-reference among attribute sets was defined as a static error. In XSLT 3.0 it is not always detectable statically, because attribute sets can bind to each other across package boundaries. Nevertheless, in cases where a processor can detect a static circularity, it can raise this error during the analysis phase, under the general provision for raising dynamic errors during stylesheet analysis if execution can never succeed.
[ERR XTDE0640] In general, a circularity in a stylesheet is a dynamic error. However, as with all other dynamic errors, an implementation will raise the error only if it actually executes the instructions and expressions that participate in the circularity. Because different implementations may optimize the execution of a stylesheet in different ways, it is implementation-dependent whether a particular circularity will actually be raised.
For example, in the following declarations, the function declares a local variable $b, but it returns a result that does not require the variable to be evaluated. It is implementation-dependent whether the value is actually evaluated, and it is therefore implementation-dependent whether the circularity is raised as an error:
<xsl:variable name="x" select="my:f(1)"/> <xsl:function name="my:f"> <xsl:param name="a"/> <xsl:variable name="b" select="$x"/> <xsl:sequence select="$a + 2"/> </xsl:function>
Although a circularity is detected as a dynamic error, there is no unique instruction whose evaluation triggers the error condition, and the result of any attempt to catch the error using an xsl:try instruction is therefore implementation-dependent.
Circularities usually involve global variables or parameters, but they can also exist between key definitions (see 20.2 Keys), between named attribute sets (see 10.2 Named Attribute Sets), or between any combination of these constructs. For example, a circularity exists if a key definition invokes a function that references an attribute set that calls the key function, supplying the name of the original key definition as an argument.
Circularity is not the same as recursion. Stylesheet functions (see 10.3 Stylesheet Functions) and named templates (see 10.1 Named Templates) may call other functions and named templates without restriction. With careless coding, recursion may be non-terminating. Implementations are required to raise circularity as a dynamic error, but they are not required to detect non-terminating recursion.
Recursive functions can also be defined using global variable declarations. For example, the variable declaration <xsl:variable name="f" select="fn($n){if ($n=0) then 0 else $f($n - 1)}"/> does not constitute a circularity, because the variable can be evaluated (delivering a function) without knowing its own value.
The requirement to report a circularity as a dynamic error overrides the rule that dynamic errors in evaluating patterns are normally masked (by treating the pattern as not matching).
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: [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.]
[Definition: [Definition: Templates can be invoked by name. An xsl:template element with a name attribute defines a named template.] The value of the name attribute is an EQName, which is expanded as described in 5.1.1 Qualified Names. If an xsl:template element has a name attribute, it may, but need not, also have a match attribute.
The match, mode and priority attributes on an xsl:template element have no effect when the template is invoked by an xsl:call-template instruction. Similarly, the name and visibility attributes on an xsl:template element have no effect when the template is invoked by an xsl:apply-templates instruction.
[ERR XTSE0660] It is a static error if a package contains more than one non-hidden template with the same name and the same import precedence, unless it also contains a template with the same name and higher import precedence.
The template name xsl:initial-template is specially recognized in that it provides a default entry point for stylesheet execution (see 2.3 Initiating a Transformation.)
[Definition: [Definition: 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.] Tunnel parameters thus allow values to be set that are accessible during an entire phase of stylesheet processing, without the need for each template that is used during that phase to be aware of the parameter.
Note:
Tunnel parameters are conceptually similar to the dynamically scoped variables found in some functional programming languages (for example, early versions of LISP), where evaluating a variable reference involves searching down the dynamic call stack for a matching variable name. There are two main use cases for the feature:
They provide a way to supply context information that might be needed by many templates (for example, the fact that the output is to be localized for a particular language), but which cannot be placed in a global variable because it might vary from one phase of processing to another. Passing such information using conventional parameters is error-prone, because a single xsl:apply-templates or xsl:call-template instruction that neglects to pass the information on will lead to failures that are difficult to diagnose.
This style of processing is even more useful when handling JSON input, because with maps and arrays, there is no ancestor axis to examine properties of nodes further up the tree; with a recursive descent of the tree, all context information needs to be passed down explicitly. One way of handling this is for each level of processing in the tree to bind a tunnel parameter to the map or array encountered at that level, which then becomes available to all template rules processing data further down the tree.
They are particularly useful when writing a customization layer for an existing stylesheet. For example, if you want to override a template rule that displays chemical formulae, you might want the new rule to be parameterized so you can apply the house-style of a particular scientific journal. Tunnel parameters allow you to pass this information to the overriding template rule without requiring modifications to all the intermediate template rules. Again, a global variable could be used, but only if the same house-style is to be used for all chemical formulae processed during a single transformation.
A tunnel parameter is created by using an xsl:with-param element that specifies tunnel="yes". A template that requires access to the value of a tunnel parameter must declare it using an xsl:param element that also specifies tunnel="yes".
On any template call using an xsl:apply-templates, xsl:call-template, xsl:apply-imports or xsl:next-match instruction, a set of tunnel parameters is passed from the calling template to the called template. This set consists of any parameters explicitly created using <xsl:with-param tunnel="yes">, overlaid on a base set of tunnel parameters. If the xsl:apply-templates, xsl:call-template, xsl:apply-imports or xsl:next-match instruction has an xsl:template declaration as an ancestor element in the stylesheet, then the base set consists of the tunnel parameters that were passed to that template; otherwise (for example, if the instruction is within a global variable declaration, an attribute set declaration, or a stylesheet function), the base set is empty. If a parameter created using <xsl:with-param tunnel="yes"> has the same expanded QName as a parameter in the base set, then the parameter created using xsl:with-param overrides the parameter in the base set; otherwise, the parameter created using xsl:with-param is added to the base set.
When a template specifies <xsl:param tunnel="yes">, this declares the intention to make use of a tunnel parameter; it does not remove the parameter from the base set of tunnel parameters that is passed on to any templates called by this template.
Two sibling xsl:with-param elements must have distinct parameter names, even if one is a tunnel parameter and the other is not. Equally, two sibling xsl:param elements representing template parametersmust have distinct parameter names, even if one is a tunnel parameter and the other is not. However, the tunnel parameters that are implicitly passed in a template call may have names that duplicate the names of non-tunnel parameters that are explicitly passed on the same call.
Tunnel parameters are not passed in calls to stylesheet functions.
All other options of xsl:with-param and xsl:param are available with tunnel parameters just as with non-tunnel parameters. For example, parameters may be declared as mandatory or optional, a default value may be specified, and a required type may be specified. If any conversion is required from the supplied value of a tunnel parameter to the required type specified in xsl:param, then the converted value is used within the receiving template, but the value that is passed on in any further template calls is the original supplied value before conversion. Equally, any default value is local to the template: specifying a default value for a tunnel parameter does not change the set of tunnel parameters that is passed on in further template calls.
Tunnel parameters are passed unchanged through a built-in template rule (see 6.8 Built-in Template Rules).
If a tunnel parameter is declared in an xsl:param element with the attribute tunnel="yes", and if the parameter is explicitly or implicitly mandatory, then a dynamic error occurs [see ERR XTDE0700] if the set of tunnel parameters passed to the template does not include a parameter with a matching expanded QName.
Suppose that the equations in a scientific paper are to be sequentially numbered, but that the format of the number depends on the context in which the equations appear. It is possible to reflect this using a rule of the form:
<xsl:template match="equation">
<xsl:param name="equation-format" select="'(1)'" tunnel="yes"/>
<xsl:number level="any" format="{ $equation-format }"/>
</xsl:template>At any level of processing above this level, it is possible to determine how the equations will be numbered, for example:
<xsl:template match="appendix">
...
<xsl:apply-templates>
<xsl:with-param name="equation-format" select="'[i]'" tunnel="yes"/>
</xsl:apply-templates>
...
</xsl:template>The parameter value is passed transparently through all the intermediate layers of template rules until it reaches the rule with match="equation". The effect is similar to using a global variable, except that the parameter can take different values during different phases of the transformation.
<!-- Category: declaration -->
<xsl:attribute-set
name = eqname
use-attribute-sets? = eqnames〔''〕
visibility? = "public" | "private" | "final" | "abstract"〔'private'〕
streamable? = boolean〔'no'〕 >
<!-- Content: xsl:attribute* -->
</xsl:attribute-set>
Attribute sets generate named collections of attributes that can be used repeatedly on different constructed elements. The xsl:attribute-set declaration is used to declare attribute sets. The requiredname attribute specifies the name of the attribute set. The value of the name attribute is an EQName, which is expanded as described in 5.1.1 Qualified Names.
[Definition: [Definition: An attribute set is defined as a set of xsl:attribute-set declarations in the same package that share the same expanded QName.]
The content of the xsl:attribute-set element consists of zero or more xsl:attribute instructions that are evaluated to produce the attributes in the set.
The effect of the streamable attribute is explained in 9 Streamable Attribute SetsSG.
Attribute sets are used by specifying a use-attribute-sets attribute on the xsl:element or xsl:copy instruction, or by specifying an xsl:use-attribute-sets attribute on a literal result element. An attribute set may be defined in terms of other attribute sets by using the use-attribute-sets attribute on the xsl:attribute-set element itself. The value of the [xsl:]use-attribute-sets attribute is in each case a whitespace-separated list of names of attribute sets. Each name is specified as an EQName, which is expanded as described in 5.1.1 Qualified Names.
[ERR XTSE0710] It is a static error if the value of the use-attribute-sets attribute of an xsl:copy, xsl:element, or xsl:attribute-set element, or the xsl:use-attribute-sets attribute of a literal result element, is not a whitespace-separated sequence of EQNames, or if it contains an EQName that does not match the name attribute of any xsl:attribute-set declaration in the containing package.
An attribute set may be considered as comprising a sequence of instructions, each of which is either an xsl:attribute instruction or an attribute set invocation. Starting with the declarations making up an attribute set, this sequence of instructions can be generated by the following rules:
The relevant attribute set declarations (that is, all declarations of attribute sets within a package sharing the same expanded QName) are considered in order: first in increasing order of import precedence, and within each precedence, in declaration order.
Each declaration is expanded to a sequence of instructions as follows. First, one attribute set invocation is generated for each EQName present in the use-attribute-sets attribute, if present, retaining the order in which the EQNames appear. This is followed by the sequence of contained xsl:attribute instructions, in order.
[Definition: [Definition: 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.]
Similarly, an [xsl:]use-attribute-sets attribute of an xsl:copy, xsl:element, or xsl:attribute-set element, or of a literal result element, is expanded to a sequence of attribute set invocations, one for each EQName in order.
An attribute set is a named component, and the binding of QNames appearing in an attribute set invocation to attribute set components follows the rules in 3.4.4.5 Binding References to Components.
The following two (mutually recursive) rules define how an [xsl:]use-attribute-set attribute is expanded:
An attribute set is evaluated by evaluating each of the contained attribute set invocations and xsl:attribute instructions in order, to deliver a sequence of attribute nodes.
An attribute set invocation is evaluated by evaluating the attribute set to which it is bound, as determined by the rules in 3.4.4.5 Binding References to Components.
For rules regarding cycles in attribute set declarations, see 9.11 Circular Definitions.
Note:
The effect of an attribute set invocation on the dynamic context is the same as the effect of an xsl:call-template instruction. In particular, it does not change the focus. Although attribute sets are often defined with fixed values, or with values that depend only on global variables, it is possible to define an attribute set in such a way that the values of the constructed attributes are dependent on the context item.
Note:
In all cases the result of evaluating an attribute set is subsequently used to create the attributes of an element node, using the rules in 5.7.1 Constructing Complex Content. The effect of those rules is that when the result of evaluating the attribute set contains attributes with duplicate names, the last duplicate wins. The optimization rules allow a processor to avoid evaluating or validating an attribute if it is able to determine that the attribute will subsequently be discarded as a duplicate.
The visibility attribute determines the potential visibility of the attribute set in packages other than the containing package. If the visibility attribute is present on any of the xsl:attribute-set declarations making up the definition of an attribute set (that is, all declarations within the same package sharing the same name), then it must be present, with the same value, on every xsl:attribute-set declaration making up the definition of that attribute set.
If the visibility attribute is present with the value abstract then there must be no xsl:attribute children and no use-attribute-sets attribute.
Changes in 4.0 (next | previous)
Parameters on functions declared using xsl:function can now be defined as optional, with a default value supplied. [Issue 155 PR 159 30 September 2022]
User-defined functions can now have names that are in no namespace. An unprefixed name appearing in a function call is resolved to a no-namespace function with matching local name in preference to a function in the standard fn namespace. [Issue 657 PR 2200 23 September 2025]
[Definition: [Definition: An xsl:function declaration declares the name, parameters, and implementation of a family of stylesheet functions that can be called from any XPath expression within the stylesheet (subject to visibility rules).]
<!-- Category: declaration -->
<xsl:function
name = eqname
as? = sequence-type〔'item()*'〕
visibility? = "public" | "private" | "final" | "abstract"〔'private'〕
streamability? = "unclassified" | "absorbing" | "inspection" | "filter" | "shallow-descent" | "deep-descent" | "ascent" | eqname〔'unclassified'〕
override-extension-function? = boolean〔'yes'〕
[override]? = boolean〔'yes'〕
new-each-time? = "yes" | "true" | "1" | "no" | "false" | "0" | "maybe"
cache? = boolean〔'no'〕 >
<!-- Content: (xsl:param*, sequence-constructor) -->
</xsl:function>
The effect of an xsl:function declaration is to add a function definition to the static context for all XPath expressions used in the stylesheet (including an XPath expression used within a predicate in a pattern).
The content of the xsl:function element consists of zero or more xsl:param elements that specify the formal parameters of the function, followed by a sequence constructor that defines the value to be returned by the function.
The children and attributes of the xsl:function declaration translate directly into properties of the function definition:
The xsl:function/@name attribute defines the function’s name.
The xsl:param children define the function’s parameters:
The xsl:param/@name attribute defines the name of the parameter.
The xsl:param/@required attribute determines whether the parameter is mandatory or optional.
The xsl:param/@as attribute determines the required type of the parameter.
The xsl:param/@select attribute determines a default value for an optional parameter.
The xsl:function/@as attribute defines the return type of the function.
The implementation of the function is defined by the sequence constructor content of the xsl:function element.
An xsl:function declaration can only appear as a top-level element in a stylesheet module.
It is possible to have multiple function declarations sharing the same function name and arity:
Multiple xsl:function declarations are allowed within a single package if they have different import precedence.
A function declared using xsl:function may have the same name and arity as an extension function.
A function declared within one package may be overridden (using xsl:override) in another package.
The rules governing these three scenarios are given in the sections that follow.
Two stylesheet functions with the same name may appear in a package if their arity ranges do not overlap. Neither overrides the other; the function that is selected is determined by the arity of the function call or function reference.
In addition, a stylesheet function may be overridden by another stylesheet function with the same name that has higher import precedence. Such overriding is only allowed, however, if the arity range of the overriding function includes the totality of the arity range of the overridden function.
[Definition: [Definition: 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.]
[ERR XTSE0769] It is a static error for a package to contain an xsl:function declaration F and an xsl:function declaration G such that F and G have the same expanded QName, F has lower import precedence than G, and the arity range of G includes part but not all of the arity range of F, unless G is itself eclipsed by another xsl:function declaration.
[ERR XTSE0770] It is a static error for a package to contain an xsl:function declaration F and an xsl:function declaration G such that F and G have the same expanded QName and the same import precedence, if the arity ranges of F and G overlap in whole or in part, unless F and G are both eclipsed by another xsl:function declaration.
Similarly it is a static error [see ERR XTDE0770] for a package to contain an xsl:function declaration F that is not eclipsed by another xsl:function declaration, if its name and arity range conflict with a constructor function in the static context. There will be a constructor function (with arity 1) in the static context for every atomic type or plain union type in the in-scope schema components.
Changes in 4.0 (next | previous)
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: [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()*).
This section describes instructions that directly create new nodes.
[Definition: [Definition: In a sequence constructor, an element in the stylesheet that does not belong to the XSLT namespace and that is not an extension instruction (see 24.3 Extension Instructions) is classified as a literal result element.] A literal result element is evaluated to construct a new element node with the same expanded QName (that is, the same namespace URI, local name, and namespace prefix). The result of evaluating a literal result element is a node sequence containing one element, the newly constructed element node.
The content of the element is a sequence constructor (see 5.7 Sequence Constructors). The sequence obtained by evaluating this sequence constructor, after prepending any attribute nodes produced as described in 11.1.2 Attribute Nodes for Literal Result Elements and namespace nodes produced as described in 11.1.3 Namespace Nodes for Literal Result Elements, is used to construct the content of the element, following the rules in 5.7.1 Constructing Complex Content
The base URI of the new element is copied from the base URI of the literal result element in the stylesheet, unless the content of the new element includes an xml:base attribute, in which case the base URI of the new element is the value of that attribute, resolved (if it is a relative URI reference) against the base URI of the literal result element in the stylesheet. (Note, however, that this is only relevant when creating a parentless element. When the literal result element is copied to form a child of an element or document node, the base URI of the new copy is taken from that of its new parent.)
When a stylesheet is used to define a transformation whose output is itself a stylesheet module, or in certain other cases where the result document uses namespaces that it would be inconvenient to use in the stylesheet, namespace aliasing can be used to declare a mapping between a namespace URI used in the stylesheet and the corresponding namespace URI to be used in the result document.
[Definition: [Definition: 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.]
[Definition: [Definition: 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.]
Either of the literal namespace URI or the target namespace URI can be null: this is treated as a reference to the set of names that are in no namespace.
<!-- Category: declaration -->
<xsl:namespace-alias
stylesheet-prefix = prefix | "#default"
result-prefix = prefix | "#default" />
[Definition: [Definition: 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.]
The effect is that when names in the namespace identified by the literal namespace URI are copied to the result tree, the namespace URI in the result tree will be the target namespace URI, instead of the literal namespace URI. This applies to:
the namespace URI in the expanded QName of a literal result element in the stylesheet
the namespace URI in the expanded QName of an attribute specified on a literal result element in the stylesheet
The effect of an xsl:namespace-alias declaration is local to the package in which it appears: that is, it only affects the result of literal result elements within the same package.
Where namespace aliasing changes the namespace URI part of the expanded QName containing the name of an element or attribute node, the namespace prefix in that expanded QName is replaced by the prefix indicated by the result-prefix attribute of the xsl:namespace-alias declaration.
The xsl:namespace-alias element declares that the namespace URI bound to the prefix specified by the stylesheet-prefix is the literal namespace URI, and the namespace URI bound to the prefix specified by the result-prefix attribute is the target namespace URI. Thus, the stylesheet-prefix attribute specifies the namespace URI that will appear in the stylesheet, and the result-prefix attribute specifies the corresponding namespace URI that will appear in the result tree.
Note:
It is the native namespace bindings that apply, not the fixed namespace bindings. More specifically: if a prefix p appears in the stylesheet-prefix or result-prefix attribute, there must be an in-scope namespace declaration of the form xmlns:p="...."; it is not sufficient to declare the namespace in the fixed-namespaces attribute of the xsl:stylesheet element.
The default namespace (as declared by xmlns) may be specified by using #default instead of a prefix. If no default namespace is in force, specifying #default denotes the null namespace URI. This allows elements that are in no namespace in the stylesheet to acquire a namespace in the result document, or vice versa. Defining an alias for the null namespace URI does not affect no-namespace attributes; these remain in no namespace. However, where result-prefix="#default" is specified and no default namespace is in force, attributes whose namespace matches the literal namespace URI are renamed to be in no namespace.
If a literal namespace URI is declared to be an alias for multiple different target namespace URIs, then the declaration with the highest import precedence is used.
[ERR XTSE0810] It is a static error if within a package there is more than one such declaration with the same literal namespace URI and the same import precedence and different values for the target namespace URI, unless there is also an xsl:namespace-alias declaration with the same literal namespace URI and a higher import precedence.
No error occurs if there is more than one such xsl:namespace-alias declaration having the same literal namespace URI and the same target namespace URI, even if the result-prefix differs; in this case the result-prefix used is the one that appears last in declaration order.
[ERR XTSE0812] It is a static error if a value other than #default is specified for either the stylesheet-prefix or the result-prefix attributes of the xsl:namespace-alias element when there is no in-scope binding for that namespace prefix.
When a literal result element is processed, its namespace nodes are handled as follows:
A namespace node whose string value is a literal namespace URI is not copied to the result tree.
A namespace node whose string value is a target namespace URI is copied to the result tree, whether or not the URI identifies an excluded namespace.
In the event that the same URI is used as a literal namespace URI and a target namespace URI, the second of these rules takes precedence.
Note:
These rules achieve the effect that the element generated from the literal result element will have an in-scope namespace node that binds the result-prefix to the target namespace URI, provided that the namespace declaration associating this prefix with this URI is in scope for both the xsl:namespace-alias instruction and for the literal result element. Conversely, the stylesheet-prefix and the literal namespace URI will not normally appear in the result tree.
When literal result elements are being used to create element, attribute, or namespace nodes that use the XSLT namespace URI, the stylesheet may use an alias.
For example, the stylesheet
<xsl:stylesheet
version="3.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:fo="http://www.w3.org/1999/XSL/Format"
xmlns:axsl="file://namespace.alias">
<xsl:namespace-alias stylesheet-prefix="axsl" result-prefix="xsl"/>
<xsl:template match="/">
<axsl:stylesheet version="3.0">
<xsl:apply-templates/>
</axsl:stylesheet>
</xsl:template>
<xsl:template match="elements">
<axsl:template match="/">
<axsl:comment select="system-property('xsl:version')"/>
<xsl:apply-templates/>
</axsl:template>
</xsl:template>
<xsl:template match="block">
<axsl:template match="{.}">
<fo:block><axsl:apply-templates/></fo:block>
</axsl:template>
</xsl:template>
</xsl:stylesheet>will generate an XSLT stylesheet from a document of the form:
<elements> <block>p</block> <block>h1</block> <block>h2</block> <block>h3</block> <block>h4</block> </elements>
The output of the transformation will be a stylesheet such as the following. Whitespace has been added for clarity. Note that an implementation may output different namespace prefixes from those appearing in this example; however, the rules guarantee that there will be a namespace node that binds the prefix xsl to the URI http://www.w3.org/1999/XSL/Transform, which makes it safe to use the QName xsl:version in the content of the generated stylesheet.
<xsl:stylesheet
version="3.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:fo="http://www.w3.org/1999/XSL/Format">
<xsl:template match="/">
<xsl:comment select="system-property('xsl:version')"/>
<xsl:apply-templates/>
</xsl:template>
<xsl:template match="p">
<fo:block><xsl:apply-templates/></fo:block>
</xsl:template>
<xsl:template match="h1">
<fo:block><xsl:apply-templates/></fo:block>
</xsl:template>
<xsl:template match="h2">
<fo:block><xsl:apply-templates/></fo:block>
</xsl:template>
<xsl:template match="h3">
<fo:block><xsl:apply-templates/></fo:block>
</xsl:template>
<xsl:template match="h4">
<fo:block><xsl:apply-templates/></fo:block>
</xsl:template>
</xsl:stylesheet>Note:
It may be necessary also to use aliases for namespaces other than the XSLT namespace URI. For example, it can be useful to define an alias for the namespace http://www.w3.org/2001/XMLSchema-instance, so that the stylesheet can use the attributes xsi:type, xsi:nil, and xsi:schemaLocation on a literal result element, without running the risk that a schema processor will interpret these as applying to the stylesheet itself. Equally, literal result elements belonging to a namespace dealing with digital signatures might cause XSLT stylesheets to be mishandled by general-purpose security software; using an alias for the namespace would avoid the possibility of such mishandling.
It is possible to define an alias for the XML namespace.
<xsl:stylesheet xmlns:axml="http://www.example.com/alias-xml"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
version="3.0">
<xsl:namespace-alias stylesheet-prefix="axml" result-prefix="xml"/>
<xsl:template match="/">
<name axml:space="preserve">
<first>James</first>
<xsl:text> </xsl:text>
<last>Clark</last>
</name>
</xsl:template>
</xsl:stylesheet>produces the output:
<name xml:space="preserve"><first>James</first> <last>Clark</last></name>
This allows an xml:space attribute to be generated in the output without affecting the way the stylesheet is parsed. The same technique can be used for other attributes such as xml:lang, xml:base, and xml:id.
Note:
Namespace aliasing is only necessary when literal result elements are used. The problem of reserved namespaces does not arise when using xsl:element and xsl:attribute to construct the result tree. Therefore, as an alternative to using xsl:namespace-alias, it is always possible to achieve the desired effect by replacing literal result elements with xsl:element and xsl:attribute instructions.
<!-- Category: instruction -->
<xsl:number
value? = expression
select? = expression
level? = "single" | "multiple" | "any"〔'single'〕
count? = pattern
from? = pattern
format? = { string }〔'1'〕
lang? = { language }
letter-value? = { "alphabetic" | "traditional" }
ordinal? = { string }〔'no'〕
start-at? = { string }
grouping-separator? = { char }
grouping-size? = { integer } />
The xsl:number instruction is used to create a formatted number. The result of the instruction is a newly constructed text node containing the formatted number as its string value.
[Definition: [Definition: The xsl:number instruction performs two tasks: firstly, determining a place marker (this is a sequence of integers, to allow for hierarchic numbering schemes such as 1.12.2 or 3(c)ii), and secondly, formatting the place marker for output as a text node in the result sequence.] The place marker to be formatted can either be supplied directly, in the value attribute, or it can be computed based on the position of a selected node within the tree that contains it.
[ERR XTSE0975] It is a static error if the value attribute of xsl:number is present unless the select, level, count, and from attributes are all absent.
Note:
The facilities described in this section are specifically designed to enable the calculation and formatting of section numbers, paragraph numbers, and the like. For formatting of other numeric quantities, the format-number function may be more suitable.
Furthermore, formatting of integers where there is no requirement to calculate the position of a node in the document can now be accomplished using the format-integer function, which borrows many concepts from the xsl:number specification.
[Definition: [Definition: A sort key specification is a sequence of one or more adjacent xsl:sort elements which together define rules for sorting the items in an input sequence to form a sorted sequence.]
[Definition: [Definition: Within a sort key specification, each xsl:sort element defines one sort key component.] The first xsl:sort element specifies the primary component of the sort key specification, the second xsl:sort element specifies the secondary component of the sort key specification, and so on.
A sort key specification may occur immediately within an xsl:apply-templates, xsl:for-each, xsl:perform-sort, or xsl:for-each-group element.
Note:
When used within xsl:for-each, xsl:for-each-group, or xsl:perform-sort, xsl:sort elements must occur before any other children.
xsl:sort Element<xsl:sort
select? = expression
lang? = { language }
order? = { "ascending" | "descending" }〔'ascending'〕
collation? = { uri }
stable? = { boolean }〔'yes'〕
case-order? = { "upper-first" | "lower-first" }
data-type? = { "text" | "number" | eqname } >
<!-- Content: sequence-constructor -->
</xsl:sort>
The xsl:sort element defines a sort key component. A sort key component specifies how a sort key value is to be computed for each item in the sequence being sorted, and also how two sort key values are to be compared.
The value of a sort key component is determined either by its select attribute or by the contained sequence constructor. If neither is present, the default is select=".", which has the effect of sorting on the actual value of the item if it is an atomic item, or on the typed-value of the item if it is a node. If a select attribute is present, its value must be an XPath expression.
[ERR XTSE1015] It is a static error if an xsl:sort element with a select attribute has non-empty content.
Those attributes of the xsl:sort elements whose values are attribute value templates are evaluated using the same focus as is used to evaluate the select attribute of the containing instruction (specifically, xsl:apply-templates, xsl:for-each, xsl:for-each-group, or xsl:perform-sort).
The stable attribute is permitted only on the first xsl:sort element within a sort key specification.
[ERR XTSE1017] It is a static error if an xsl:sort element other than the first in a sequence of sibling xsl:sort elements has a stable attribute.
[Definition: [Definition: A sort key specification is said to be stable if its first xsl:sort element has no stable attribute, or has a stable attribute whose effective value is yes.]
[Definition: [Definition: The sequence to be sorted is referred to as the initial sequence.]
[Definition: [Definition: The sequence after sorting as defined by the xsl:sort elements is referred to as the sorted sequence.]
[Definition: [Definition: For each item in the initial sequence, a value is computed for each sort key component within the sort key specification. The value computed for an item by using the Nth sort key component is referred to as the Nth sort key value of that item.]
The items in the initial sequence are ordered into a sorted sequence by comparing their sort key values. The relative position of two items A and B in the sorted sequence is determined as follows. The first sort key value of A is compared with the first sort key value of B, according to the rules of the first sort key component. If, under these rules, A is less than B, then A will precede B in the sorted sequence, unless the order attribute of this sort key component specifies descending, in which case B will precede A in the sorted sequence. If, however, the relevant sort key values compare equal, then the second sort key value of A is compared with the second sort key value of B, according to the rules of the second sort key component. This continues until two sort key values are found that compare unequal. If all the sort key values compare equal, and the sort key specification is stable, then A will precede B in the sorted sequence if and only if A preceded B in the initial sequence. If all the sort key values compare equal, and the sort key specification is not stable, then the relative order of A and B in the sorted sequence is implementation-dependent.
Note:
If two items have equal sort key values, and the sort is stable, then their order in the sorted sequence will be the same as their order in the initial sequence, regardless of whether order="descending" was specified on any or all of the sort key components.
The Nth sort key value is computed by evaluating either the select attribute or the contained sequence constructor of the Nth xsl:sort element, or the expression . (dot) if neither is present. This evaluation is done with the focus set as follows:
The context item is the item in the initial sequence whose sort key value is being computed.
The context position is the position of that item in the initial sequence.
The context size is the size of the initial sequence.
Note:
As in any other XPath expression, the current function may be used within the select expression of xsl:sort to refer to the item that is the context item for the expression as a whole; that is, the item whose sort key value is being computed.
The sort key values are atomized, and are then compared. The way they are compared depends on their datatype, as described in the next section.
The rules given in this section apply when comparing values whose type is xs:string or a type derived by restriction from xs:string, or whose type is xs:anyURI or a type derived by restriction from xs:anyURI.
[Definition: [Definition: Facilities in XSLT 3.0 and XPath 3.0 that require strings to be ordered rely on the concept of a named collation. A collation is a set of rules that determine whether two strings are equal, and if not, which of them is to be sorted before the other.] A collation is identified by a URI, but the manner in which this URI is associated with an actual rule or algorithm is largely implementation-defined.
For more information about collations, see [Functions and Operators 4.0] section 5.3 Comparison of strings in [Functions and Operators 4.0]. Some specifications, for example [UNICODE TR10], use the term “collation” to describe rules that can be tailored or parameterized for various purposes. In this specification, a collation URI refers to a collation in which all such parameters have already been fixed. Therefore, if a collation URI is specified, other attributes such as case-order and lang are ignored.
Every implementation must recognize the collation URI http://www.w3.org/2005/xpath-functions/collation/codepoint, which provides the ability to compare strings based on the Unicode codepoint values of the characters in the string.
Furthermore, every implementation must recognize collation URIs representing tailorings of the Unicode Collation Algorithm (UCA), as described in [Functions and Operators 4.0] section 5.3.4 The Unicode Collation Algorithm. Although this form of collation URI must be recognized, implementations are not required to support every possible tailoring.
If the xsl:sort element has a collation attribute, then the strings are compared according to the rules for the named collation: that is, they are compared using the XPath function call compare($a, $b, $collation).
If the effective value of the collation attribute of xsl:sort is a relative URI, then it is resolved against the base URI of the xsl:sort element.
[ERR XTDE1035] It is a dynamic error if the collation attribute of xsl:sort (after resolving against the base URI) is not a URI that is recognized by the implementation as referring to a collation.
Note:
It is entirely for the implementation to determine whether it recognizes a particular collation URI. For example, if the implementation allows collation URIs to contain parameters in the query part of the URI, it is the implementation that determines whether a URI containing an unknown or invalid parameter is or is not a recognized collation URI. The fact that this situation is described as an error thus does not prevent an implementation applying a fallback collation if it chooses to do so.
The lang and case-order attributes are ignored if a collation attribute is present. But in the absence of a collation attribute, these attributes provide input to an implementation-defined algorithm to locate a suitable collation:
The lang attribute indicates that a collation suitable for a particular natural language should be used. The effective value of the attribute must either be a string in the value space of xs:language, or a zero-length string. Supplying the zero-length string has the same effect as omitting the attribute. If a language is requested that is not supported, the processor may use a fallback language identified by removing successive hyphen-separated suffixes from the supplied value until a supported language code is obtained; failing this, the processor behaves as if the lang attribute were omitted.
Note:
The fallback algorithm described above is identical to the rules in RFC4647 Basic Filtering used in BCP 47, and is specified in [RFC4647] in greater detail.
The case-order attribute indicates whether the desired collation should sort upper-case letters before lower-case or vice versa. The effective value of the attribute must be either lower-first (indicating that lower-case letters precede upper-case letters in the collating sequence) or upper-first (indicating that upper-case letters precede lower-case).
When lower-first is requested, the returned collation should have the property that when two strings differ only in the case of one or more characters, then a string in which the first differing character is lower-case should precede a string in which the corresponding character is title-case, which should in turn precede a string in which the corresponding character is upper-case. When upper-first is requested, the returned collation should have the property that when two strings differ only in the case of one or more characters, then a string in which the first differing character is upper-case should precede a string in which the corresponding character is title-case, which should in turn precede a string in which the corresponding character is lower-case.
So, for example, if lang="en", then A a B b are sorted with case-order="upper-first" and a A b B are sorted with case-order="lower-first".
As a further example, if lower-first is requested, then a sorted sequence might be “MacAndrew, macintosh, macIntosh, Macintosh, MacIntosh, macintoshes, Macintoshes, McIntosh”. If upper-first is requested, the same sequence would sort as “MacAndrew, MacIntosh, Macintosh, macIntosh, macintosh, MacIntoshes, macintoshes, McIntosh”.
If none of the collation, lang, or case-order attributes is present, the collation is chosen in an implementation-defined way. It is not required that the default collation for sorting should be the same as the default collation used when evaluating XPath expressions, as described in 5.3.1 Initializing the Static Context and 3.6.2 The default-collation Attribute.
Note:
It is usually appropriate, when sorting, to use a strong collation, that is, one that takes account of secondary differences (accents) and tertiary differences (case) between strings that are otherwise equal. A weak collation, which ignores such differences, may be more suitable when comparing strings for equality.
Useful background information on international sorting is provided in [UNICODE TR10]. The case-order attribute may be interpreted as described in section 6.6 of [UNICODE TR10].
The collation, case-order, and lang attributes are ignored when no string comparisons are performed during the sorting process; this includes the cases where (a) the sequences to be sorted are empty, (b) the sort keys are of a non-string type such as xs:integer, or (c) data-type="number" is specified. In these cases, an implementation may raise errors in the value of these attributes, but is not required to do so. As always, an implementation may issue warnings.
Changes in 4.0 (next | previous)
A new attribute xsl:for-each-group/@split-when is available to give applications more complete control over how a sequence is partitioned [Issue 571 PR 740 26 September 2023]
A new attribute xsl:for-each-group/@merge-when is available to give applications control to create groups based on clustering, overlap, and networks. [Issue 2051 PR 2123 30 September 2025]
The facilities described in this section are designed to allow items in a sequence to be grouped based on common values; for example it allows grouping of elements having the same value for a particular attribute, or elements with the same name, or elements with common values for any other expression. Since grouping identifies items with duplicate values, the same facilities also allow selection of the distinct values in a sequence of items, that is, the elimination of duplicates.
Note:
Simple elimination of duplicates can also be achieved using the function distinct-values: see [Functions and Operators 4.0].
In addition these facilities allow grouping based on sequential position, for example selecting groups of adjacent para elements. The facilities also provide an easy way to do fixed-size grouping, for example identifying groups of three adjacent nodes, which is useful when arranging data in multiple columns.
For each group of items identified, it is possible to evaluate a sequence constructor for the group. Grouping is nestable to multiple levels so that groups of distinct items can be identified, then from among the distinct groups selected, further sub-grouping of distinct items in the current group can be done.
It is also possible for one item to participate in more than one group.
Note:
Grouping can also be achieved by constructing a map. For example, the function call map:build(//employee, fn { department }) constructs a map in which employees are grouped by department.
xsl:for-each-group ElementThe xsl:for-each-groupinstruction allows a flat sequence of items to be processed as a sequence of groups, allowing a number of criteria to be used to define the grouping. The instruction may be used anywhere within a sequence constructor.
<!-- Category: instruction -->
<xsl:for-each-group
select = expression
group-by? = expression
group-adjacent? = expression
group-starting-with? = pattern
group-ending-with? = pattern
split-when? = expression
merge-when? = expression
composite? = boolean〔'no'〕
collation? = { uri } >
<!-- Content: (xsl:sort*, sequence-constructor) -->
</xsl:for-each-group>
The select attribute contains an expression which is evaluated to produce a sequence, called the population.
[Definition: [Definition: The xsl:for-each-group instruction allocates the items in an input sequence into groups of items (that is, it establishes a collection of sequences) based either on common values of a grouping key, or on a pattern that the initial or final item in a group must match.] The sequence constructor that forms the content of the xsl:for-each-group instruction is evaluated once for each of these groups.
[Definition: [Definition: The sequence of items to be grouped, which is referred to as the population, is determined by evaluating the XPath expression contained in the select attribute.]
[Definition: [Definition: The population is treated as a sequence; the order of items in this sequence is referred to as population order.]
A group is never empty. If the population is empty, the number of groups will be zero.
The assignment of items to groups depends on the group-by, group-adjacent, group-starting-with, group-ending-with, split-when,and merge-when attributes.
[ERR XTSE1080] These six attributes are mutually exclusive: it is a static error if none of these attributes is present or if more than one of them is present.
[ERR XTSE1090] It is a static error to specify the collation attribute or the composite attribute if neither the group-by attribute nor the group-adjacent attribute is specified.
[Definition: [Definition: If the group-by or group-adjacent attributes is present, then for each item in the population a set of grouping keys is calculated, as follows: the expression contained in the group-by or group-adjacent attribute is evaluated; the result is atomized; and any xs:untypedAtomic items are cast to xs:string. If composite="yes" is specified, there is a single grouping key whose value is the resulting sequence; otherwise, there is a set of grouping keys, consisting of the distinct atomic items present in the result sequence.]
When calculating grouping keys for an item in the population, the expression contained in the group-by or group-adjacent attribute is evaluated with that item as the context item, with its position in population order as the context position, and with the size of the population as the context size.
If the group-by attribute is present, and if the composite attribute is omitted or takes the value no, then an item in the population may have multiple grouping keys: that is, the group-by expression evaluates to a sequence, and each item in the sequence is treated as a separate grouping key. The item is included in as many groups as there are distinct grouping keys (which may be zero).
If the group-adjacent attribute is used, and if the composite attribute is omitted or takes the value no, then each item in the population must have exactly one grouping key value.
[ERR XTTE1100] It is a type error if the result of evaluating the group-adjacent expression is the empty sequence or a sequence containing more than one item, unless composite="yes" is specified.
Atomic grouping keys are compared using the rules of the distinct-values function, using the relevant collation. The relevant collation is the collation specified as the effective value of the collation attribute, resolved if relative against the base URI of the xsl:for-each-group element; if there is no collation attribute then the default collation is used. Given this collation, two grouping keys K1 and K2 are considered equal if count(distinct-values(($K1, $K2), $collation)) = 1.
Composite grouping keys are equal if they contain the same number of items and the items are pairwise equal when compared according to the rules in the previous paragraph.
[ERR XTDE1110] It is a dynamic error if the collation URI specified to xsl:for-each-group (after resolving against the base URI) is a collation that is not recognized by the implementation. (For notes, [see ERR XTDE1035].)
For more information on collations, see 13.1.3 Sorting Using Collations.
The way in which an xsl:for-each-group element is evaluated depends on which of the six group-defining attributes is present:
If the group-by attribute is present, the items in the population are examined, in population order. For each item J, the expression in the group-by attribute is evaluated to produce a sequence of zero or more grouping key values. If composite="yes" is specified, there will be a single grouping key, which will in general be a sequence of zero or more atomic items; otherwise, there will be zero or more grouping keys, each of which will be a single atomic item. For each one of these grouping keys, if there is already a group created to hold items having that grouping key value, J is appended to that group; otherwise a new group is created for items with that grouping key value, and J becomes its first member.
An item in the population may thus be appended to zero, one, or many groups. An item will never be appended more than once to the same group; if two or more grouping keys for the same item are equal, then the duplicates are ignored. An item here means the item at a particular position within the population—if the population contains the same node at several different positions in the sequence then a group may indeed contain duplicate nodes.
The number of groups will be the same as the number of distinct grouping key values present in the population.
If the group-adjacent attribute is present, the items in the population are examined, in population order. If an item has the same value for the grouping key as its preceding item within the population (in population order), then it is appended to the same group as its preceding item; otherwise a new group is created and the item becomes its first member.
If the group-starting-with attribute is present, then its value must be a pattern.
The items in the population are examined in population order. If an item matches the pattern, or is the first item in the population, then a new group is created and the item becomes its first member. Otherwise, the item is appended to the same group as its preceding item within the population.
If the group-ending-with attribute is present, then its value must be a pattern.
The items in the population are examined in population order. If an item is the first item in the population, or if the previous item in the population matches the pattern, then a new group is created and the item becomes its first member. Otherwise, the item is appended to the same group as its preceding item within the population.
If the split-when attribute is present, then its value must be an expression. This expression is evaluated once for every item in the population except the first. The context item is that item, the context position is its position in the population, and the context size is the size of the population. The expression is supplied with two variables: $group is set to the contents of the current group being constructed, and $next is the next item in the population. If the effective boolean valueXP of the expression is true, then this item forms the start of a new group; if it is false, the item is added to the existing group.
The variable $group is implicitly declared, and shadows any other variable of the same name. Its name is in no namespace. Its scope is the split-when expression, and its type is item()+.
The variable $next is implicitly declared, and shadows any other variable of the same name. Its name is in no namespace. Its scope is the split-when expression, and its type is item().
For example:
split-when="count($group) = 3" starts a new group whenever the existing group has exactly three members; that is, it partitions the population into groups of size 3 (with the last group being smaller if necessary).
split-when="$next[self::h1]" starts a new group whenever an h1 element is encountered. The effect is the same as specifying group-starting-with="h1"
split-when="foot($group)/@continued='no'" starts a new group immediately after any element having @continued="no". The effect is the same as specifying group-ending-with="*[@continued='no']"
split-when="node-name($group[last()] != node-name($next)" starts a new group whenever the name of an item differs from the name of the previous item. The effect is the same as specifying group-adjacent="node-name(.)".
split-when="foot($group)[self::hr] or $next[self::hr]" starts a new group immediately before and immediately after every hr element. (That is, hr elements become singleton groups.)
split-when="$next ne foot($group) + 1" starts a new group whenever the current item is not equal to the previous item plus one. For example 1, 2, 5, 6, 7, 10, 11 is grouped as (1, 2), (5, 6, 7), (10, 11).
split-when="sum($group/string-length()) gt 40" starts a new group when the sum of the string lengths of the items in the current group exceeds 40.
split-when="ends-with(foot($group), '.') and matches($next, '^\p{Lu}')" starts a new group when the last item in the current group ends with "." and the next item starts with a capital letter.
split-when="deep-equal(slice($group, -2 to -1), ('', ''))" starts a new group after two consecutive zero-length strings.
split-when="count($group) gt 1 and head($group)/@name = foot($group)/@name" starts a new group if the last item in the current group has the same value for @name as the first item in that group (provided they are not the same item).
If the merge-when attribute is present, then its value must be an expression that is a sequence comparator. [Definition: [Definition: A sequence comparator is an expression that evaluates two sequences of items and results in a true or false value. ]
The sequence comparator is supplied with two variables: $group-a and $group-b. Each of these variables is implicitly declared, and shadows any other variable of the same name. Its name is in no namespace. Its scope is the merge-when expression, and its type is item()+.
The sequence comparator is evaluated not item by item (as with split-when) but group by group. The context item is absent, the context position is the position of the first sequence ($group-a) within the sequence of groups being constructed, and the context size is the number of groups at the moment of evaluation.
The process begins by creating singleton groups. For each item in the population a group is created, with that item's position as its grouping key, and the item as its only member.
After the groups are created, they are evaluated pairwise against the sequence comparator. The pairwise comparison begins with the first two groups, then the first and third groups, and so on until the first and last groups, then pairwise comparison moves to the second and third groups, then the second and fourth groups, and so forth. Pairwise comparison proceeds until the next-to-last and last groups are evaluated.
$group-a is set to the items in the first group in a pair of groups, G1, and $group-b to the second group, G2.
If the effective boolean valueXP of the sequence comparator is true, then all items in G2 are merged with the items in G1, preserving original sequence order, and the grouping keys of G2 are merged with those of G1, sorted in ascending order. The process of merging two groups is identical to the process described in 15 Merging to merge sequences. Pairwise comparison then restarts from the beginning with the first pair of groups, as described above.
The process is repeated until it is the case that there is no pair of groups for which the sequence comparator evaluates to true, or there is only one group.
Every item in the population will be appended to exactly one group.
Unlike other grouping methods, a group created by merge-when may have more than one grouping key. Although those grouping keys are not significant for the semantics of the grouping operation, they can be used to examine the original population, and they are useful for the merge operation.
merge-when is most effective for building clusters or networks. For example:
merge-when="$group-a/(@id | is-related-to) = $group-b/(@id | is-related-to)" creates groups of elements. In a group with more than one item, each item has at least one other item that it relates to, or that relates to the same item it relates to. That is, each group represents a kind of network cluster.
Suppose we have elements containing text units where word tokens of significance are wrapped in children tok elements. merge-when="every $a in $group-a, $b in $group-b satisfies count($a/tok[. = $b/tok]) ge 3" creates groups of possibly related texts. In groups of more than one item, any pair of texts has at least three common word-tokens.
merge-when="some $a in $group-a, $b in $group-b satisfies count($a/tok[. = $b/tok]) ge 3" creates groups of related texts, likely less cohesive than in the previous example. In groups of more than one item, every text has at least one other text with which it has three word-tokens in common.
merge-when="not($group-a = $group-b)" creates maximal groups of distinct values. For example, 4, 1, 5, 1, 9, 4, 1 is grouped as 4, 1, 5, 9 (with grouping keys 1, 2, 3, 5), 1, 4 (with grouping keys 4, 6), and 1 (with grouping key 7). Note, the first group is always the result of the distinct-values function, and the final group always contains the items that appear most frequently in the original population.
In merge-when="count($group-a) le 3 and count(distinct-values(($group-a, $group-b) ! node-name(.))) eq 1" no group has more than three items. Within each group, every item has the same node name. The effect is the same as specifying group-by="node-name(.)" then subgrouping with split-when="count($group) = 3".
merge-when="some $a in $group-a, $b in $group-b satisfies tokenize($a/@class) = tokenize($b/@class)" creates groups of elements. In a group with multiple items, every item has at least one other item that has at least one of its tokens in @class.
merge-when="some $a in $group-a, $b in $group-b satisfies abs($a - $b) le 2" creates groups of numerals. Each numeral has at least one other numeral where the two differ by two or less. For example, 3, 9, 4, 1, 10, 6 is grouped as (3, 4, 1, 6) (with grouping keys 1, 3, 4, 6) and (9, 10) (with grouping keys 2, 5).
merge-when="some $a in $group-a, $b in $group-b satisfies abs($a - $b) le xs:dayTimeDuration('PT2H')" creates groups of time values. Within groups of more than one item, each time value has at least one other time value that is two hours or less apart. For example, xs:time("11:12:00Z"), xs:time("13:24:55Z"), xs:time("09:44:10Z"), xs:time("14:09:22Z"), xs:time("08:16:30Z") is grouped as (xs:time("11:12:00Z"), xs:time("09:44:10Z"), xs:time("08:16:30Z")) (with grouping keys 1, 3, 5) and (xs:time("13:24:55Z"), xs:time("14:09:22Z")) (with grouping keys 2, 4).
merge-when="every $a in $group-a, $b in $group-b satisfies (string-to-codepoints($a) = string-to-codepoints($b))" creates groups of strings. In groups with more than one member, each member shares at least one codepoint with every other member. For example, ("animal", "bison", "cat", "dog", "zebra") is grouped as ("animal", "bison", "zebra") (linking letters are a, i, n, and b), ("cat") (although it shares letter a with "animal," the group has already been merged with "bison," which has no common letter with "cat"), and ("dog"). The grouping keys are 1, 2, 5, 3, and 4, respectively.
In all cases the order of items within each group is predictable, and reflects the original population order, in that the items are processed in population order and each item is appended at the end of zero or more groups.
Note:
As always, a different algorithm may be used if it achieves the same effect.
[Definition: [Definition: For each group, the item within the group that is first in population order is known as the initial item of the group.]
The sequence constructor contained in the xsl:for-each-group element is evaluated once for each of the groups, in processing order. The sequences that result are concatenated, in processing order, to form the result of the xsl:for-each-group element. Within the sequence constructor, the context item is the initial item of the relevant group, the context position is the position of this group in the processing order of the groups, and the context size is the number of groups This has the effect that within the sequence constructor, a call on position() takes successive values 1, 2, ... last().
Two pieces of information are available during the processing of each group (that is, while evaluating the sequence constructor contained in the xsl:for-each-group instruction, and also while evaluating the sort key of a group as expressed by the select attribute or sequence constructor of an xsl:sort child of the xsl:for-each-group element):
[Definition: [Definition: The current group is the group itself, as a sequence of items].
[Definition: [Definition: 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.]
Information about the current group and the current grouping key is held in the dynamic context, and is available using the current-group and current-grouping-key functions respectively.
In XSLT 2.0, the current group and the current grouping key were passed unchanged through calls of xsl:apply-templates and xsl:call-template, and also xsl:apply-imports and xsl:next-match. This behavior is retained in XSLT 3.0 except in the case where streaming is in use: specifically, if the xsl:apply-templates, xsl:call-template, xsl:apply-imports, or xsl:next-match instruction occurs within a declared-streamableSG construct (typically, within an xsl:source-document instruction, or within a streamable template rule), then the current group and current grouping key are set to absent in the called template. The reason for this is to allow the streamability of an xsl:for-each-group instruction to be assessed statically, as described in 12.5.19 Streamability ofSG.
[Definition: [Definition: 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.]
[Definition: [Definition: 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.]
If there are no xsl:sort elements immediately within the xsl:for-each-group element, the processing order of the groups is the order of first appearance.
Otherwise, the xsl:sort elements immediately within the xsl:for-each-group element define the processing order of the groups (see 13 Sorting). They do not affect the order of items within each group. Multiple sort key components are allowed, and are evaluated in major-to-minor order. If two groups have the same values for all their sort key components, they are processed in order of first appearance if the sort key specification is stable, otherwise in an implementation-dependent order.
The selectexpression of an xsl:sort element is evaluated once for each group. During this evaluation, the context item is the initial item of the group, the context position is the position of this item within the set of initial items (that is, one item for each group in the population) in population order, the context size is the number of groups, the current group is the group whose sort key value is being determined, and the current grouping key is the grouping key for that group. If the xsl:for-each-group instruction uses the group-starting-with, group-ending-with, or split-when attributes, then the current grouping key is absent.
For example, this means that if the grouping key is @category, you can sort the groups in order of their grouping key by writing <xsl:sort select="current-grouping-key()"/>; or you can sort the groups in order of size by writing <xsl:sort select="count(current-group())"/>
The xsl:merge instruction allows a sorted sequence of items to be constructed by merging several input sequences. Each input sequence must have a merge key (one or more atomic items that can be computed as a function of the items in the sequence); the input sequence must either already be sorted on the value of its merge keys, or pre-sorting on these values must be requested. The merge keys for the different input sequences must be compatible in the sense that key values from an item in one sequence are always comparable with key values from an item in a different sequence.
For example, if two log files contain details of events sorted by date and time, then the xsl:merge instruction can be used to combine these into a single sequence that is also sorted by date and time.
The data written to the output sequence can be computed in an arbitrary way from the data in the input sequences, provided it follows the ordering of the input sequences.
The xsl:merge instruction can be used to merge several sequences of items that all have the same structure (more precisely, sequences whose merge keys are computed in the same way): for example, log files created by the same application running on different machines in a server farm. Alternatively, xsl:merge can be used to merge sequences that have different structure (sequences whose merge keys are computed in different ways), provided that the computed merge keys are compatible: an example might be two log files created by different applications, using different XML vocabularies, that both contain timestamped events but represent the timestamp in different ways. The xsl:merge-source element represents a set of input sequences that follow common rules, including the rules for computing the merge key. The xsl:merge operation may take any number of xsl:merge-source elements representing different rules for input sequences, and each xsl:merge-source element may describe any number (zero or more) of input sequences. The number of input sequences to the merging operation is thus fixed only at the time the xsl:merge instruction is evaluated, and may vary from one evaluation to another.
The following examples illustrate some of the possibilities. The detailed explanation of the constructs used follows later in this section.
This example takes as input a homogeneous collection of XML log files each of which contains a sorted sequence of event elements with a timestamp attribute validated as an instance of xs:dateTime. It merges the events from the input files into a single sorted output file.
<xsl:result-document href="merged-events.xml">
<events>
<xsl:merge>
<xsl:merge-source for-each-source="uri-collection('log-files')"
select="events/event">
<xsl:merge-key select="@timestamp"/>
</xsl:merge-source>
<xsl:merge-action>
<xsl:copy-of select="current-merge-group()"/>
</xsl:merge-action>
</xsl:merge>
</events>
</xsl:result-document>The example assumes that there are several input files each of which has a structure similar to the following, in which the timestamp attribute has a typed value that is an instance of xs:dateTime:
<events> <event timestamp="2009-08-20T12:01:01Z">Transaction T1234 started</event> <event timestamp="2009-08-20T12:01:08Z">Transaction T1235 started</event> <event timestamp="2009-08-20T12:01:12Z">Transaction T1235 ended</event> <event timestamp="2009-08-20T12:01:15Z">Transaction T1234 ended</event> </events>
The output file will have the same structure, and will contain copies of all the event elements from all of the input files, in sorted order. Note that multiple events with the same timestamp can occur either within a single file or across multiple files: the order of appearance of these events in the output file corresponds to the order of the log files within the collection (which might or might not be predictable, depending on the implementation).
This example takes as input two log files with different structure, producing a single merged output in which the entries have a common structure:
<xsl:result-document href="merged-events.xml">
<events>
<xsl:merge>
<xsl:merge-source select="doc('log-file-1.xml')/events/event">
<xsl:merge-key select="@timestamp"/>
</xsl:merge-source>
<xsl:merge-source select="doc('log-files-2.xml')/log/day/record">
<xsl:merge-key select="dateTime(../@date, time)"/>
</xsl:merge-source>
<xsl:merge-action>
<xsl:apply-templates select="current-merge-group()"
mode="standardize-log-entry"/>
</xsl:merge-action>
</xsl:merge>
</events>
</xsl:result-document>Here the first input file has a structure similar to that shown in the previous example, while the second input has a different structure, of the form:
<log>
<day date="2009-08-20">
<record>
<time>12:01:09-05:00</time>
<message>Temperature 15.4C</message>
</record>
<record>
<time>12:03:00-05:00</time>
<message>Temperature 18.2C</message>
</record>
</day>
</log>The templates in mode standardize-log-entry convert the log entries to a common output format, for example:
<xsl:template match="event" mode="standardize-log-entry"
as="schema-element(event)">
<xsl:copy-of select="." validation="preserve"/>
</xsl:template>
<xsl:template match="record" mode="standardize-log-entry"
as="schema-element(event)">
<event timestamp="{dateTime(../@date, time)}" xsl:validation="strict">
<xsl:value-of select="message"/>
</event>
</xsl:template>Note:
The xsl:merge instruction is designed to enable streaming of data, so that there is no need to allocate memory to hold the input sequences. However, it can also be used in cases where streamed processing is not possible, for example when the input needs to be sorted.
[Definition: [Definition: A merge source definition is the definition of one kind of input to the merge operation. It selects zero or more merge input sequences, and it includes a merge key specification to define how the merge key values are computed for each such merge input sequence.] A merge source definition corresponds to an xsl:merge-source element in the stylesheet.
[Definition: [Definition: A merge input sequence is an arbitrary sequenceDM of items which is already sorted according to the merge key specification for the corresponding merge source definition.]
[Definition: [Definition: A merge key specification consists of one or more adjacent xsl:merge-key elements which together define how the merge input sequences selected by a merge source definition are sorted. Each xsl:merge-key element defines one merge key component.] For example, a merge key specification for a log file might specify two merge key components, date and time.
[Definition: [Definition: A merge key component specifies one component of a merge key specification; it corresponds to a single xsl:merge-key element in the stylesheet.]
[Definition: [Definition: For each item in a merge input sequence, a value is computed for each merge key component within the merge key specification. The value computed for an item by using the Nth merge key component is referred to as the Nth merge key value of that item.] A merge key value may be any sequence of atomic items (including the empty sequence).
[Definition: [Definition: The ordered collection of merge key values computed for one item in a merge input sequence (one for each merge key component within the merge key specification) is referred to as a combined merge key value.] Since each merge key value is (in general) a sequence of atomic items, the combined merge key value is modeled as an array of such sequences.
[Definition: [Definition: A merge activation is a single evaluation of the sequence constructor contained within the xsl:merge-action element, which occurs once for each distinct combined merge key value.]
During processing of an xsl:merge instruction, two additional values are available within the dynamic context:
[Definition: [Definition: 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.]
[Definition: [Definition: 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.]
These values are made available through the functions current-merge-group, current-merge-key-array and current-merge-key.
The current merge group and current merge key are available within the sequence constructor contained by an xsl:merge-action element. The values are initially absent during the evaluation of global variables and stylesheet parameters, during the evaluation of the use attribute or contained sequence constructor of xsl:key, and during the evaluation of the initial-value attribute of xsl:accumulator and the select attribute of contained sequence constructor of xsl:accumulator-rule. All invocation constructs set the current merge group and current merge key to absent.
Note:
Taken together, these rules mean that any invocation of current-merge-group, current-merge-key-array, or current-merge-key that is not lexically scoped by an xsl:merge-action element will raise a dynamic error.
When an inner xsl:merge instruction is lexically nested within the xsl:merge-action element of an outer xsl:merge instruction, any use of current-merge-group or current-merge-key that appears within the xsl:merge-action of the inner xsl:merge instruction is a reference to the current merge group or current merge key of the inner xsl:merge instruction, while any such reference that appears within the outer xsl:merge-action element, but not within the inner xsl:merge-action, is a reference to the current merge group or current merge key of the outer xsl:merge instruction. This means, for example, that a reference to the current merge group of the outer xsl:merge can appear in the select attribute of an xsl:merge-source child of the inner xsl:merge.
On completion of the evaluation of the xsl:merge-action sequence constructor, the current merge group and current merge key revert to their previous values.
The function library for XPath 3.0 defines several functions that make use of regular expressions:
matches returns a boolean result that indicates whether or not a string matches a given regular expression.
replace takes a string as input and returns a string obtained by replacing all substrings that match a given regular expression with a replacement string.
tokenize returns a sequence of strings formed by breaking a supplied input string at any separator that matches a given regular expression.
analyze-string returns a tree of nodes that effectively add markup to a string indicating the parts of the string that matched the regular expression, as well as its captured groups.
These functions are described in [Functions and Operators 4.0].
Supplementing these functions, XSLT provides an instruction xsl:analyze-string, which is defined in this section.
Note:
The xsl:analyze-string instruction predates the analyze-string function, and provides very similar functionality, though in a different way.
The regular expressions used by this instruction, and the flags that control the interpretation of these regular expressions, must conform to the syntax defined in [Functions and Operators 4.0] (see [Functions and Operators 4.0] section 6.1 Regular expression syntax), which is itself based on the syntax defined in [XML Schema Part 2].
As described in [Functions and Operators 4.0] section 6.1 Regular expression syntax, the effect of processing a string using a regular expression is a sequence of non-overlapping matching segments, each of which is associated with a set of captured groups, represented as a map from a group number to a segment of the input string. The term segment here means a contiguous (and possibly empty) subsequence of characters from the input string, characterized by a starting position and ending position within that string.
Two functions are available for processing the values of captured groups associated with a matching segment.
Examples of the use of these functions can be found in 17.3 Examples of Regular Expression Matching.
Returns the set of captured groups associated with a matching segment during evaluation of the xsl:analyze-string instruction.
fn:regex-groups() as map(xs:integer, record(value as xs:string, position as xs:integer)) |
This function is deterministicFO, context-dependentFO, and focus-independentFO.
[Definition: [Definition: 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.] These captured groups are accessible using the regex-groups and regex-group functions.
The regex-groups function returns this information as a map.
The Nth captured group (where N > 0) is the segment of the input string matched by the subexpression contained by the Nth left parenthesis in the regex, excluding any non-capturing parenthesized expressions. The zeroth captured substring is the segment of the input string that matches the entire regex. In both cases, a segment is identified by a record containing both the captured string itself (as value) and the start position (1-based) of the captured group within the input string (as position).
Note:
This means that the string value of group zero is the same as the value of . (dot).
The result map contains no entry for a number N if there is no captured group with the number N. This can occur for a number of reasons:
N is negative.
The regular expression contains fewer than N capturing subexpressions.
The Nth capturing subexpression exists, but did not match any part of the input string.
The string value of a captured group may be the empty string.
The set of captured groups is a context variable with dynamic scope. It is initially an empty sequence. During the evaluation of an xsl:matching-substring instruction it is set to the sequence of matched segments for that regex match. During the evaluation of an xsl:non-matching-substring instruction or a pattern or a stylesheet function it is set to an empty sequence. On completion of an instruction that changes the value, the variable reverts to its previous value.
The value of the current captured groups is unaffected through calls of xsl:apply-templates, xsl:call-template, xsl:apply-imports or xsl:next-match, or by expansion of named attribute sets.
The regex-groups function provides additional information that is not available via regex-group:
It distinguishes capturing subexpressions that matched an empty string from capturing subexpressions that did not match anything.
It identifies not just the string that was captured, but its position within the input.
In 4.0 regular expressions may contain capturing subexpressions within a lookahead. In this situation a segment returned in the result of regex-groups may be positioned beyond the end of the corresponding matching segment.
Accumulators were introduced in XSLT 3.0 to enable data that is read during streamed processing of a document to be accumulated, processed or retained for later use. However, they may equally be used with non-streamed processing.
[Definition: [Definition: 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.]
There are two ways the values of an accumulator can be established for a given tree: they can be computed by evaluating the rules appearing in the xsl:accumulator declaration, or they can be copied from the corresponding nodes in a different tree. The second approach (copying the values) is available via the snapshot and copy-of functions, or by use of the xsl:copy-of instruction specifying copy-accumulators="yes". Accumulator values are also copied during the implicit invocation of the snapshot function performed by the xsl:merge instruction.
Note:
Accumulators can apply to trees rooted at any kind of node. But because they are most often applied to trees rooted at a document node, this section sometimes refers to the “document” to which an accumulator applies; use of this term should be taken to include all trees whether or not they are rooted at a document node.
Accumulators can apply to trees rooted at nodes (such as text nodes) that cannot have children, though this serves no useful purpose. In the case of a tree rooted at an attribute or namespace node, there is no way to obtain the value of the accumulator.
The following sections give first, the syntax rules for defining an accumulator; then an informal description of the semantics; then a more formal definition; and finally, examples. But to illustrate the concept intuitively, the following simple example shows how an accumulator can be used for numbering of nodes:
This example assumes document input in which figure elements can appear within chapter elements (which we assume are not nested), and the requirement is to render the figures with a caption that includes the figure number within its containing chapter.
When the document is processed using streaming, the xsl:number instruction is not available, so a solution using accumulators is needed.
The required accumulator can be defined and used like this:
<xsl:accumulator name="figNr" as="xs:integer"
initial-value="0" streamable="yes">
<xsl:accumulator-rule match="chapter" select="0"/>
<xsl:accumulator-rule match="figure" select="$value + 1"/>
</xsl:accumulator>
<xsl:mode streamable="yes"/>
<xsl:template match="figure" expand-text="yes">
<xsl:apply-templates/>
<p>Figure {accumulator-before('figNr')}</p>
</xsl:template><!-- Category: declaration -->
<xsl:accumulator
name = eqname
initial-value = expression
as? = sequence-type〔'item()*'〕
streamable? = boolean〔'no'〕 >
<!-- Content: xsl:accumulator-rule+ -->
</xsl:accumulator>
<xsl:accumulator-rule
match = pattern
phase? = "start" | "end"〔'start'〕
select? = expression
capture? = boolean〔'no'〕 >
<!-- Content: sequence-constructor -->
</xsl:accumulator-rule>
An xsl:accumulator element is a declarationXT of an accumulator. The name attribute defines the name of the accumulator. The value of the name attribute is an EQNameXT, which is expanded as described in section 5.1.1 Qualified Names.
An xsl:accumulator declaration can only appear as a top-levelXT element in a stylesheet module.
The capture attribute is allowed only on an xsl:accumulator-rule element that specifies phase="end". Its effect is described in 19.9 Capturing Accumulators.
The functions accumulator-before and accumulator-after return, respectively, the value of the accumulator before visiting the descendants of a given node, and the value after visiting the descendants of a node. Each of these functions takes a single argument, the name of the accumulator, and the function applies implicitly to the context node. The type of the return value (for both functions) is determined by the as attribute of the xsl:accumulator element.
[Definition: [Definition: The functions accumulator-before and accumulator-after are referred to as the accumulator functions.]
The initial value of the accumulator is obtained by evaluating the expression in the initial-value attribute. This attribute is mandatory. The expression in the initial-value attribute is evaluated with a singleton focusXT based on the root node of the streamed input tree to which the accumulator is being applied.
The values of the accumulator for individual nodes in a tree are obtained by applying the xsl:accumulator-rule rules contained within the xsl:accumulator declaration, as described in subsequent sections. The match attribute of xsl:accumulator-rule is a patternXT which determines which nodes trigger execution of the rule; the phase attribute indicates whether the rule fires before descendants are processed (phase="start", which is the default), or after descendants are processed (phase="end").
The select attribute and the contained sequence constructor of the xsl:accumulator-rule element are mutually exclusive: if the select attribute is present then the sequence constructor must be empty. The expression in the select attribute of xsl:accumulator-rule or the contained sequence constructor is evaluated with a static context that follows the normal rules for expressions in stylesheets, except that:
An additional variable is present in the context. The name of this variable is value (in no namespace), and its type is the type that appears in the as attribute of the xsl:accumulator declaration.
The context item for evaluation of the expression or sequence constructor will always be a node that matches the patternXT in the match attribute.
The result of both the initial-value and select expressions (or contained sequence constructor) is converted to the type declared in the as attribute by applying the coercion rulesXT. A type errorXT occurs if conversion is not possible. The as attribute defaults to item()*.
The effect of the streamable attribute is defined in 11 Streamable AccumulatorsSG.
The effect of the capture attribute is defined in 19.9 Capturing Accumulators.
This section describes how accumulator values are established by evaluating the rules in an xsl:accumulator declaration. This process does not apply to trees created with accumulator values copied from another document, for example by using the copy-of or snapshot functions.
[Definition: [Definition: A traversal of a tree is a sequence of traversal events.]
[Definition: [Definition: a traversal event (shortened to event in this section) is a pair comprising a phase (start or end) and a node.] It is modelled as a map with two entries: { "phase": p, "node": n } where p is the string "start" or "end" and n is a node.
The traversal of a tree contains two traversal events for each node in the tree, other than attribute and namespace nodes. One of these events (the “start event”) has phase "start", the other (the “end event”) has phase "end".
The order of traversal events within a traversal is such that, given any two nodes M and N with start/end events denoted by M0, M1, N0, and N1, :
For any node N, N0 precedes N1;
If M is an ancestor of N then M0 precedes N0 and N1 precedes M1;
If M is on the preceding axis of N then M1 precedes N0.
The accumulator defines a (private) delta function Δ. The delta function computes the value of the accumulator for one traversal event in terms of its value for the previous traversal event. The function is defined as follows:
The signature of Δ is function ($old-value as T, $event as map(*)) as T, where T is the sequence type declared in the as attribute of the accumulator declaration;
The implementation of the function is equivalent to the following algorithm:
Let R be the set of xsl:accumulator-rule elements among the children of the accumulator declaration whose phase attribute equals $event("phase") and whose match attribute is a patternXT that matches $event("node")
If R is empty, return $old-value
Let Q be the xsl:accumulator-rule in R that is last in document order
Return the value of the expression in the select attribute of Q, or the contained sequence constructor, evaluating this with a singleton focusXT set to $event("node") and with a dynamic context that binds the variable whose name is $value (in no namespace) to the value $old-value.
Note:
The argument names old-value and event are used here purely for definitional purposes; these names are not available for use within the select expression or contained sequence constructor.
Note:
There is a slight variation here for an accumulator rule specifying phase="end" and capture="yes". For details, see 11 Streamable AccumulatorsSG.
For every node N, other than attribute and namespace nodes, the accumulator defines a pre-descent value BN and a post-descent value AN whose values are as follows:
Let T be the traversal of the tree rooted at fn:root(N).
Let SB be the subsequence of T starting at the first event in T and ending with the start event for node N (that is, the event { "phase": "start", "node": N }).
Let SA be the subsequence of T starting at the first event in T, and ending with the end event for node N (that is, the event { "phase": "end", "node": N }).
Let Z be the result of evaluating the expression contained in the initial-value attribute of the xsl:accumulator declaration, evaluated with a singleton focusXT based on root(N).
Then the pre-descent value BN is the value of fn:fold-left(SB, Z, Δ), and the post-descent value AN is the value of fn:fold-left(SA, Z, Δ).
Changes in 4.0 (next | previous)
Functions that accept a lexical QName as an argument, such as key, function-available, element-available, type-available, system-property, accumulator-before, and accumulator-after, now have the option of supplying an xs:QName value instead. [This change was in the editor's draft accepted by the WG as its baseline when it started work.] [ 1 January 2022]
This section describes XSLT-specific additions to the XPath function library. Some of these additional functions also make use of information specified by declarations in the stylesheet; this section also describes these declarations.
Keys provide a way to work with documents that contain an implicit cross-reference structure. They make it easier to locate the nodes within a document that have a given value for a given attribute or child element, and they provide a hint to the implementation that certain access paths in the document need to be efficient.
xsl:key Declaration<!-- Category: declaration -->
<xsl:key
name = eqname
match = pattern
use? = expression
composite? = boolean〔'no'〕
collation? = uri >
<!-- Content: sequence-constructor -->
</xsl:key>
The xsl:keydeclaration is used to declare keys. The name attribute specifies the name of the key. The value of the name attribute is an EQName, which is expanded as described in 5.1.1 Qualified Names. The match attribute is a Pattern; an xsl:key element applies to all nodes that match the pattern specified in the match attribute.
[Definition: [Definition: A key is defined as a set of xsl:key declarations in the same package that share the same name.]
The key name is scoped to the containing package, and is available for use in calls to the key function within that package.
The value of the key may be specified either using the use attribute or by means of the contained sequence constructor.
[ERR XTSE1205] It is a static error if an xsl:key declaration has a use attribute and has non-empty content, or if it has empty content and no use attribute.
If the use attribute is present, its value is an expression specifying the values of the key. The expression will be evaluated with a singleton focus based on the node that matches the pattern. The result of evaluating the expression is atomized.
Similarly, if a sequence constructor is present, it is used to determine the values of the key. The sequence constructor will be evaluated with the node that matches the pattern as the context node. The result of evaluating the sequence constructor is atomized.
[Definition: [Definition: 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.]
When evaluation of the key specifier results in a sequence (after atomization) containing more than one atomic item, the effect depends on the value of the composite attribute:
When the attribute is absent or has the value no, each atomic item in the sequence acts as an individual key. For example, if match="book" use="author" composite="no" is specified, then a book element may be located using the value of any author element.
When the attribute is present and has the value yes, the sequence of atomic items is treated as a composite key that must be matched in its entirety. For example, if match="book" use="author" composite="yes" is specified, then a book element may be located using the value of all its author elements, supplied in the correct order.
If there are several xsl:key declarations in the same package with the same key name, then they must all have the same effective value for their composite attribute. The effective value is the actual value of the attribute if present, or "no" if the attribute is absent.
Note:
There is no requirement that all the values of a key should have the same type.
The presence of an xsl:key declaration makes it easy to find a node that matches the match pattern if the values of the key specifier (when applied to that node) are known. It also provides a hint to the implementation that access to the nodes by means of these values needs to be efficient (many implementations are likely to construct an index or hash table to achieve this).
Note:
An xsl:key declaration is not bound to a specific source document. The source document to which it applies is determined only when the key function is used to locate nodes using the key. Keys can be used to locate nodes within any source document (including temporary trees), but each use of the key function searches one document only.
Keys can only be used to search within a tree that is rooted at a document node.
The optional collation attribute is used only when deciding whether two strings are equal for the purposes of key matching. Specifically, two key values $a and $b are considered equal if the result of the function call deep-equal($a, $b, $collation) returns true. The effective collation for an xsl:key declaration is the collation specified in its collation attribute if present, resolved against the base URI of the xsl:key element, or the default collation that is in scope for the xsl:key declaration otherwise; the effective collation must be the same for all the xsl:key declarations making up a key.
[ERR XTSE1210] It is a static error if the xsl:key declaration has a collation attribute whose value (after resolving against the base URI) is not a URI recognized by the implementation as referring to a collation.
[ERR XTSE1220] It is a static error if there are several xsl:key declarations in the same package with the same key name and different effective collations. Two collations are the same if their URIs are equal under the rules for comparing xs:anyURI values, or if the implementation can determine that they are different URIs referring to the same collation.
[ERR XTSE1222] It is a static error if there are several xsl:key declarations in a package with the same key name and different effective values for the composite attribute.
It is possible to have:
multiple xsl:key declarations with the same name;
a node that matches the match patterns of several different xsl:key declarations, whether these have the same key name or different key names;
a node that returns more than one value from its key specifier (which can be treated either as separate individual key values, or as a single composite key value);
a key value that identifies more than one node (the key values for different nodes do not need to be unique).
An xsl:key declaration with higher import precedence does not override another of lower import precedence; all the xsl:key declarations in the stylesheet are effective regardless of their import precedence.
Returns a copy of a sequence, retaining copies of the ancestors and descendants of any node in the input sequence, together with their attributes and namespaces.
fn:snapshot( | ||
$input | as item()* | := . |
) as item()* | ||
The zero-argument form of this function is nondeterministicFO, focus-dependentFO, and context-independentFO.
The one-argument form of this function is nondeterministicFO, focus-independentFO, and context-independentFO.
The zero-argument form of this function is defined so that snapshot() returns the value of internal:snaphot-item(.), where internal:snapshot-item (which exists only for the purpose of this exposition) is defined below. Informally, snapshot() takes a snapshot of the context item.
The single argument form of this function is defined in terms of the internal:snapshot-item as follows: snapshot($input) is equivalent to $input ! internal:snapshot-item(.). Informally, snapshot($input) takes a snapshot of each item in the input sequence in turn.
The internal:snapshot-item function behaves as follows:
If the supplied item is an atomic item or a function item (including maps and arrays), then it returns that item unchanged.
If the supplied item is a node, then it returns a snapshot of that node, as defined below.
[Definition: [Definition: 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.]
If the function is called more than once with the same argument, it is implementation-dependent whether each call returns the same node, or whether multiple calls return different nodes. That is, the result of the expression snapshot($X) is snapshot($X) is implementation-dependent.
Except for the effect on accumulators, the internal:snapshot-item function can be expressed as follows:
<xsl:function name="internal:snapshot-item" as="item()">
<xsl:param name="input" as="item()"/>
<xsl:apply-templates select="$input" mode="internal:snapshot"/>
</xsl:function>
<!-- for atomic items and function items, return the item unchanged -->
<xsl:template match="." mode="internal:snapshot" priority="1">
<xsl:sequence select="."/>
</xsl:template>
<!-- for a document node, or any other root node, return a deep copy -->
<xsl:template match="root()" mode="internal:snapshot" priority="5">
<xsl:copy-of select="."/>
</xsl:template>
<!-- for an element, comment, text node, or processing instruction: -->
<xsl:template match="node()" mode="internal:snapshot"
as="node()" priority="3">
<xsl:sequence select="internal:graft-to-parent(
., .., function($n){$n/node()})"/>
</xsl:template>
<!-- for an attribute: -->
<xsl:template match="@*" mode="internal:snapshot"
as="attribute()" priority="3">
<xsl:variable name="name" select="node-name(.)"/>
<xsl:sequence select="internal:graft-to-parent(., ..,
function($n){$n/@*[node-name(.) = $name]})"/>
</xsl:template>
<!-- for a namespace node: -->
<xsl:template match="namespace-node()" mode="internal:snapshot"
as="namespace-node()" priority="3">
<xsl:variable name="name" select="local-name(.)"/>
<xsl:sequence select="internal:graft-to-parent(., ..,
function($n){$n/namespace-node()[local-name(.) = $name]})"/>
</xsl:template>
<!-- make a copy C of a supplied node N, grafting it to a shallow copy of
C's original parent, and returning the copy C -->
<xsl:function name="internal:graft-to-parent" as="node()">
<xsl:param name="n" as="node()"/>
<xsl:param name="original-parent" as="node()?"/>
<xsl:param name="down-function" as="function(node()) as node()"/>
<xsl:choose>
<xsl:when test="exists($original-parent)">
<xsl:variable name="p" as="node()">
<xsl:copy select="$original-parent">
<xsl:copy-of select="@*"/>
<xsl:copy-of select="$n"/>
</xsl:copy>
</xsl:variable>
<xsl:variable name="copied-parent"
select="internal:graft-to-parent(
$p, $original-parent/.., function($n){$n/node()}))"/>
<xsl:sequence select="$down-function($copied-parent)"/>
</xsl:when>
<xsl:otherwise>
<xsl:sequence select="$n"/>
</xsl:otherwise>
</xsl:choose>
</xsl:function>The snapshot function is available for use (and is primarily intended for use) when a source document is processed using streaming. It can also be used when not streaming. The effect is to take a copy of the subtree rooted at the current node, along with copies of the ancestors and their attributes, and to make this available as a normal tree, that can be processed without any of the restrictions that apply while streaming, for example only being able to process children once. The copy, of course, does not include siblings of the context node or of its ancestors, so any attempt to navigate to these siblings will result in an empty sequence being returned.
For parentless nodes, the effect of snapshot($x) is identical to the effect of copy-of($x).
Using | |
This example copies from the source document all employees who work in marketing and are based in Dubai. It assumes that employees are grouped by location. Because there are two accesses using the child axis (referencing | |
<xsl:source-document streamable="yes" href="employees.xml">
<xsl:for-each select="snapshot(locations/location[@name='Dubai']
/employee)[department='Marketing']">
<employee>
<location code="{../@code}"/>
<salary value="{salary}"/>
</employee>
</xsl:for-each>
</xsl:source-document> |
Changes in 4.0 (next | previous)
Functions that accept a lexical QName as an argument, such as key, function-available, element-available, type-available, system-property, accumulator-before, and accumulator-after, now have the option of supplying an xs:QName value instead. [This change was in the editor's draft accepted by the WG as its baseline when it started work.] [ 1 January 2022]
XSLT allows three kinds of extension: extension attributes, extension instructions, and extension functions.
[Definition: [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: [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: [Definition: An extension function is a named function introduced to the static or dynamic context by mechanisms outside the scope of this specification.]
This specification does not define any mechanism for creating or binding implementations of extension attributes, extension instructions, or extension functions, and it is not required that implementations support any such mechanism. Such mechanisms, if they exist, are implementation-defined. Therefore, an XSLT stylesheet that must be portable between XSLT implementations cannot rely on particular extensions being available. XSLT provides mechanisms that allow an XSLT stylesheet to determine whether the implementation makes particular extensions available, and to specify what happens if those extensions are not available. If an XSLT stylesheet is careful to make use of these mechanisms, it is possible for it to take advantage of extensions and still retain portability.
[ERR XTSE0085] It is a static error to use a reserved namespace in the name of any extension attribute, extension function, or extension instruction, other than a function or instruction defined in this specification or in a normatively referenced specification. It is a static error to use a prefix bound to a reserved namespace in the [xsl:]extension-element-prefixes attribute.
Changes in 4.0 (next | previous)
It is possible to invoke a named template using an extension instruction, specifically, an element whose name matches the name of the named template. [Issue 168 30 September 2022]
[Definition: [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.
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
xsl:result-documentThere are restrictions on the use of the xsl:result-document instruction, designed to ensure that the results are fully interoperable even when processors optimize the sequence in which instructions are evaluated. Informally, the restriction is that the xsl:result-document instruction can only be used while writing a final result tree, not while writing to a temporary tree or a sequence. This restriction is defined formally as follows.
[Definition: [Definition: Each instruction in the stylesheet is evaluated in one of two possible output states: final output state or temporary output state.]
[Definition: [Definition: The first of the two output states is called final output state. This state applies when instructions are writing to a final result tree.]
[Definition: [Definition: The second of the two output states is called temporary output state. This state applies when instructions are writing to a temporary tree or any other non-final destination.]
The instructions in the initial named template are evaluated in final output state. An instruction is evaluated in the same output state as its calling instruction, except that xsl:variable, xsl:param, xsl:with-param, xsl:function, xsl:key, xsl:sort, xsl:accumulator-rule, and xsl:merge-key always evaluate the instructions in their contained sequence constructor in temporary output state.
[ERR XTDE1480] It is a dynamic error to evaluate the xsl:result-document instruction in temporary output state.
[ERR XTDE1490] It is a dynamic error for a transformation to generate two or more final result trees with the same URI.
Note:
Note, this means that it is an error to evaluate more than one xsl:result-document instruction that omits the href attribute, or to evaluate any xsl:result-document instruction that omits the href attribute if an initial final result tree is created implicitly.
In addition, an implementation may raise this error if it is able to detect that two or more final result trees are generated with different URIs that refer to the same physical resource.
[ERR XTDE1500] It is a dynamic error for a stylesheet to write to an external resource and read from the same resource during a single transformation, if the same absolute URI is used to access the resource in both cases.
In addition, an implementation may raise this error if it is able to detect that a transformation writes to a resource and reads from the same resource using different URIs that refer to the same physical resource. Note that if the error is not detected, it is implementation-dependent whether the document that is read from the resource reflects its state before or after the result tree is written.
[Definition: [Definition: The current output URI is the URI associated with the principal result or secondary result that is currently being written.]
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.
xsl:output declarationChanges in 4.0 (next | previous)
A new serialization parameter escape-solidus is provided to control whether the character / is escaped as \/ by the JSON serialization method. [Issue 530 PR 534 9 June 2023]
A new serialization parameter canonical is available to give control over serialization of XML, XHTML, and JSON. [Issue 938 PR 2259 2 November 2025]
A new serialization parameter json-lines is available to enable output as one JSON value per line. [Issue 1538 PRs 1497 1546 13 November 2024]
<!-- Category: declaration -->
<xsl:output
name? = eqname
method? = "xml" | "html" | "xhtml" | "text" | "json" | "adaptive" | eqname
allow-duplicate-names? = boolean
build-tree? = boolean
byte-order-mark? = boolean
canonical? = boolean
cdata-section-elements? = eqnames
doctype-public? = string
doctype-system? = string
encoding? = string
escape-solidus? = boolean
escape-uri-attributes? = boolean
html-version? = decimal
include-content-type? = boolean
indent? = boolean
item-separator? = string
json-lines? = boolean
json-node-output-method? = "xml" | "html" | "xhtml" | "text" | eqname
media-type? = string
normalization-form? = "NFC" | "NFD" | "NFKC" | "NFKD" | "fully-normalized" | "none" | nmtoken
omit-xml-declaration? = boolean
parameter-document? = uri
standalone? = boolean | "omit"
suppress-indentation? = eqnames
undeclare-prefixes? = boolean
use-character-maps? = eqnames
version? = nmtoken />
The xsl:output declaration is optional; if used, it must always appear as a top-level element within a stylesheet module.
A stylesheet may contain multiple xsl:output declarations and may include or import stylesheet modules that also contain xsl:output declarations. The name of an xsl:output declaration is the value of its name attribute, if any.
[Definition: [Definition: All the xsl:output declarations within a package that share the same name are grouped into a named output definition; those that have no name are grouped into a single unnamed output definition.]
An output definition is scoped to a package. If this is a library package the output definition applies only to xsl:result-document instructions within the same package. If it is the top-level package, the output definition applies to xsl:result-document instructions within the same package and also to the implicit final result tree.
A stylesheet always includes an unnamed output definition; in the absence of an unnamed xsl:output declaration, the unnamed output definition is equivalent to the one that would be used if the stylesheet contained an xsl:output declaration having no attributes.
A named output definition is used when its name matches the format attribute used in an xsl:result-document element. The unnamed output definition is used when an xsl:result-document element omits the format attribute. It is also used when serializing the principal result. .
All the xsl:output elements making up an output definition are effectively merged. For those attributes whose values are namespace-sensitive, the merging is done after lexical QNames have been converted into expanded QNames. For the cdata-section-elements and suppress-indentation attributes, the output definition uses the union of the values from all the constituent xsl:output declarations. For the use-character-maps attribute, the output definition uses the concatenation of the sequences of expanded QNames values from all the constituent xsl:output declarations, taking them in order of increasing import precedence, or where several have the same import precedence, in declaration order. For other attributes, the output definition uses the value of that attribute from the xsl:output declaration with the highest import precedence.
The parameter-document attribute allows serialization parameters to be supplied in an external document. The external document must contain an output:serialization-parameters element with the format described in [Serialization 4.0] section 3.1 Setting Serialization Parameters by Means of a Parameter Document, and the parameters are interpreted as described in that specification.
If present, the URI supplied in the parameter-document attribute is dereferenced, after resolution against the base URI of the xsl:output element if it is a relative reference. The parameter document should be read during static analysis of the stylesheet. A serialization error occurs if the result of dereferencing the URI is ill-formed or invalid; but if no document can be found at the specified location, the attribute should be ignored.
A serialization parameter specified in the parameter-document takes precedence over a value supplied directly in the output declaration, except that the values of the cdata-section-elements and suppress-indentation attributes are merged in the same way as when multiple xsl:output declarations are merged.
[ERR XTSE1560] It is a static error if two xsl:output declarations within an output definition specify explicit values for the same attribute (other than cdata-section-elements, suppress-indentation, and use-character-maps), with the values of the attributes being not equal, unless there is another xsl:output declaration within the same output definition that has higher import precedence and that specifies an explicit value for the same attribute.
If the result is not serialized, then the decision whether to return the raw result or to construct a tree depends on the effective value of the build-tree attribute. If the effective value of the build-tree attribute is yes, then a final result tree is created by invoking the process of sequence normalization. Conversely, if the result is serialized, then the decision whether or not to construct a tree depends on the choice of serialization method, and the build-tree attribute is then ignored. For example, with method="xml" a tree is always constructed, whereas with method="json" a tree is never constructed.
Note:
The default for build-tree may differ for user-defined serialization methods or for serialization methods introduced in future versions of this specification.
[Definition: [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.
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="<%"/> <xsl:output-character character="»" string="%>"/> <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.
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=" " string="&nbsp;" />
<xsl:output-character character="¡" string="&iexcl;" />
...
</xsl:character-map>
<xsl:character-map name="doc-entities">
<xsl:output-character character="" string="&t-and-c;" />
<xsl:output-character character="" string="&chap1;" />
<xsl:output-character character="" string="&chap2;" />
...
</xsl:character-map>
<xsl:character-map name="windows-format">
<!-- newlines as CRLF -->
<xsl:output-character character="
" string="
" />
<!-- tabs as three spaces -->
<xsl:output-character character="	" string=" " />
<!-- images for special characters -->
<xsl:output-character character=""
string="<img src='special1.gif' />" />
<xsl:output-character character=""
string="<img src='special2.gif' />" />
...
</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.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="⎘" _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.
Changes in 4.0 (previous)
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]
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:
The schema-awareness feature, defined in 27.2 Schema-Awareness Conformance Feature
The serialization feature, defined in 27.3 Serialization Feature
The backwards compatibility feature, defined in 27.4 Compatibility Features
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:
A processor that does not provide the schema-awareness feature restricts the data model so that it does not contain atomic items of types other than the built-in types, or nodes with non-trivial type annotations.
[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.
[Definition: [Definition: 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.] These constructs are listed below.
A conformant processor must either be a conformant schema-aware XSLT processor or a conformant non-schema-aware processor.
[Definition: [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: [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.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.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.
[Definition: [Definition: A processor that claims conformance with the serialization featuremust support the conversion of a final result tree to a sequence of octets following the rules defined in 26 Serialization.] It must respect all the attributes of the xsl:output and xsl:character-map declarations, and must provide all four output methods, xml, xhtml, html, and text. Where the specification uses words such as must and required, then it must serialize the result tree in precisely the way described; in other cases it may use an alternative, equivalent representation.
A processor may claim conformance with the serialization feature whether or not it supports the setting disable-output-escaping="yes" on xsl:text, or xsl:value-of.
A processor that does not claim conformance with the serialization feature must not raise an error merely because the stylesheet contains xsl:output or xsl:character-map declarations, or serialization attributes on the xsl:result-document instruction. Such a processor may check that these declarations and attributes have valid values, but is not required to do so. Apart from optional validation, these declarations should be ignored.
Note:
A processor that does not claim conformance with the serialization feature may offer alternative serialization capabilities, and these may make use of the serialization parameters defined on xsl:output and/or xsl:result-document. Such a processor may implement selected parts of the serialization capabilities defined in this specification. For example, it may implement selected output methods, or selected serialization properties. It may implement sequence normalization using the item-separator property even if it has no other serialization capabilities.
If the processor claims conformance with the serialization feature then it must fully implement the serialize function defined in [Functions and Operators 4.0], and must not raise error [ERR FODC0010] FO40 as the result of such a call.
If the processor does not claim conformance with the serialization feature, then it may raise error [ERR FODC0010] FO40 in respect of some or all calls on the serialize function; it must not return a result from a call on this function unless the result is conformant with the specification, given the parameters actually supplied.
A processor that claims conformance with the Serialization Feature must satisfy the mandatory requirements of [Serialization 4.0]. It must provide a mode of operation which conforms to the 3.0 version of that specification. It may also provide a mode of operation which conforms to a later version of that specification; in such cases the detail of how XSLT 3.0 interacts with new features introduced by such a version (for example, support for new serialization properties) is implementation-defined.
[Definition: [Definition: 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.]
Note that a processor that does not claim conformance with the XSLT 1.0 compatibility featuremust raise a dynamic error if an instruction is evaluated whose effective version is 1.0. [see ERR XTDE0160].
Note:
The reason this is a dynamic error rather than a static error is to allow stylesheets to contain conditional logic, following different paths depending on whether the XSLT processor implements XSLT 1.0, 2.0, or 3.0. The selection of which path to use can be controlled by using the system-property function to test the xsl:version system property.
A processor that claims conformance with the XSLT 1.0 compatibility featuremust permit the use of the namespace axis in XPath expressions when backwards compatible behavior is enabled. In all other circumstances, support for the namespace axis is optional.
Note:
There are no incompatibilities between 3.0 and 2.0 that would justify a 2.0-compatibility mode. When a 3.0 processor encounters a stylesheet that specifies version="2.0", evaluation therefore proceeds exactly as if it specified version="3.0". However, a software product may invoke an XSLT 2.0 processor in preference to an XSLT 3.0 processor when the stylesheet specifies version="2.0", in which case any use of new 3.0 constructs will be rejected.
There are cases where setting [xsl:]version to a value less than 4.0 affects the behavior of an XSLT 4.0 stylesheet: see J Incompatibilities with XSLT 3.0. However these are sufficiently minor that they do not warrant the introduction of a separate conformance option.
[Definition: [Definition: 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.]
A processor that does not claim conformance with the streaming feature is not required to use streamed processing and is not required to determine whether any construct is guaranteed streamable. Such a processor must, however, implement the semantics of all constructs in the language provided that enough memory is available to perform the processing without streaming.
A processor that conforms with the feature must return the value "yes" in response to the function call system-property('xsl:supports-streaming'); a processor that does not conform with the feature must return the value "no".
Note:
The term streamed processing as used here means the ability to process arbitrarily large input documents without ever-increasing memory requirements.