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.
XSLT 4.0 is a revised version of the XSLT 3.0 Recommendation [XSLT 3.0] published on 8 June 2017. Changes are presented in 1.2 What’s New in XSLT 4.0?.
XSLT 4.0 is designed to be used in conjunction with XPath 4.0, which is defined in [XPath 4.0]. XSLT shares the same data model as XPath 4.0, which is defined in [XDM 3.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.
This section describes the status of this document at the time of its publication. Other documents may supersede this document. A list of current W3C publications and the latest revision of this technical report can be found in the W3C technical reports index at https://www.w3.org/TR/.
This document has no official standing. It is produced by the editor as a proposal for community review. Insofar as it copies large amounts of text from the W3C XSLT 3.0 Recommendation, W3C copyright and similar provisions apply.
The publications of this community group are dedicated to our co-chair, Michael Sperberg-McQueen (1954–2024).
[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 5.46.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.13 Stylesheet Preprocessing.
[Definition: The effective value of an attribute or text node in the stylesheet is the value after any required expansion or normalization.]
More specifically, the effective value is the value after:
Expanding shadow attributes as described in 3.13.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.10 Forwards Compatible Processing.
[Definition: Some constructs defined in this specification are described as being deprecated. The use of this term implies that stylesheet authors should not use the construct, and that the construct may be removed in a later version of this specification.]
Note:
This specification includes a non-normative XML Schema for XSLT stylesheet modules (see H Schemas for XSLT 4.0 Stylesheets). The syntax summaries described in this section are normative.
XSLT defines a set of standard functions which are additional to those defined in [Functions and Operators 4.0]. A list of these functions appears in G.2 List of XSLT-defined functions. The signatures of these functions are described using the same notation as used in [Functions and Operators 4.0]. The names of many of these functions are in the standard function namespace.
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.66.7 Default Priority for Template Rules), 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: 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.
This section describes the overall structure of a stylesheet as a collection of XML documents.
[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.13.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.9 Backwards Compatible Processing and 3.10 Forwards Compatible Processing
[xsl:]xpath-default-namespacesee 5.1.2 Unprefixed Lexical QNames in Expressions and Patterns
[Definition: An explicit package is represented by an xsl:package element, which will generally be the outermost element of an XML document. When the xsl:package element is not used explicitly, the entire stylesheet comprises a single implicit package.] (This specification does not preclude the xsl:package being embedded in another XML document, but it will never have any other XSLT element as an ancestor).
<xsl:package
id? = id
name? = uri
package-version? = string〔'1'〕
version = decimal
input-type-annotations? = "preserve" | "strip" | "unspecified"〔'unspecified'〕
declared-modes? = boolean〔'yes'〕
default-mode? = eqname | "#unnamed"〔'#unnamed'〕
default-validation? = "preserve" | "strip"〔'strip'〕
default-collation? = uris
extension-element-prefixes? = prefixes
exclude-result-prefixes? = prefixes
expand-text? = boolean〔'no'〕
fixed-namespaces? = string
schema-role? = ncname
use-when? = expression〔true()〕
xpath-default-namespace? = uri >
<!-- Content: ((xsl:expose | declarations)*) -->
</xsl:package>
[Definition: The content of the xsl:package element is referred to as the package manifest].
The version attribute indicates the version of the XSLT language specification to which the package manifest conforms. The value should normally be 4.0. If the value is numerically less than 4.0, the content of the xsl:package element is processed using the rules for backwards compatible behavior (see 3.9 Backwards Compatible Processing). If the value is numerically greater than 4.0, it is processed using the rules for forwards compatible behavior (see 3.10 Forwards Compatible Processing).
A package typically has a name, given in its name attribute, which must be an absolute URI. Unnamed packages are allowed, but they can only be used as the “top level” of an application; they cannot be the target of an xsl:use-package declaration in another package.
A package may have a version identifier, given in its package-version attribute. This is used to distinguish different versions of a package. The value of the version attribute, after trimming leading and trailing whitespace, must conform to the syntax given in 3.5.1 Versions of a Package. If no version number is specified for a package, version 1 is assumed.
The attributes default-collation, default-mode, default-validation, exclude-result-prefixes, expand-text, extension-element-prefixes, use-when, version, and xpath-default-namespace are standard attributes that can appear on any XSLT element, and potentially affect all descendant elements. Their meaning is described in 3.4 Standard Attributes.
The package manifest contains the following elements, arbitrarily ordered:
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.3.1 Stripping Type Annotations from a Source Tree.
A more extensive example of a package, illustrating how components in a package can be overridden in a client package, is given in 3.5.8 Worked Example of a Library Package.
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.95.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: A xsl:package-location without the attribute is-priority, or with is-priority set to true is a high priority package location.][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: The first package location whose value of href, when resolved as described in 5.95.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.
xsl:package-locations.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.
The rules in the previous section apply to named components including functions, named templates, global variables, and named attribute sets. The rules for modes, and the template rules appearing within a mode, are slightly different.
The unnamed mode is local to a package: in effect, each package has its own private unnamed mode, and the unnamed mode of one package does not interact with the unnamed mode of any other package. An xsl:apply-templates instruction with no mode attribute is treated as a symbolic reference to the default mode defined for that instruction (see 3.7.3 The default-mode Attribute), which in turn defaults to the unnamed mode. Because the unnamed mode always has private visibility, it cannot be overridden in another package.
A named mode may be declared in an xsl:mode declaration as being either public, private, or final. The values of the visibility attribute are interpreted as follows:
| Value | Meaning |
|---|---|
| public | A using package may use xsl:apply-templates to invoke templates in this mode; it may also declare additional template rules in this mode, which are selected in preference to template rules in the used package. These may appear only as children of the xsl:override element within the xsl:use-package element. |
| private | A using package may neither reference the mode nor provide additional templates in this mode; the name of the mode is not even visible in the using package, so no such attempt is possible. The using package can use the same name for its own modes without risk of conflict. |
| final | A using package may use xsl:apply-templates to invoke templates in this mode, but it must not provide additional template rules in this mode. |
As with other named components, an xsl:use-package declaration may contain an xsl:accept element to control the visibility of a mode acquired from the used package. The allowed values of its visibility attribute are public, private, and final.
The xsl:mode declaration itself must not be overridden. A using package must not contain an xsl:mode declaration whose name matches that of a public or finalxsl:mode component accepted from a used package.
The xsl:expose and xsl:accept elements may be used to reduce the visibility of a mode in a using package; the same rules apply in general, though some of the rules are not applicable because, for example, modes cannot be abstract.
It is not possible for a package to combine the template rules from two other packages into a single mode. When xsl:apply-templates is used without specifying a mode, the chosen template rules will always come from the same package; when it is used with a named mode, then they will come from the package where the mode is defined, or any package that uses that package and adds template rules to the mode. If two template rules defined in different packages match the same node, then the rule in the using package wins over any rule in the used package; this decision is made before taking other factors such as import precedence and priority into account.
A static error occurs if two modes with the same name are visible within a package, either because they are both declared within the package, or because one is declared within the package and the other is acquired from a used package, or because both are accepted from different used packages.
The rules for matching template rules by import precedence and priority operate as normal, with the addition that template rules declared within an xsl:use-package element have higher precedence than any template rule declared in the used package. More specifically, given an xsl:apply-templates instruction in package P, naming a mode M that is declared in a used package Q and is overridden in P, the search order for template rules is:
Rules declared within P (specifically, xsl:template rules declared as children of an xsl:override element within the xsl:use-package element that references package Q). If there are multiple rules declared within P that match a selected node, they are resolved on the basis of their explicit or implicit priority, and if the priorities are equal, the last one in declaration order wins.
Rules declared within Q, taking import precedence, priority, and declaration order into account in the usual way (see 6.56.6 Conflict Resolution for Template Rules).
Built-in template rules (see 6.86.9 Built-in Template Rules) selected according to the on-no-match attribute of the xsl:mode declaration (in Q), or its default.
If the mode is overridden again in a package R that uses P, then this search order is extended by adding R at the start of the search list, and so on recursively.
Note:
If existing XSLT code has been written to use template rules in the unnamed mode, a convenient way to incorporate this code into a library package is to add a stub module that defines a new named public or final mode, in which there is a single template rule whose content is the single instruction <xsl:apply-templates select="."/>. This in effect redirects xsl:apply-templates instructions using the named mode to the rules defined in the unnamed mode.
In previous versions of XSLT, modes were implicitly declared by simply using a mode name in the mode attribute of xsl:template or xsl:apply-templates. XSLT 3.0 introduced the ability to declare a mode explicitly using an xsl:mode declaration (see 6.7.16.8.1 Declaring Modes).
By default, within a package that is defined using an explicit xsl:package element, all modes must be explicitly declared. In an implicit package, however (that is, one rooted at an xsl:stylesheet or xsl:transform element), modes can be implicitly declared as in previous XSLT versions.
The declared-modes attribute of xsl:package determines whether or not modes that are referenced within the package must be explicitly declared. If the value is yes (the default), then it is an error to use a mode name unless the package either contains an explicit xsl:mode declaration for that mode, or accepts the mode from a used package. If the value is no, then this is not an error.
This attribute affects all modules making up the package, it is not confined to declarations appearing as children of the xsl:package element.
[ERR XTSE3085] It is a static error, when the effective value of the declared-modes attribute of an xsl:package element is yes, if the package contains an explicit reference to an undeclared mode, or if it implicitly uses the unnamed mode and the unnamed mode is undeclared.
For the purposes of the above rule:
A mode is declared if either of the following conditions is true:
The package contains an xsl:mode declaration for that mode.
The mode is a public or final mode accepted from a used package.
The offending reference may be either an explicit mode name, or the token #unnamed treated as a reference to the unnamed mode, or a defaulted mode attribute, and it may occur in any of the following:
The mode attribute of an xsl:template declaration
The mode attribute of an xsl:apply-templates instruction
An [xsl:]default-mode attribute.
A package implicitly uses the unnamed mode if either of the following conditions is true:
There is an xsl:apply-templates element with no mode attribute, and with no ancestor-or-self having an [xsl:]default-mode attribute.
There is an xsl:template element with a match attribute and no mode attribute, and with no ancestor-or-self having an [xsl:]default-mode attribute.
A new attribute, main-module, is added to the xsl:stylesheet element. The attribute is provided for the benefit of development tools such as syntax-directed editors to provide information about all the components (variables, functions, etc) visible within a stylesheet module. [Issue 87 PR 353 19 April 2023]
<xsl:stylesheet
id? = id
version = decimal
default-mode? = eqname | "#unnamed"〔'#unnamed'〕
default-validation? = "preserve" | "strip"〔'strip'〕
input-type-annotations? = "preserve" | "strip" | "unspecified"〔'unspecified'〕
default-collation? = uris
extension-element-prefixes? = prefixes
exclude-result-prefixes? = prefixes
expand-text? = boolean
fixed-namespaces? = string
main-module? = uri
schema-role? = ncname
use-when? = expression〔true()〕
xpath-default-namespace? = uri >
<!-- Content: (declarations) -->
</xsl:stylesheet>
<xsl:transform
id? = id
version = decimal
default-mode? = eqname | "#unnamed"〔'#unnamed'〕
default-validation? = "preserve" | "strip"〔'strip'〕
input-type-annotations? = "preserve" | "strip" | "unspecified"〔'unspecified'〕
default-collation? = uris
extension-element-prefixes? = prefixes
exclude-result-prefixes? = prefixes
expand-text? = boolean〔'no'〕
fixed-namespaces? = string
main-module? = uri
schema-role? = ncname
use-when? = expression〔true()〕
xpath-default-namespace? = uri >
<!-- Content: (declarations) -->
</xsl:transform>
A stylesheet module is represented by an xsl:stylesheet element in an XML document. xsl:transform is allowed as a synonym for xsl:stylesheet; everything this specification says about the xsl:stylesheet element applies equally to xsl:transform.
The version attribute indicates the version of XSLT that the stylesheet module requires. The attribute is required.
[ERR XTSE0110] The value of the version attribute must be a number: specifically, it must be a valid instance of the type xs:decimal as defined in [XML Schema Part 2].
The version attribute is intended to indicate the version of the XSLT specification against which the stylesheet is written. In a stylesheet written to use XSLT 4.0, the value should normally be set to 4.0. If the value is numerically less than 4.0, the stylesheet is processed using the rules for backwards compatible behavior (see 3.9 Backwards Compatible Processing). If the value is numerically greater than 4.0, the stylesheet is processed using the rules for forwards compatible behavior (see 3.10 Forwards Compatible Processing).
The effect of the input-type-annotations attribute is described in 4.3.1 Stripping Type Annotations from a Source Tree.
The [xsl:]default-validation attribute defines the default value of the validation attribute of all relevant instructions appearing within its scope. For details of the effect of this attribute, see 25.4 Validation.
The optional main-module attribute is purely documentary. By including this attribute in every stylesheet module of a package, an XSLT editing tool may be enabled to locate the top-level module of the relevant package, and thus to gather information about all the global variables, templates, and functions available within the module being edited. This information can be used (for example) to enable auto-completion and error highlighting of the code as it is entered. Note that it may be inconvenient or misleading to use this attribute when the stylesheet module is used as a shared component within multiple stylesheets.
[ERR XTSE0120] An xsl:stylesheet, xsl:transform, or xsl:package element must not have any text node children. (This rule applies after stripping of whitespace text nodes as described in 3.13.1 Stripping Whitespace and Commentary from the Stylesheet.)
[Definition: An element occurring as a child of an xsl:package, xsl:stylesheet, xsl:transform, or xsl:override element is called a top-level element.]
[Definition: Top-level elements fall into two categories: declarations, and user-defined data elements. Top-level elements whose names are in the XSLT namespace are declarations. Top-level elements in any other namespace are user-defined data elements (see 3.7.4 User-defined Data Elements)].
The declaration elements permitted in the xsl:stylesheet element are:
xsl: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.56.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.
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.
The include and import mechanisms use two declarations, xsl:include and xsl:import, which are defined in the sections that follow.
These declarations use an href attribute, whose value is a URI reference, to identify the stylesheet module to be included or imported. If the value of this attribute is a relative URI reference, it is resolved as described in 5.95.8 URI References.
After resolving against the base URI, the way in which the URI reference is used to locate a representation of a stylesheet module, and the way in which the stylesheet module is constructed from that representation, are implementation-defined. In particular, it is implementation-defined which URI schemes are supported, whether fragment identifiers are supported, and what media types are supported. Conventionally, the URI is a reference to a resource containing the stylesheet module as a source XML document, or it may include a fragment identifier that selects an embedded stylesheet module within a source XML document; but the implementation is free to use other mechanisms to locate the stylesheet module identified by the URI reference.
The referenced stylesheet modulemust be either a standard stylesheet module or a simplified stylesheet. It must not be a package manifest. If it is a simplified stylesheet module then it is transformed into the equivalent standard stylesheet module by applying the transformation described in 3.8 Simplified Stylesheet Modules.
Implementations may choose to accept URI references containing a fragment identifier defined by reference to the XPointer specification (see [XPointer Framework]). Note that if the implementation does not support the use of fragment identifiers in the URI reference, then it will not be possible to include an embedded stylesheet module.
[ERR XTSE0165] It is a static error if the processor is not able to retrieve the resource identified by the URI reference, or if the resource that is retrieved does not contain a stylesheet module.
Note:
It is appropriate to use this error code when the resource cannot be retrieved, or when the retrieved resource is not well formed XML. If the resource contains XML that can be parsed but that violates the rules for stylesheet modules, then a more specific error code may be more appropriate.
XSLT uses the expression language defined by XPath 4.0 [XPath 4.0]. Expressions are used in XSLT for a variety of purposes including:
selecting nodes for processing;
specifying conditions for different ways of processing a node;
generating text to be inserted in a result tree.
[Definition: Within this specification, the term XPath expression, or simply expression, means a string that matches the production ExprXP defined in [XPath 4.0].]
XPath expressions may occur:
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 ???.
In general:
It is a static error if an XPath expression does not match the XPath production ExprXP, or if it fails to satisfy other static constraints defined in the XPath specification, for example that all variable references must refer to variables that are in scope. Error codes are defined in [XPath 4.0].
The transformation fails with a dynamic error if any XPath expression is evaluated and raises a dynamic error. Error codes are defined in [XPath 4.0].
The transformation fails with a type error if an XPath expression raises a type error, or if the result of evaluating the XPath expression is evaluated and raises a type error, or if the XPath processor raises a type error during static analysis of an expression. Error codes are defined in [XPath 3.0].
There are some exceptions to these rules, for example:
Static errors may be suppressed where forwards compatible behavior is enabled (see 3.10 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: The context within a stylesheet where an XPath expression appears may specify the required type of the expression. The required type indicates the type of the value that the expression is expected to return.] If no required type is specified, the expression may return any value: in effect, the required type is then item()*.
[Definition: The term coercion rules means the coercion rules defined in [XPath 4.0], applied unless otherwise specified with XPath 1.0 compatibility mode set to false.]
Note:
In earlier versions of this specification, the coercion rules were referred to as the function conversion rules.
Note:
These are the rules defined in [XPath 4.0] for converting the supplied argument of a function call to the required type of that argument, as defined in the function signature. The same rules are used in XSLT for converting the value of a variable to the declared type of the variable, or the result of evaluating a function or template body to the declared type of the function or template. They are also used when parameters are supplied to a template using xsl:with-param. In all such cases, the rules that apply are the XPath 4.0 rules without XPath 1.0 compatibility mode. The rules with XPath 1.0 compatibility mode set to true are used only for XPath function calls, and for the operands of certain XPath operators.
This specification also invokes the XPath coercion rules to convert the result of evaluating an XSLT sequence constructor to a required type (for example, the sequence constructor enclosed in an xsl:variable, xsl:template, or xsl:function element).
Any dynamic error or type error that occurs when applying the coercion rules to convert a value to a required type results in the transformation failing, in the same way as if the error had occurred while evaluating an expression.
Note:
Note the distinction between the two kinds of error that may occur. Attempting to convert an integer to a date is a type error, because such a conversion is never possible. Type errors can be raised statically if they can be detected statically, whether or not the construct in question is ever evaluated. Attempting to convert the xs:untypedAtomic item 2003-02-29 to a date is a dynamic error rather than a type error, because the problem is with this particular value, not with its type. Dynamic errors are raised only if the instructions or expressions that cause them are actually evaluated. [XSLT 3.0 Erratum E21, bug 30236]
The XPath specification states (see Section A.3.4 End-of-Line HandlingXP) that the host language must specify whether the XPath processor normalizes all line breaks on input, before parsing, and if it does so, whether it uses the rules of [XML 1.0] or [XML 1.1]. In the case of XSLT, all handling of line breaks is the responsibility of the XML parser (which may support either XML 1.0 or XML 1.1); the XSLT and XPath processors perform no further changes.
Note:
Most XPath expressions in a stylesheet appear within XML attributes. They are therefore subject to XML line-ending normalization (for example, a CRLF sequence is normalized to LF) and also to XML attribute-value normalization, which replaces tabs and newlines by spaces. Normalization of whitespace can be prevented by using character references such as 	.
XPath expressions appearing in text nodes, (specifically, in text value templates — see 5.7.25.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 Section 2.2 Expression ContextXP). This section describes the way in which these components are initialized when an XPath expression is contained within an XSLT stylesheet.
This section does not apply to static expressions (whose context is defined in 9.7 Static Expressions), nor to XPath expressions evaluated using xsl:evaluate (whose context is defined in 10.5.2 Dynamic context for the target expression). [XSLT 3.0 Erratum E24, bug 30241]
As well as providing values for the static and dynamic context components defined in the XPath specification, XSLT defines additional context components of its own. These context components are used by XSLT instructions (for example, xsl:next-match and xsl:apply-imports), and also by the functions in the extended function library described in this specification.
The following four sections describe:
5.3.1 Initializing the Static Context
5.3.2 Additional Static Context Components used by XSLT
5.3.3 Initializing the Dynamic Context
5.3.4 Additional Dynamic Context Components used by XSLT
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.96.10 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.76.8 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 an 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 substrings: this is a sequence of strings, which is maintained when a string is matched against a regular expression using the xsl:analyze-string instruction, and which is accessible using the regex-group function: see 17.2 fn:regex-group.
The output state: this is a flag whose two possible values are final output state and temporary output state. The initial setting when the stylesheet is invoked by executing a template is final output state, and it is switched to temporary output state by instructions such as xsl:variable. For more details, see 25.2 Restrictions on the use of xsl:result-document.
The current output URI: this is the URI associated with the result tree to which instructions are currently writing. The current output URI is initially the same as the base output URI. During the evaluation of an xsl:result-document instruction, the current output URI is set to the absolute URI identified by the href attribute of that instruction.
The following non-normative table summarizes the initial state of each of the components in the evaluation context, and the instructions which cause the state of the component to change.
[Definition: The initial setting of a component of the dynamic context is used when evaluating global variables and stylesheet parameters, when evaluating the use and match attributes of xsl:key, and when evaluating the initial-value of xsl:accumulator and the select expressions or contained sequence constructors of xsl:accumulator-rule].
[Definition: The term non-contextual function call is used to refer to function calls that do not pass the dynamic context to the called function. This includes all calls on stylesheet functions and all [TERMDEF dt-dynamic-function-invocation IN XP40]dynamic function invocations, (that is calls to function items as permitted by XPath 3.0). It excludes calls to some functions in the namespace http://www.w3.org/2005/xpath-functions, in particular those that explicitly depend on the context, such as the current-group and regex-group functions. It is implementation-defined whether, and under what circumstances, calls to extension functions are non-contextual.]
Named function references (such as position#0) and calls on function-lookup (for example, function-lookup("position", 0)) are defined to retain the XPath static and dynamic context at the point of invocation as part of the closure of the resulting function item, and to use this preserved context when a dynamic function call is subsequently made using the function item. This rule does not extend to the XSLT extensions to the dynamic context defined in this section. If a dynamic function call is made that depends on the XSLT part of the dynamic context (for example, regex-group#1(2)), then the relevant components of the context are cleared as described in the table above.
In XSLT 4.0, patterns can match any kind of item: atomic items and function items as well as nodes.
A template rule identifies the items to which it applies by means of a pattern. As well as being used in template rules, patterns are used for numbering (see 12 Numbering), for grouping (see 14 Grouping), and for declaring keys (see 20.2 Keys).
[Definition: A pattern specifies a set of conditions on an item. An item that satisfies the conditions matches the pattern; an item that does not satisfy the conditions does not match the pattern.]
There are three kinds of pattern: predicate patterns, type patterns, and node patterns:
[Definition: A predicate pattern is written as . (dot) followed by zero or more predicates in square brackets, and it matches any item for which each of the predicates evaluates to true.]
A predicate pattern .[P1][P2]... can be regarded as an abbreviation for the type pattern type(item())[P1][P2]....
The detailed semantics are given in 5.4.2.1 Predicate Patterns. This construct can be used to match items of any kind (nodes, atomic items, and function items). For example, the pattern .[starts-with(., '$')] matches any string that starts with the character $, or a node whose atomized value starts with $. This example shows a predicate pattern with a single predicate, but the grammar allows any number of predicates (zero or more).
[Definition: A type pattern can be written as type(T) (where T is an ItemTypeXP followed by zero or more predicates in square brackets, and it matches any item of type T which each of the predicates evaluates to true.]
The parameter T can also be a list of item types, separated by "|". For example, type(array(*) | map(*)) matches arrays and maps, while type(text() | comment()) matches text nodes and comment nodes.
The most commonly used type patterns can be abbreviated. For example, match="type(record(F1, F2, *))" can be abbrevated to match="record(F1, F2, *)", and match="type(array(xs:string))" can be abbreviated to match="array(xs:string)". The main case where such abbreviation is not possible is with atomic items: match="type(xs:date)" cannot be abbreviated because a bare QName is interpreted as a node pattern, matching elements named xs:date. The pattern match="type(text() | comment())" has almost the same effect as match="text() | comment()", except that the rules for calculating a default priority are different.
[Definition: A node pattern uses a subset of the syntax for path expressions, and is defined to match a node if the corresponding path expression would select the node. Node patterns may also be formed by combining other patterns using union, intersection, and difference operators.]
The syntax for node patterns (UnionExprP in the grammar: see 5.4.2 Syntax of Patterns) is a subset of the syntax for expressions. Node patterns are used only for matching nodes; an item other than a node will never match a node pattern. As explained in detail below, a node matches a node pattern if the node can be selected by deriving an equivalent expression, and evaluating this expression with respect to some possible context.
Note:
The specification uses the phrases an item matches a pattern and a pattern matches an item interchangeably. They are equivalent: an item matches a pattern if and only if the pattern matches the item.
Here are some examples of patterns:
Predicate Patterns:
. matches any item.
.[. castable as xs:date] matches any item that can be successfully cast to xs:date: for example, an xs:date or xs:dateTime value, or a string in the lexical form of a date, or a node whose typed value is an xs:date or a string in the form of a date.
.[string() => matches('^[0-9]$')] matches any item whose string value is a sequence of digits.
.[. castable as xs:date][xs:date(.) le current-date()] matches any item that is castable to xs:date provided that the result of casting the value to xs:date is a date in the past.
Type Patterns
type(item()) matches any item.
type(node()) matches any node. (Note the distinction from the pattern node().)
type(xs:date) matches any atomic item of type xs:date (or a type derived by restriction from xs:date).
type(xs:date)[. gt current-date()] matches any date in the future.
type(xs:string)[starts-with(., 'e')] matches any xs:string value that starts with the letter e. Note there is no type conversion; the pattern will not match an xs:untypedAtomic or xs:anyURI value, nor will it match any node.
type(fn(*)) matches any function item.
type(fn($x as xs:integer) as xs:boolean)[.(42)] matches any function that accepts an xs:integer argument and returns a boolean result, provided that the result of calling the function with the argument value 42 is true.
type(xs:date | xs:dateTime | xs:time) matches any atomic item that is an instance of xs:date, xs:dateTime, or xs:time.
type(array(xs:date) | array(xs:dateTime) | array(xs:time)) matches any array whose members are all of type xs:date, any array whose members are all of type xs:dateTime, or any array whose members are all of type xs:time.
type(map((xs:string|xs:untypedAtomic), *) matches any map whose keys are all instances of xs:string or xs:untypedAtomic.
enum("red", "green", "blue") matches any one of the three strings "red", "green", or "blue".
record(first, last, *)[?location = 'UK'] matches any map whose keys include the strings "first" and "last", and that also has an entry with key "location" whose value is "UK".
record(longitude, latitude) matches any map with two entries whose keys are the strings "longitude" and "latitude".
array(xs:integer)[array:size(.) eq 4] matches any array of four integers.
array(record(first, last, *)) matches any array of maps where each map contains entries with keys "first" and "last". (Note that this includes the empty array).
array(record(first, last, *))[array:size(.) gt 0] matches any non-empty array of maps where each map contains entries with keys "first" and "last".
type(complex) matches any value that is an instance of the item type declared in an xsl:item-type or xsl:record-type declaration with name "complex"
type(complex)[?i eq 0] matches any value that is an instance of the item type declared in an xsl:item-type or xsl:record-type declaration with name "complex" and that is a map with an entry having key i and value zero.
Node Patterns
* matches any element.
para matches any para element.
chapter|appendix matches any chapter element and any appendix element.
child::(chapter|appendix) matches any chapter element and any appendix element. Note that although the child axis is explicitly written, an element can match even though it has no parent.
olist/entry matches any entry element with an olist parent.
appendix//para matches any para element with an appendix ancestor element.
appendix/descendant::(para|table) matches any para or tableelement with an appendix ancestor element.
schema-element(us:address) matches any element that is annotated as an instance of the type defined by the schema element declaration us:address, and whose name is either us:address or the name of another element in its substitution group.
attribute(*, xs:date) matches any attribute annotated as being of type xs:date.
/ matches a document node.
document-node() matches a document node.
document-node(schema-element(my:invoice)) matches the document node of a document whose document element is named my:invoice and matches the type defined by the global element declaration my:invoice.
text() matches any text node.
namespace-node() matches any namespace node.
node() matches any node other than an attribute node, namespace node, or document node.
id("W33") matches the element with unique ID W33.
para[1] matches any para element that is the first para child element of its parent. It also matches a parentless para element.
//para matches any para element in a tree that is rooted at a document node.
bullet[position() mod 2 = 0] matches any bullet element that is an even-numbered bullet child of its parent.
div[@class="appendix"]//p matches any p element with a div ancestor element that has a class attribute with value appendix.
@class matches any class attribute (not any element that has a class attribute).
@(class|type|kind) matches any attribute named class or type or kind.
@* matches any attribute node.
$xyz matches any node that is present in the value of the variable $xyz.
$xyz//* matches any element that is a descendant of a node that is present in the value of the variable $xyz.
doc('product.xml')//* matches any element within the document whose document URI is product.xml.
[ERR XTSE0340] Where an attribute is defined to contain a pattern, it is a static error if the pattern does not match the production Pattern40.
The complete grammar for patterns is listed in E Pattern Syntax Summary. It uses the notation defined in Section A.1.1 NotationXP.
The lexical rules for patterns are the same as the lexical rules for XPath expressions, as defined in Section A.3 Lexical structureXP. Comments are permitted between tokens, using the syntax (: ... :). All other provisions of the XPath grammar apply where relevant, for example the rules for whitespace handling and extra-grammatical constraints.
Pattern40 | ::= | PredicatePattern | TypePattern | NodePattern |
PredicatePattern | ::= | "." PredicateXP* |
TypePattern | ::= | (WrappedItemTest | AnyItemTestXP | FunctionTypeXP | MapTypeXP | ArrayTypeXP | RecordTypeXP | EnumerationTypeXP) PredicateXP* |
NodePattern | ::= | UnionExprP |
Patterns fall into three groups:
A PredicatePattern matches items according to conditions that the item must satisfy: for example .[. castable as xs:integer] matches any value (it might be an atomic item, a node, or an array) that is castable as an integer.
A TypePattern matches items according to their type. For example type(xs:integer) matches an atomic item that is an instance of xs:integer, while record(longitude, latitude) matches a map that has exactly two entries, with keys "longitude" and "latitude"
A NodePattern matches nodes in a tree, typically by specifying a path that can be used to locate the nodes: for example order matches an element node named order, while billing-address/city matches an element named city whose parent node is an element named billing-address.
The following sections define the rules for each of these groups.
PredicatePattern | ::= | "." PredicateXP* |
Predicate | ::= | "[" ExprXP "]" |
Expr | ::= | (ExprSingleXP ++ ",") |
ExprSingle | ::= | ForExprXP| LetExprXP| QuantifiedExprXP| IfExprXP |
ForExpr | ::= | ForClauseXPForLetReturnXP |
ForClause | ::= | "for" (ForBindingXP ++ ",") |
ForLetReturn | ::= | ForExprXP | LetExprXP | ("return" ExprSingleXP) |
LetExpr | ::= | LetClauseXPForLetReturnXP |
LetClause | ::= | "let" (LetBindingXP ++ ",") |
QuantifiedExpr | ::= | ("some" | "every") (QuantifierBindingXP ++ ",") "satisfies" ExprSingleXP |
QuantifierBinding | ::= | VarNameAndTypeXP "in" ExprSingleXP |
IfExpr | ::= | "if" "(" ExprXP ")" (UnbracedActionsXP | BracedActionXP) |
UnbracedActions | ::= | "then" ExprSingleXP "else" ExprSingleXP |
BracedAction | ::= | EnclosedExprXP |
A PredicatePatternPP matches an item J if and only if the XPath expression taking the same form as PP returns a non-empty sequence when evaluated with a singleton focus based on J.
Note:
The pattern ., which is a PredicatePattern with no predicates, matches every item.
A predicate with the numeric value 1 (one) always matches, and a predicate with any other numeric value never matches. Numeric predicates in a PredicatePattern are therefore not useful, but are defined this way in the interests of consistency with XPath.
For example, the pattern .[contains(., "XSLT")] matches any item whose atomized value contains "XSLT" as a substring. It matches values such as the string "XSLT Transformations", the xs:anyURI value http://www.w3.org/TR/XSLT, the attribute node class="XSD XSLT XPath", and the singleton array [ "XSLT 4.0" ].
Note:
Evaluation of this example pattern may fail with a dynamic error if the item in question has an atomized value that is not a string, or that is a sequence of strings: an example might be the array [ "XSLT", 1999 ]. It will also fail if the item cannot be atomized, for example if it is a map. The rules in 5.4.3 Errors in Patterns cause these errors to be masked: they simply result in the pattern being treated as non-matching.
Patterns (especially those used in template rules) can now be defined by reference to item types, so any item type can be used as a match pattern. For example match="record(longitude, latitude, *)" matches any map that includes the key values "longitude" and "latitude". [Issue 400 PR 401 21 March 2023]
TypePattern | ::= | (WrappedItemTest | AnyItemTestXP | FunctionTypeXP | MapTypeXP | ArrayTypeXP | RecordTypeXP | EnumerationTypeXP) PredicateXP* |
WrappedItemTest | ::= | "type" ChoiceItemTypeXP |
ChoiceItemType | ::= | "(" (ItemTypeXP ++ "|") ")" |
ItemType | ::= | RegularItemTypeXP | FunctionTypeXP | TypeNameXP | ChoiceItemTypeXP |
RegularItemType | ::= | AnyItemTestXP | NodeKindTestXP | GNodeTypeXP | JNodeTypeXP | MapTypeXP | ArrayTypeXP | RecordTypeXP | EnumerationTypeXP |
AnyItemTest | ::= | "item" "(" ")" |
NodeKindTest | ::= | DocumentTestXP| ElementTestXP| AttributeTestXP| SchemaElementTestXP| SchemaAttributeTestXP| PITestXP| CommentTestXP| TextTestXP| NamespaceNodeTestXP| AnyNodeKindTestXP |
GNodeType | ::= | "gnode" "(" ")" |
JNodeType | ::= | "jnode" "(" SequenceTypeXP? ")" |
MapType | ::= | AnyMapTypeXP | TypedMapTypeXP |
ArrayType | ::= | AnyArrayTypeXP | TypedArrayTypeXP |
RecordType | ::= | AnyRecordTypeXP | TypedRecordTypeXP |
EnumerationType | ::= | "enum" "(" (StringLiteralXP ++ ",") ")" |
FunctionType | ::= | AnyFunctionTypeXP| TypedFunctionTypeXP |
AnyFunctionType | ::= | ("function" | "fn") "(" "*" ")" |
TypedFunctionType | ::= | ("function" | "fn") "(" (TypedFunctionParamXP ** ",") ")" "as" SequenceTypeXP |
TypeName | ::= | EQNameXP |
EQName | ::= | QName | URIQualifiedNameXP |
TypedFunctionParam | ::= | ("$" EQNameXP "as")? SequenceTypeXP |
URIQualifiedName | ::= | BracedURILiteralNCName |
| /* ws: explicit */ | ||
SequenceType | ::= | ("empty-sequence" "(" ")")| (ItemTypeXPOccurrenceIndicatorXP?) |
OccurrenceIndicator | ::= | "?" | "*" | "+" |
| /* xgs: occurrence-indicators */ | ||
AnyMapType | ::= | "map" "(" "*" ")" |
TypedMapType | ::= | "map" "(" ItemTypeXP "," SequenceTypeXP ")" |
AnyArrayType | ::= | "array" "(" "*" ")" |
TypedArrayType | ::= | "array" "(" SequenceTypeXP ")" |
AnyRecordType | ::= | "record" "(" "*" ")" |
TypedRecordType | ::= | "record" "(" (FieldDeclarationXP ** ",") ExtensibleFlagXP? ")" |
FieldDeclaration | ::= | FieldNameXP "?"? ("as" SequenceTypeXP)? |
FieldName | ::= | NCNameXP | StringLiteralXP |
StringLiteral | ::= | AposStringLiteral | QuotStringLiteral |
| /* ws: explicit */ | ||
ExtensibleFlag | ::= | "," "*" |
AposStringLiteral | ::= | "'" (EscapeApos | [^'])* "'" |
| /* ws: explicit */ | ||
QuotStringLiteral | ::= | '"' (EscapeQuot | [^"])* '"' |
| /* ws: explicit */ | ||
Predicate | ::= | "[" ExprXP "]" |
Expr | ::= | (ExprSingleXP ++ ",") |
ExprSingle | ::= | ForExprXP| LetExprXP| QuantifiedExprXP| IfExprXP |
ForExpr | ::= | ForClauseXPForLetReturnXP |
ForClause | ::= | "for" (ForBindingXP ++ ",") |
ForLetReturn | ::= | ForExprXP | LetExprXP | ("return" ExprSingleXP) |
LetExpr | ::= | LetClauseXPForLetReturnXP |
LetClause | ::= | "let" (LetBindingXP ++ ",") |
QuantifiedExpr | ::= | ("some" | "every") (QuantifierBindingXP ++ ",") "satisfies" ExprSingleXP |
QuantifierBinding | ::= | VarNameAndTypeXP "in" ExprSingleXP |
IfExpr | ::= | "if" "(" ExprXP ")" (UnbracedActionsXP | BracedActionXP) |
UnbracedActions | ::= | "then" ExprSingleXP "else" ExprSingleXP |
BracedAction | ::= | EnclosedExprXP |
A type pattern tests whether an item matches a given item type, optionally qualified with one or more predicates that the value must also satisfy.
The general-purpose construct type(ItemType) allows any ItemType to be used in a pattern. Where syntactic constraints permit, many ItemTypes can also be used directly: for example type(item()) can be abbreviated as item().
For example:
type(xs:integer) matches any instance of xs:integer
type(xs:integer)[. gt 0] matches any positive integer.
type(xs:string | xs:untypedAtomic)[matches(., '[0-9]+')] matches any instance of xs:string or xs:untypedAtomic that contains a sequence of decimal digits.
type(node()) matches any node. (This is not the same as the pattern node(), which for historical reasons only matches element, text, comment, and processing instruction nodes).
More formally, an item $J matches a pattern type(T)[P1][P2][P3] if the XPath expression $J instance of T and exists($J[P1][P2][P3]) is true.
Note:
As with predicate patterns, numeric predicates are allowed, but serve no useful purpose.
A pattern written as record(A, B, C) is an abbreviation for type(record(A, B, C)) (retaining any predicates). For example, the pattern record(first, last, *)[?first eq "Sharon"] matches any map having entries with the string-valued keys "first" and "last", where the entry for the key "first" is equal to the string "Sharon".
Note:
The item type in a pattern can be any ItemType, but patterns that match nodes can usually be expressed more economically as a NodeTest: for example match="type(element(PERSON))" has the same meaning as match="element(PERSON)", which in turn is usually abbreviated to match="PERSON".
Although match="type(element(PERSON))" matches exactly the same items as match="PERSON", the priority relative to other template rules (in the absence of an explicit priority attribute) may be different.
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]
The semantics of patterns using the intersect and except operators have been changed to reflect the intuitive meaning: for example a node now matches A except B if it matches A and does not match B. [Issue 402 ]
NodePattern | ::= | UnionExprP |
UnionExprP | ::= | IntersectExceptExprP (("union" | "|") IntersectExceptExprP)* |
IntersectExceptExprP | ::= | PathExprP (("intersect" | "except") PathExprP)* |
PathExprP | ::= | RootedPath| ("/" RelativePathExprP?)| ("//" RelativePathExprP)| RelativePathExprP |
| /* xgs: leading-lone-slash */ | ||
RootedPath | ::= | VarRefXPPredicateXP* (("/" | "//") RelativePathExprP)? |
VarRef | ::= | "$" EQNameXP |
Predicate | ::= | "[" ExprXP "]" |
RelativePathExprP | ::= | StepExprP (("/" | "//") StepExprP)* |
StepExprP | ::= | PostfixExprP | AxisStepP |
Node Patterns are used to match XDM nodes.
The names of these constructs are chosen to align with the XPath 3.0 grammar. Constructs whose names are suffixed with P are restricted forms of the corresponding XPath 3.0 construct without the suffix. Constructs labeled with the suffix “XP40” are defined in [XPath 4.0].
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.
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 (/*)
The meaning of a node pattern is defined formally as follows, where “if” is to be read as “if and only if”.
A node matches a UnionExprPA union B (or equivalently, A | B) if it matches either A or B or both.
A node matches an IntersectExceptExprPA intersect B if it matches both A and B.
A node matches an IntersectExceptExprPA except B if it matches A and does not match B.
A node matches a PathExprP under the following conditions:
If the PathExprP consists in its entirety of a ParenthesizedExprP, then the node matches the ParenthesizedExprP if it matches the UnionExprP enclosed within the parentheses.
Otherwise, the PathExprP pattern is converted to an expression, called the equivalent expression. The equivalent expression to a PathExprP is the XPath expression that takes the same lexical form as the PathExprP as written, with the following adjustment:
If any PathExprP in the Pattern is a RelativePathExprP, then the first StepExprPPS of this RelativePathExprP is adjusted to allow it to match a parentless element, attribute, or namespace node. The adjustment depends on the axis used in this step, whether it appears explicitly or implicitly (according to the rules of Section 4.6.7 Abbreviated SyntaxXP), 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 node at all, XSLT 4.0 allows the pattern .[. instance of node()] to be used.
The meaning of the pattern is then defined in terms of the semantics of the equivalent expression, denoted below as EE.
Specifically, an item N matches a PathExprP pattern P if the following applies, where EE is the equivalent expression to P:
N is a node, and the result of evaluating the expression root(.)//(EE) with a singleton focus based on N is a sequence that includes the node N.
If a pattern appears in an attribute of an element that is processed with XSLT 1.0 behavior (see 3.9 Backwards Compatible Processing), then the semantics of the pattern are defined on the basis that the equivalent XPath expression is evaluated with XPath 1.0 compatibility mode set to true.
Note:
This version of the specification includes an incompatible change to the semantics of patterns using the intersect and except operators. This change is made to eliminate cases where the behavior defined in XSLT 3.0 was counter-intuitive.
Consider the pattern para except appendix//para. In XSLT 4.0 this matches any para element that is not the descendant of an appendix element. In XSLT 3.0 it would match the para element in the XML tree shown below:
<appendix> <section> <para/> </section> </appendix>
because there is an element $S (specifically, the section element), such that the expression $S//(para except appendix//para) selects this para element.
It is recommended that processors should report a compatibility warning when such constructs are encountered. The problem arises with patterns using intersect or except where one of the branches uses the descendant axis: it does not arise in simple cases like * except A, or @* except @code, where the branches only use the child or attribute axis.
The change does not affect the meaning of patterns that use the intersect or except operators nested within a path expression, for example a pattern such as A[.//C except B//C].
The node patternp matches any p element, because a p element will always be present in the result of evaluating the expressionroot(.)//(child-or-top::p). Similarly, / matches a document node, and only a document node, because the result of the expressionroot(.)//(/) returns the root node of the tree containing the context node if and only if it is a document node.
The node patternnode() matches all nodes selected by the expression root(.)//(child-or-top::node()), that is, all element, text, comment, and processing instruction nodes, whether or not they have a parent. It does not match attribute or namespace nodes because the expression does not select nodes using the attribute or namespace axes. It does not match document nodes because for backwards compatibility reasons the child-or-top axis does not match a document node.
Note:
The pattern type(node()) matches all nodes.
The node pattern$V matches all nodes selected by the expression root(.)//($V), that is, all nodes in the value of $V (which will typically be a global variable, though when the pattern is used in contexts such as the xsl:number or xsl:for-each-group instructions, it can also be a local variable).
The node patterndoc('product.xml')//product matches all nodes selected by the expression root(.)//(doc('product.xml')//product), that is, all product elements in the document whose URI is product.xml.
The node patternroot(.)/self::E matches an E element that is the root of a tree (that is, an E element with no parent node).
Although the semantics of node patterns are specified formally in terms of expression evaluation, it is possible to understand pattern matching using a different model. A node pattern such as book/chapter/section can be examined from right to left. A node will only match this pattern if it is a section element; and then, only if its parent is a chapter; and then, only if the parent of that chapter is a book. When the pattern uses the // operator, one can still read it from right to left, but this time testing the ancestors of a node rather than its parent. For example appendix//section matches every section element that has an ancestor appendix element.
The formal definition, however, is useful for understanding the meaning of a pattern such as para[1]. This matches any node selected by the expression root(.)//(child-or-top::para[1]): that is, any para element that is the first para child of its parent, or a para element that has no parent.
Note:
An implementation, of course, may use any algorithm it wishes for evaluating patterns, so long as the result corresponds with the formal definition above. An implementation that followed the formal definition by evaluating the equivalent expression and then testing the membership of a specific node in the result would probably be very inefficient.
Note:
Patterns using the intersect and except operators do not always have the intuitive meaning: in particular, it is not always the case that a node matches A except B if it matches A but does not match B.
For example, consider the pattern para except appendix//para. This expands to root(.)/descendant-or-self::node()/(child::para except child::appendix//para). Since for a given parent node, the results of child::para and child::appendix are disjoint, the right-hand operand of except has no effect.
The effect of matching all paragraphs except those within an appendix can be achieved using the pattern para except //appendix//para; alternatively, use para[not(ancestor::appendix)].
Simpler patterns such as @* except @code generally have the expected effect; the complications arise mainly when non-trivial relative paths are used.
A dynamic error or type error that occurs during the evaluation of a pattern against a particular item has the effect that the item being tested is treated as not matching the pattern. The error does not cause the transformation to fail, and cannot be caught by a try/catch expression surrounding the instruction that causes the pattern to be evaluated.
Note:
The reason for this provision is that it is difficult for the stylesheet author to predict which predicates in a pattern will actually be evaluated. In the case of match patterns in template rules, it is not even possible to predict which patterns will be evaluated against a particular node.
There is a risk that ignoring errors in this way may make programming mistakes harder to debug. Implementations may mitigate this by providing warnings or other diagnostics when evaluation of a pattern triggers an error condition.
Static errors in patterns, including dynamic and type errors that are raised statically as permitted by the specification, are raised in the normal way and cause the transformation to fail.
The requirement to detect and raise a circularity as a dynamic error overrides this rule.
XSLT 4.0 introduces two new and closely-related constructs allowing item types to be given names, and to be referred to by name anywhere that item types are used, for example in function declarations and variable declarations.
The xsl:item-type declaration allows any item type to be given a name. It is particularly useful to avoid repetitive use of the same choice types, enumeration types, or function types, and means that if the definition changes, the change only needs to be made in one place.
The xsl:record-type declaration takes this a step further. Like xsl:item-type, it allows a name to be given to any record type. In addition, though, it offers two further capabilities:
Named record types can be recursive, allowing definitions of recursive data structures such as lists and trees.
Declaring a named record type automatically establishes a constructor function for records of that type; the constructor function has the same name as the record type itself.
Named item types can be declared using the new xsl:item-type element. This is designed to avoid repeating lengthy type definitions (for example function types) every time they are used. [This feature was present in the editor's draft presented to the WG when it started work.] [ 1 January 2022]
<!-- Category: declaration -->
<xsl:item-type
name = eqname
as? = item-type〔'item()*'〕
visibility? = "private" | "public"〔'private'〕 />
An xsl:item-type declaration associates a name with an item type, and allows the type to be referenced by name throughout the stylesheet package.
The following example declares a named item type for colors, and uses it in three variable declarations and a function declaration.
<xsl:item-type name="my:color" as="enum('red', 'green', 'blue')"/> <xsl:variable name="RED" as="my:color" select="'red'"/> <xsl:variable name="GREEN" as="my:color" select="'green'"/> <xsl:variable name="BLUE" as="my:color" select="'blue'"/> <xsl:function name="my:html-color" as="xs:string"> <xsl:param name="color" as="my:color"/> <xsl:switch select="$color"> <xsl:when test="$RED">#FF0000</xsl:when> <xsl:when test="$GREEN">#008000</xsl:when> <xsl:when test="$BLUE">#0000FF</xsl:when> </xsl:switch> </xsl:function>
The following example declares a named choice type for the two binary types xs:hexBinary and xs:base64Binary and uses it in a function declaration that compares two such values for equality.
<xsl:item-type name="my:binary" as="(xs:hexBinary | xs:base64Binary)"/> <xsl:function name="my:binary-equal" as="xs:boolean"> <xsl:param name="x" as="my:binary"/> <xsl:param name="y" as="my:binary"/> <xsl:sequence select="$x eq $y"/> </xsl:function>
Using named item types makes the stylesheet more readable, and improves potential for change: a change to the set of colors allowed by the type my:color is less likely to affect users of a function library. However, named item types do not provide true encapsulation or information hiding; users of the function library can still treat enumeration values as simple strings if they wish.
The xsl:item-type declaration adds an entry to the in-scope named item typesXP component of the static context for XPath expressions, and also becomes available for use wherever XSLT allows an ItemType to appear.
The scope of a named item type is the package in which it is declared. If it is declared with visibility="public" then it also becomes available for use in using packages. (Since there is no mechanism for the using package to override the definition, public effectively means final.)
A named item type is essentially an abbreviation for the item type designator appearing in the as attribute, and the semantics can be defined in terms of textual replacement of the name by its definition. In consequence, named item types cannot be recursive, since this would make the textual expansion non-terminating.
The name of the item type is the expanded name formed by resolving the name attribute. A lexical QName with no prefix is treated as being in the default namespace for elements and typesXP.
If two xsl:item-type declarations in a package have the same name, then the one with higher import precedence is used.
[ERR XTSE4030] It is a static error if a package contains two xsl:item-type or xsl:record-type declarations having the same name and the same import precedence, unless there is another definition with the same name and higher import precedence. It is also a static error if the name of the item type uses a reserved namespace, or if it has the same name as a type in the in-scope schema typesXP of the static context.
[ERR XTSE4035] It is a static error for an item type named N to contain in its as attribute a reference to N, or to an item type that references N directly or indirectly.
It is permissible to use a private named item type in the declaration of a public variable, function, or template. A package that uses (or overrides) such a component will not be able to use the type name, but it can use the underlying type definition, or provide its own declaration of the relevant item type, using the same name or a different name.
<!-- Category: declaration -->
<xsl:record-type
name = eqname
constructor? = boolean〔'no'〕
extensible? = boolean〔'no'〕
visibility? = "private" | "public"〔'private'〕 >
<!-- Content: (xsl:field*) -->
</xsl:record-type>
<xsl:field
name = ncname
as? = sequence-type〔'item()*'〕
required? = boolean〔'yes'〕
default? = expression />
An xsl:record-type declaration associates a name with a record type, and allows the record type to be referenced by name throughout the stylesheet package.
The following example declares a named record type for complex numbers, and uses it in a variable declaration and a function declaration.
<xsl:record-type name="cx:complex"> <xsl:field name="r" as="xs:double"/> <xsl:field name="i" as="xs:double"/> </xsl:record-type> <xsl:variable name="i" as="cx:complex" select="cx:complex(0, 1)"/> <xsl:function name="cx:add" as="cx:complex"> <xsl:param name="x" as="cx:complex"/> <xsl:param name="y" as="cx:complex"/> <xsl:sequence select="cx:complex($x?r + $y?r, $x?i + $y?i)"/> </xsl:function>
Note how the record type declaration has implicitly declared a constructor function cx:complex that can be used to create instances of the item type.
[ERR XTSE4050] It is a static error if the names of the fields in an xsl:record-type declaration are not distinct.
[ERR XTSE4051] It is a static error if an xsl:field element has a default attribute unless it specifies required="no".
An xsl:record-type declaration has two effects:
In the same way as xsl:item-type, it defines a named item type in the static context, allowing the record type to be referenced by name anywhere an ItemType can appear, for example in the declarations of functions and variables. Unlike types declared in xsl:item-type, however, named record types can be recursive.
An xsl:record-type declaration also implicitly defines a constructor function, of the same name, and adds this to the set of statically known function definitionsXP in the static context.
Because of its dual role, the name of an xsl:record-type declaration must be valid both as an item type name and as a function name. This means the name must be distinct from other type names and function names in the static context. It also means that the name must be in a namespace.
Considered as an item type, the xsl:record-type declaration is equivalent to an xsl:item-type declaration formed by the following template rule, evaluated in the context of a namespace alias <xsl:namespace-alias stylesheet-prefix="t" result-prefix="xsl"/>:
<xsl:template match="xsl:record-type" expand-text="yes"> <t:item-type name="{@name}" visibility="{@visibility otherwise 'private'}"> <xsl:attribute name="as"> <xsl:text>record(</xsl:text> <xsl:for-each select="xsl:field" separator=", "> <xsl:variable name="optional" as="xs:boolean" select="normalize-space(@required) = ('no','false','0')"/> {@name}{'?'[$optional]} as {@as otherwise 'item()*'} </xsl:for-each> <xsl:if test="normalize-space(@extensible) = ('yes','true','1')"> <xsl:text>, *</xsl:text> </xsl:if> <xsl:text>)</xsl:text> </xsl:attribute> </t:item-type> </xsl:template>
This generated xsl:item-type declaration must meet all the constraints placed on user-written xsl:item-type declarations, including the rule requiring names to be unique, but not including the rule disallowing recursive references.
For example, the declaration:
<xsl:record-type name="cx:complex" extensible="yes"> <xsl:field name="r" as="xs:double"/> <xsl:field name="i" as="xs:double" required="no" default="0"/> </xsl:record-type>
produces the equivalent item type declaration:
<xsl:item-type name="cx:complex" as="record(r as xs:double, i? as xs:double, *)"/>
Considered as a function declaration, an xsl:record-type declaration is equivalent to an xsl:function declaration formed by the following template rule, evaluated in the context of a namespace alias <xsl:namespace-alias stylesheet-prefix="t" result-prefix="xsl"/>:
<xsl:template match="xsl:record-type"> <t:function name="{@name}" as="{@name}" visibility="{(@visibility otherwise 'private')}"> <!-- if the record type is extensible, choose a name for the options parameter --> <xsl:variable name="options-param" as="xs:string?"> <xsl:if test="normalize-space(@extensible) = ('yes', 'true', 'a')" then="('options', (1 to count(xsl:field)) ! `options{.}`) [not(. = current()/xsl:field/@name)][1]"/> </xsl:variable> <!-- declare the parameters --> <xsl:for-each select="xsl:field"> <t:param name="{@name}" required="{@required otherwise 'yes'}"> <xsl:attribute name="as"> <xsl:variable name="as" select="normalize-space(@as otherwise 'item()*')"/> <xsl:variable name="optional" select="normalize-space(@required) = ('no', 'false', '0')"/> <xsl:choose> <xsl:when test="not($optional)" select="$as"/> <!-- for optional fields, amend the required type to allow () --> <xsl:when test="matches($as, '[?*]$')" select="$as"/> <xsl:when test="matches($as, '\+$')" select="replace($as, '\+$', '*')"/> <xsl:otherwise select="$as || '?'"/> </xsl:choose> </xsl:attribute> <xsl:if test="@default"> <xsl:attribute name="select" select="@default"/> </xsl:if> </t:param> </xsl:for-each> <!-- for an extensible record type, declare the options parameter --> <xsl:if test="exists($options-param)"> <t:param name="{$options-param}" as="map(*)" required="no" select="{}"/> </xsl:if> <!-- function body: construct a map --> <t:map duplicates="fn($first, $second){{$first}}"> <xsl:for-each select="xsl:field"> <xsl:variable name="optional" select="normalize-space(@required) = ('no', 'false', '0')"/> <xsl:choose> <xsl:when test="$optional and not(@default)"> <!-- omit map entries for optional fields if no value is supplied --> <t:if test="exists(${@name})"> <t:map-entry key="'{@name}'" select="${@name}"/> </t:if> </xsl:when> <xsl:otherwise> <t:map-entry key="'{@name}'" select="${@name}"/> </xsl:otherwise> </xsl:choose> </xsl:for-each> <!-- if the record type is extensible, add entries from the options parameter --> <xsl:if test="exists($options-param)"> <t:sequence select="${$options-param}"/> </xsl:if> </t:map> </t:function> </xsl:template>
For example, the declaration:
<xsl:record-type name="cx:complex"> <xsl:field name="r" as="xs:double"/> <xsl:field name="i" as="xs:double" required="no" default="0"/> </xsl:record-type>
produces the equivalent function declaration:
<xsl:function name="cx:complex" as="cx:complex" visibility="private"> <xsl:param name="r" as="xs:double"/> <xsl:param name="i" as="xs:double" required="no" select="0"/> <xsl:map> <xsl:map-entry key="'r'" select="$r"/> <xsl:map-entry key="'i'" select="$i"/> </xsl:map> </xsl:function>
No entry is generated in the constructed map for a field that is declared as optional with no default. So the declaration:
<xsl:record-type name="cx:complex" visibility="public"> <xsl:field name="r" as="xs:double"/> <xsl:field name="i" as="xs:double" required="no"/> </xsl:record-type>
produces the equivalent function declaration:
<xsl:function name="cx:complex" as="cx:complex" visibility="public"> <xsl:param name="r" as="xs:double"/> <xsl:param name="i" as="xs:double?" required="no"/> <xsl:map> <xsl:map-entry key="'r'" select="$r"/> <xsl:if test="exists($i)"> <xsl:map-entry key="'i'" select="$i"/> </xsl:if> </xsl:map> </xsl:function>
If the record type is extensible, the generated function includes an optional options parameter So the declaration:
<xsl:record-type name="cx:complex" extensible="yes"> <xsl:field name="r" as="xs:double"/> <xsl:field name="i" as="xs:double"/> </xsl:record-type>
produces the equivalent function declaration:
<xsl:function name="cx:complex" as="cx:complex" visibility="private"> <xsl:param name="r" as="xs:double"/> <xsl:param name="i" as="xs:double"/> <xsl:param name="options" as="map(*)" required="no" default="{}"/> <xsl:map duplicates="fn($first, $second){$first}"> <xsl:map-entry key="'r'" select="$r"/> <xsl:map-entry key="'i'" select="$i"/> <xsl:sequence select="$options"/> </xsl:map> </xsl:function>
This generated xsl:function declaration must meet all the constraints placed on user-written xsl:function declarations, including the rule requiring the combination of name and arity to be unique.
The generated xsl:function declaration has the import precedence associated with the stylesheet module in which the xsl:record-type declaration appears, and it may be overridden by another xsl:function declaration with higher import precedence. If the visibility is public then it can also be overridden using xsl:override in another package.
The scope of a named record type is the package in which it is declared. If it is declared with visibility="public" then it also becomes available for use in using packages.
The name of the record type is the expanded name formed by resolving the name attribute. Because function names are always in a namespace, the name must be prefixed.
If two xsl:record-type declarations in a package have the same name, then the one with higher import precedence is used.
A record type declaration may refer directly or indirectly to itself if it satisfies the conditions defined in Section 3.2.8.3.1 Recursive Record TypesXP. This allows types to be declared that match recursive data structures such as linked lists and trees.
A named record type with visibility private may be used in the definition of a component (such as a variable, a function, a template, or another named record type) that is itself public. Another package may reference such a component even though it cannot reference the types used in its definition. The fact that the record type is private, however, means that it is impossible to override a variable or function that references the record type.
This example illustrates the definition of a recursive record type. The record type represents a node of a binary tree containing a payload value in each node, together with optional references to left and right subtrees. As well as the data fields, the record type defines a depth function that returns the maximum depth of the tree, by making recursive calls on its subtrees.
<xsl:record-type name="my:binary-tree"> <xsl:field name="left" as="my:binary-tree?"/> <xsl:field name="payload" as="item()*"/> <xsl:field name="right" as="my:binary-tree?"/> <xsl:field name="depth" as="%method fn(my:binary-tree) as xs:integer" default="%method fn() {1 + max((?left ? depth(), ?right ? depth())) otherwise 0)}"/> </xsl:record-type>
The %method annotation is described in Section 4.5.6.1 MethodsXP. Its effect is to give a function item contained in a map access to the containing map. It thus mimics method invocation in object-oriented languages, though there is no inheritance or encapsulation.
The following code builds a simple tree and calculates its depth:
let $tree := my:binary-tree(
my:binary-tree((), 17, ()),
18,
my:binary-tree((), 19,
my:binary-tree((), 20, ())))
return $tree =?> depth()Returning the result 3.
A more detailed example that uses a recursive named record type appears in the following section.
This example demonstrates a library package that provides a new data type to manipulate sets of atomic items.
A stylesheet that incorporates this package (by referencing it in an xsl:use-package declaration) can use constructs such as:
<xsl:variable name="empty" as="set:atomic-set" select="set:build(())"/>
<xsl:variable name="evens" as="set:atomic-set" select="set:build((1 to 100)[. mod 2 = 0])"/>
<xsl:variable name="odds" as="set:atomic-set" select="set:build((1 to 100)) ? except($evens)"/>
<xsl:function name="my:is-even" as="xs:boolean"> <xsl:param name="n" as="xs:integer"/> <xsl:sequence select="$evens ? contains($n)"/> </xsl:function>
Here is the implementation of the package. It relies heavily on the use of the function annotation %method, which gives a function item contained in a map access to the containing map: methods are described in Section 4.5.6.1 MethodsXP.
<xsl:package name="http://qt4cg.org/atomic-set" package-version="1.0.0" xmlns:set="http://qt4cg.org/atomic-set" xmlns:map="http://www.w3.org/2005/xpath-functions/map" xmlns:xs="http://www.w3.org/2001/XMLSchema"> <xsl:note> This package defines a type set:atomic-set which represents a set of distinct atomic items. Atomic items are considered distinct based on the comparison function fn:atomic-equal. An instance of an atomic set can be constructed using a function call such as set:build((1, 3, 5, 7, 9)). If $A and $B are instances of set:atomic-set, then they can be manipulated using methods including: $A?size() - returns the number of items in the set $A?empty() - returns true if the set is empty $A?contains($k) - determines whether $k is a member of the set $A?contains-all($B) - returns true if $B is a subset of $A $A?values() - returns the items in $A, as a sequence $A?add($k) - returns a new atomic set containing an additional item $A?remove($k) - returns a new atomic set in which the given item is absent $A?union($B) - returns a new atomic set holding the union of $A and $B $A?intersect($B) - returns a new atomic set holding the intersection of $A and $B $A?except($B) - returns a new atomic set holding the difference of $A and $B </xsl:note> <xsl:record-type name="set:atomic-set" visibility="public" extensible="yes"> <xsl:field name="_data" as="map(xs:anyAtomicType, xs:boolean)"/> <xsl:field name="size" as="%method fn() as xs:integer"/> <xsl:field name="empty" as="%method fn() as xs:boolean"/> <xsl:field name="contains" as="%method fn($value as xs:anyAtomicType) as xs:boolean"/> <xsl:field name="contains-all" as="%method fn($value as set:atomic-set) as xs:boolean"/> <xsl:field name="add" as="%method fn($item as xs:anyAtomicType) as set:atomic-set"/> <xsl:field name="remove" as="%method fn($item as xs:anyAtomicType) as set:atomic-set"/> <xsl:field name="union" as="%method fn($value as set:atomic-set) as set:atomic-set"/> <xsl:field name="intersect" as="%method fn($value as set:atomic-set) as set:atomic-set"/> <xsl:field name="except" as="%method fn($value as set:atomic-set) as set:atomic-set"/> </xsl:record-type> <xsl:variable name="DATA" select="'_data'" visibility="private"/> <xsl:note> The private function set:replaceData processes the internal map by applying a supplied function, and returns a new atomic set with the resulting internal map </xsl:note> <xsl:function name="set:replaceData" visibility="private" as="map(xs:anyAtomicType, xs:boolean)"> <xsl:param name="input" as="set:atomic-set"/> <xsl:param name="update" as="fn(map(*)) as map(*)"/> <xsl:sequence select="map:put($input, $DATA, $update($input?$DATA))"/> </xsl:function> <xsl:function name="set:build" as="set:atomic-set" visibility="public"> <xsl:param name="values" as="xs:anyAtomicType*" default="()"/> <xsl:record as="set:atomic-set" _data= "map:build($values, values:=true#0, {'duplicates': 'use-first'})" size= "%method fn() as xs:integer { map:size(?$DATA) }" empty= "%method fn() as xs:boolean { map:empty(?$DATA) }" contains= "%method fn($value as xs:anyAtomicType) as xs:boolean { map:contains(?$DATA, $value) }" contains-all= "%method fn($other as set:atomic-set) as xs:boolean { every($value, map:contains(?$DATA, ?)) }" values= "%method fn() as xs:anyAtomicType* { keys(?$DATA) }" add= "%method fn($value as xs:anyAtomicType) as xs:anyAtomicType* { set:replaceData(., map:put(?, $value, true())) }" remove= "%method fn($value as xs:anyAtomicType) as xs:anyAtomicType* { set:replaceData(., map:remove(?, $value)) }" union= "%method fn($other as set:atomic-set) as set:atomic-set { set:replaceData(., fn($this) {map:merge(($this, $other?$DATA), {'duplicates': 'use-first'})}) }" intersect= "%method fn($other as set:atomic-set) as set:atomic-set { set:replaceData(., map:filter(?, $other?contains)) }" except= "%method fn($other as set:atomic-set) as set:atomic-set { set:replaceData(., map:remove(?, $other?values())) }"/> </xsl:function> </xsl:package>
| Editorial note | |
The example is not yet tested. It could also be written using the new xsl:record instruction, which might be more concise. | |
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: 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: 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: 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.8.25.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: 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.75.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 or a child of an xsl:text instruction, (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: 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.75.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 or xsl:text instruction. 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 or xsl:text instruction, 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: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: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: 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.13.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.7.25.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.2 Extension Instructions) also produces a sequence of items as its result.
[Definition: The result of evaluating a sequence constructor is the sequence of items formed by concatenating the results of evaluating each of the nodes in the sequence constructor, retaining order. This is referred to as the immediate result of the sequence constructor.]
However:
For the effect of the xsl:fallback instruction, see 24.2.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.8.15.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.8.15.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:value-of, xsl:namespace, xsl:comment, or xsl:processing-instruction. For details, see 5.8.25.7.2 Constructing Simple Content.
Many instructions, for example xsl:copy, xsl:element, xsl:document, xsl:result-document, and literal result elements, create a new parent node, and evaluate a sequence constructor forming the content of the instruction to create the attributes, namespaces, and children of the new parent node. The immediate result of the sequence constructor is processed to create the content of the new parent node as described in this section.
When constructing the content of an element, the inherit-namespaces attribute of the xsl:element or xsl:copy instruction, or the xsl:inherit-namespaces property of the literal result element, determines whether namespace nodes are to be inherited. The effect of this attribute is described in the rules that follow.
The immediate result of the sequence constructor is processed as follows (applying the rules in the order they are listed):
The containing instruction may generate attribute nodes and/or namespace nodes, as specified in the rules for the individual instruction. For example, these nodes may be produced by expanding an [xsl:]use-attribute-sets attribute, or by expanding the attributes of a literal result element. Any such nodes are prepended to the immediate result of the sequence constructor.
Any array item in the sequence (see 22 Arrays) is replaced by its members, recursively. This is equivalent to applying the array:flatten function defined in [Functions and Operators 3.1].
Any atomic item in the sequence is cast to a string.
Note:
Casting from xs:QName or xs:NOTATION to xs:string always succeeds, because these values retain a prefix for this purpose. However, there is no guarantee that the prefix used will always be meaningful in the context where the resulting string is used.
Any consecutive sequence of strings in the sequence is converted to a single text node, whose string value contains the content of each of the strings in turn, with U+0020 (SPACE) used as a separator between successive strings.
Any document node within the sequence is replaced by a sequence containing each of its children, in document order.
Zero-length text nodes within the sequence are removed.
Adjacent text nodes within the sequence are merged into a single text node.
Invalid items in the sequence are detected as follows.
[ERR XTDE0410] It is a dynamic error if the sequence used to construct the content of an element node contains a namespace node or attribute node that is preceded in the sequence by a node that is neither a namespace node nor an attribute node.
[ERR XTDE0420] It is a dynamic error if the sequence used to construct the content of a document node contains a namespace node or attribute node.
[ERR XTDE0430] It is a dynamic error if the sequence contains two or more namespace nodes having the same name but different string values (that is, namespace nodes that map the same prefix to different namespace URIs).
[ERR XTDE0440] It is a dynamic error if the sequence contains a namespace node with no name and the element node being constructed has a null namespace URI (that is, it is an error to define a default namespace when the element is in no namespace).
[ERR XTDE0450] It is a type error if the result sequence contains a function item.
Note:
The error code reflects the fact that this error was at one time classified as a dynamic error rather than a type error. [XSLT 3.0 Erratum E17, bug 30223].
If the sequence contains two or more namespace nodes with the same name (or no name) and the same string value (that is, two namespace nodes mapping the same prefix to the same namespace URI), then all but one of the duplicate nodes are discarded.
Note:
Since the order of namespace nodes is implementation-dependent, it is not significant which of the duplicates is retained.
If an attribute A in the sequence has the same name as another attribute B that appears later in the sequence, then attribute A is discarded from the sequence. Before discarding attribute A, the processor may raise any type errors that would be raised if attribute B were not present.
Each node in the resulting sequence is attached as a namespace, attribute, or child of the newly constructed element or document node. Conceptually this involves making a deep copy of the node; in practice, however, copying the node will only be necessary if the existing node can be referenced independently of the parent to which it is being attached. When copying an element or processing instruction node, its base URI property is changed to be the same as that of its new parent, unless it has an xml:base attribute (see [XML Base]) that overrides this. If the copied element has an xml:base attribute, its base URI is the value of that attribute, resolved (if it is relative) against the base URI of the new parent node.
Except for the handling of base URI, the copying of a node follows the rules of the xsl:copy-of instruction with attributes copy-namespaces="yes" copy-accumulators="no" validation="preserve".
Note:
This has the consequence that the type annotation and the values of the nilled, is-id, and is-idrefs properties are retained. However, if the node under construction (the new parent of the node being copied) uses a validation mode other than preserve, this will be transient: the values will be recomputed when the new parent node is validated.
If the newly constructed node is an element node, then namespace fixup is applied to this node, as described in 5.8.35.7.3 Namespace Fixup.
If the newly constructed node is an element node, and if namespaces are inherited, then each namespace node of the newly constructed element (including any produced as a result of the namespace fixup process) is copied to each descendant element of the newly constructed element, unless that element or an intermediate element already has a namespace node with the same name (or absence of a name) or that descendant element or an intermediate element is in no namespace and the namespace node has no name.
Consider the following stylesheet fragment:
<td> <xsl:attribute name="valign">top</xsl:attribute> <xsl:value-of select="@description"/> </td>
This fragment consists of a literal result element td, containing a sequence constructor that consists of two instructions: xsl:attribute and xsl:value-of. The sequence constructor is evaluated to produce a sequence of two nodes: a parentless attribute node, and a parentless text node. The td instruction causes a td element to be created; the new attribute therefore becomes an attribute of the new td element, while the text node created by the xsl:value-of instruction becomes a child of the td element (unless it is zero-length, in which case it is discarded).
Consider the following stylesheet fragment:
<doc> <e><xsl:sequence select="1 to 5"/></e> <f> <xsl:for-each select="1 to 5"> <xsl:value-of select="."/> </xsl:for-each> </f> </doc>
This produces the output (when indented):
<doc> <e>1 2 3 4 5</e> <f>12345</f> </doc>
The difference between the two cases is that for the e element, the sequence constructor generates a sequence of five atomic items, which are therefore separated by spaces. For the f element, the content is a sequence of five text nodes, which are concatenated without space separation.
It is important to be aware of the distinction between xsl:sequence, which returns the value of its select expression unchanged, and xsl:value-of, which constructs a text node.
The instructions xsl:attribute, xsl:comment, xsl:processing-instruction, xsl:namespace, and xsl:value-of all create nodes that cannot have children. Specifically, the xsl:attribute instruction creates an attribute node, xsl:comment creates a comment node, xsl:processing-instruction creates a processing instruction node, xsl:namespace creates a namespace node, and xsl:value-of creates a text node. The string value of the new node is constructed using either the select attribute of the instruction, or the sequence constructor that forms the content of the instruction. The select attribute allows the content to be specified by means of an XPath expression, while the sequence constructor allows it to be specified by means of a sequence of XSLT instructions. The select attribute or sequence constructor is evaluated to produce a result sequence, and the string value of the new node is derived from this result sequence according to the rules below.
These rules are also used to compute the effective value of a value template. In this case the sequence being processed is the result of evaluating an XPath expression enclosed between curly brackets, and the separator is a single space character.
Zero-length text nodes in the sequence are discarded.
Adjacent text nodes in the sequence are merged into a single text node.
The sequence is atomized (which may cause a dynamic error).
Every value in the atomized sequence is cast to a string.
The strings within the resulting sequence are concatenated, with a (possibly zero-length) separator inserted between successive strings. The default separator depends on the containing instruction; except where otherwise specified, it is a single space.
In the case of xsl:attribute and xsl:value-of, the default separator is a single space when the select attribute is used, or a zero-length string otherwise; a different separator can be specified using the separator attribute of the instruction.
In the case of xsl:comment, xsl:processing-instruction, and xsl:namespace, and when expanding a value template, the default separator cannot be changed.
In the case of xsl:processing-instruction, any leading spaces in the resulting string are removed.
The resulting string forms the string value of the new attribute, namespace, comment, processing-instruction, or text node.
Consider the following stylesheet fragment:
<doc> <xsl:attribute name="e" select="1 to 5"/> <xsl:attribute name="f"> <xsl:for-each select="1 to 5"> <xsl:value-of select="."/> </xsl:for-each> </xsl:attribute> <xsl:attribute name="g" expand-text="yes">{1 to 5}</xsl:attribute> </doc>
This produces the output:
<doc e="1 2 3 4 5" f="12345" g="1 2 3 4 5"/>
The difference between the three cases is as follows. For the e attribute, the sequence constructor generates a sequence of five atomic items, which are therefore separated by spaces. For the f attribute, the content is supplied as a sequence of five text nodes, which are concatenated without space separation. For the g attribute, the text value template constructs a text node using the rules for constructing simple content, which insert space separators between atomic items; the text node is then atomized to form the value of the attribute.
Specifying separator="" on the first xsl:attribute instruction would cause the attribute value to be e="12345". A separator attribute on the second xsl:attribute instruction would have no effect, since the separator only affects the way adjacent atomic items are handled: separators are never inserted between adjacent text nodes. A separator on the third xsl:attribute instruction would also have no effect, because text value templates are evaluated without regard to the containing instruction.
Note:
If an attribute value template contains a sequence of fixed and variable parts, no additional whitespace is inserted between the expansions of the fixed and variable parts. For example, the effective value of the attribute a="chapters{4 to 6}" is a="chapters4 5 6".
In a tree supplied to or constructed by an XSLT processor, the constraints relating to namespace nodes that are specified in [XDM 3.0]must be satisfied. For example:
If an element node has an expanded QName with a non-null namespace URI, then that element node must have at least one namespace node whose string value is the same as that namespace URI.
If an element node has an attribute node whose expanded QName has a non-null namespace URI, then the element must have at least one namespace node whose string value is the same as that namespace URI and whose name is non-empty.
Every element must have a namespace node whose expanded QName has local-part xml and whose string value is http://www.w3.org/XML/1998/namespace. The namespace prefix xmlmust not be associated with any other namespace URI, and the namespace URI http://www.w3.org/XML/1998/namespacemust not be associated with any other prefix.
A namespace node must not have the name xmlns or the string value http://www.w3.org/2000/xmlns/.
[Definition: The rules for the individual XSLT instructions that construct a result tree (see 11 Creating Nodes) prescribe some of the situations in which namespace nodes are written to the tree. These rules, however, are not sufficient to ensure that the prescribed constraints are always satisfied. The XSLT processor must therefore add additional namespace nodes to satisfy these constraints. This process is referred to as namespace fixup.]
The actual namespace nodes that are added to the tree by the namespace fixup process are implementation-dependent, provided firstly, that at the end of the process the above constraints must all be satisfied, and secondly, that a namespace node must not be added to the tree unless the namespace node is necessary either to satisfy these constraints, or to enable the tree to be serialized using the original namespace prefixes from the source document or stylesheet.
Namespace fixup must not result in an element having multiple namespace nodes with the same name.
Namespace fixup may, if necessary to resolve conflicts, change the namespace prefix contained in the QName value that holds the name of an element or attribute node. This includes the option to add or remove a prefix. However, namespace fixup must not change the prefix component contained in a value of type xs:QName or xs:NOTATION that forms the typed value of an element or attribute node.
Note:
Namespace fixup is not used to create namespace declarations for xs:QName or xs:NOTATION values appearing in the content of an element or attribute.
Where values acquire such types as the result of validation, namespace fixup does not come into play, because namespace fixup happens before validation: in this situation, it is the user’s responsibility to ensure that the element being validated has the required namespace nodes to enable validation to succeed.
Where existing elements are copied along with their existing type annotations (validation="preserve") the rules require that existing namespace nodes are also copied, so that any namespace-sensitive values remain valid.
Where existing attributes are copied along with their existing type annotations, the rules of the XDM data model require that a parentless attribute node cannot contain a namespace-sensitive typed value; this means that it is an error to copy an attribute using validation="preserve" if it contains namespace-sensitive content.
Namespace fixup is applied to every element that is constructed using a literal result element, or one of the instructions xsl:element, xsl:copy, or xsl:copy-of. An implementation is not required to perform namespace fixup for elements in any source document, that is, for a document in the initial match selection, documents loaded using the document, doc or collection function, documents supplied as the value of a stylesheet parameter, or documents returned by an extension function or extension instruction.
Note:
A source document (an input document, a document returned by the document, doc or collection functions, a document returned by an extension function or extension instruction, or a document supplied as a stylesheet parameter) is required to satisfy the constraints described in [XDM 3.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.8.15.7.1 Constructing Complex Content, does cause the namespaces of a parent element to be inherited by its children unless this is prevented using [xsl:]inherit-namespaces="no" on the instruction that creates the parent element.
Note:
This has implications on serialization, defined in [XSLT and XQuery Serialization]. 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: 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 Section 5.3.1 CollationsFO.
URI references used to identify external resources must conform to the same rules as the locator attribute (href) defined in section 5.4 of [XLink]. If the URI reference is relative, then it is resolved (unless otherwise specified) against the base URI of the containing element node, according to the rules of [RFC3986], after first escaping all characters that need to be escaped to make it a valid RFC3986 URI reference. (But a relative URI reference in the href attribute of xsl:result-document is resolved against the Base Output URI.)
Other URI references appearing in an XSLT stylesheet document, for example the system identifiers of external entities or the value of the xml:base attribute, must follow the rules in their respective specifications.
The base URI of an element node in the stylesheet is determined as defined in Section 5.2 base-uri Accessor DM30. Some implementations may allow the output of the static analysis phase of stylesheet processing (a “compiled stylesheet”) to be evaluated in a different location from that where static analysis took place. Furthermore, stylesheet authors may in such cases wish to avoid exposing the location of resources that are private to the development environment. If the base URI of an element in the stylesheet is defined by an absolute URI appearing in an xml:base attribute within the stylesheet, this value must be used as the static base URI. In other cases where processing depends on the static base URI of a stylesheet module, implementations may use different values for the static base URI during static analysis and during dynamic evaluation (for example, an implementation may use different base URIs for resolving xsl:import module references and for resolving a relative reference used as an argument to the doc function). In such cases an implementation must document how the static base URI is computed for each situation in which it is required.
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: 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.85.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.
This section describes template rules. Named templates are described in 10.1 Named Templates.
A template rule is specified using the xsl:template element with a match attribute. The match attribute is a Pattern that identifies the items to which the rule applies. The result of applying the template rule is the result of evaluating the sequence constructor contained in the xsl:template element, with the matching item used as the context item.
For example, an XML document might contain:
This is an <emph>important</emph> point.
The following template rule matches emph elements and produces a fo:wrapper element with a font-weight property of bold.
<xsl:template match="emph"> <fo:wrapper font-weight="bold" xmlns:fo="http://www.w3.org/1999/XSL/Format"> <xsl:apply-templates/> </fo:wrapper> </xsl:template>
A template rule is evaluated when an xsl:apply-templates instruction selects an item that matches the pattern specified in the match attribute. The xsl:apply-templates instruction is described in the next section. If several template rules match a selected item, only one of them is evaluated, as described in 6.56.6 Conflict Resolution for Template Rules.
In XSLT 4.0, patterns can match any kind of item: atomic items and function items as well as nodes.
A template rule identifies the items to which it applies by means of a pattern. As well as being used in template rules, patterns are used for numbering (see 12 Numbering), for grouping (see 14 Grouping), and for declaring keys (see 20.2 Keys).
[Definition: A pattern specifies a set of conditions on an item. An item that satisfies the conditions matches the pattern; an item that does not satisfy the conditions does not match the pattern.]
There are three kinds of pattern: predicate patterns, type patterns, and node patterns:
[Definition: A predicate pattern is written as . (dot) followed by zero or more predicates in square brackets, and it matches any item for which each of the predicates evaluates to true.]
A predicate pattern .[P1][P2]... can be regarded as an abbreviation for the type pattern type(item())[P1][P2]....
The detailed semantics are given in 6.3.2.1 Predicate Patterns. This construct can be used to match items of any kind (nodes, atomic items, and function items). For example, the pattern .[starts-with(., '$')] matches any string that starts with the character $, or a node whose atomized value starts with $. This example shows a predicate pattern with a single predicate, but the grammar allows any number of predicates (zero or more).
[Definition: A type pattern can be written as type(T) (where T is an ItemTypeXP followed by zero or more predicates in square brackets, and it matches any item of type T which each of the predicates evaluates to true.]
The parameter T can also be a list of item types, separated by "|". For example, type(array(*) | map(*)) matches arrays and maps, while type(text() | comment()) matches text nodes and comment nodes.
The most commonly used type patterns can be abbreviated. For example, match="type(record(F1, F2, *))" can be abbrevated to match="record(F1, F2, *)", and match="type(array(xs:string))" can be abbreviated to match="array(xs:string)". The main case where such abbreviation is not possible is with atomic items: match="type(xs:date)" cannot be abbreviated because a bare QName is interpreted as a node pattern, matching elements named xs:date. The pattern match="type(text() | comment())" has almost the same effect as match="text() | comment()", except that the rules for calculating a default priority are different.
[Definition: A node pattern uses a subset of the syntax for path expressions, and is defined to match a node if the corresponding path expression would select the node. Node patterns may also be formed by combining other patterns using union, intersection, and difference operators.]
The syntax for node patterns (UnionExprP in the grammar: see 6.3.2 Syntax of Patterns) is a subset of the syntax for expressions. Node patterns are used only for matching nodes; an item other than a node will never match a node pattern. As explained in detail below, a node matches a node pattern if the node can be selected by deriving an equivalent expression, and evaluating this expression with respect to some possible context.
Note:
The specification uses the phrases an item matches a pattern and a pattern matches an item interchangeably. They are equivalent: an item matches a pattern if and only if the pattern matches the item.
Here are some examples of patterns:
Predicate Patterns:
. matches any item.
.[. castable as xs:date] matches any item that can be successfully cast to xs:date: for example, an xs:date or xs:dateTime value, or a string in the lexical form of a date, or a node whose typed value is an xs:date or a string in the form of a date.
.[string() => matches('^[0-9]$')] matches any item whose string value is a sequence of digits.
.[. castable as xs:date][xs:date(.) le current-date()] matches any item that is castable to xs:date provided that the result of casting the value to xs:date is a date in the past.
Type Patterns
type(item()) matches any item.
type(node()) matches any node. (Note the distinction from the pattern node().)
type(xs:date) matches any atomic item of type xs:date (or a type derived by restriction from xs:date).
type(xs:date)[. gt current-date()] matches any date in the future.
type(xs:string)[starts-with(., 'e')] matches any xs:string value that starts with the letter e. Note there is no type conversion; the pattern will not match an xs:untypedAtomic or xs:anyURI value, nor will it match any node.
type(fn(*)) matches any function item.
type(fn($x as xs:integer) as xs:boolean)[.(42)] matches any function that accepts an xs:integer argument and returns a boolean result, provided that the result of calling the function with the argument value 42 is true.
type(xs:date | xs:dateTime | xs:time) matches any atomic item that is an instance of xs:date, xs:dateTime, or xs:time.
type(array(xs:date) | array(xs:dateTime) | array(xs:time)) matches any array whose members are all of type xs:date, any array whose members are all of type xs:dateTime, or any array whose members are all of type xs:time.
type(map((xs:string|xs:untypedAtomic), *) matches any map whose keys are all instances of xs:string or xs:untypedAtomic.
enum("red", "green", "blue") matches any one of the three strings "red", "green", or "blue".
record(first, last, *)[?location = 'UK'] matches any map whose keys include the strings "first" and "last", and that also has an entry with key "location" whose value is "UK".
record(longitude, latitude) matches any map with two entries whose keys are the strings "longitude" and "latitude".
array(xs:integer)[array:size(.) eq 4] matches any array of four integers.
array(record(first, last, *)) matches any array of maps where each map contains entries with keys "first" and "last". (Note that this includes the empty array).
array(record(first, last, *))[array:size(.) gt 0] matches any non-empty array of maps where each map contains entries with keys "first" and "last".
type(complex) matches any value that is an instance of the item type declared in an xsl:item-type or xsl:record-type declaration with name "complex"
type(complex)[?i eq 0] matches any value that is an instance of the item type declared in an xsl:item-type or xsl:record-type declaration with name "complex" and that is a map with an entry having key i and value zero.
Node Patterns
* matches any element.
para matches any para element.
chapter|appendix matches any chapter element and any appendix element.
child::(chapter|appendix) matches any chapter element and any appendix element. Note that although the child axis is explicitly written, an element can match even though it has no parent.
olist/entry matches any entry element with an olist parent.
appendix//para matches any para element with an appendix ancestor element.
appendix/descendant::(para|table) matches any para or tableelement with an appendix ancestor element.
schema-element(us:address) matches any element that is annotated as an instance of the type defined by the schema element declaration us:address, and whose name is either us:address or the name of another element in its substitution group.
attribute(*, xs:date) matches any attribute annotated as being of type xs:date.
/ matches a document node.
document-node() matches a document node.
document-node(schema-element(my:invoice)) matches the document node of a document whose document element is named my:invoice and matches the type defined by the global element declaration my:invoice.
text() matches any text node.
namespace-node() matches any namespace node.
node() matches any node other than an attribute node, namespace node, or document node.
id("W33") matches the element with unique ID W33.
para[1] matches any para element that is the first para child element of its parent. It also matches a parentless para element.
//para matches any para element in a tree that is rooted at a document node.
bullet[position() mod 2 = 0] matches any bullet element that is an even-numbered bullet child of its parent.
div[@class="appendix"]//p matches any p element with a div ancestor element that has a class attribute with value appendix.
@class matches any class attribute (not any element that has a class attribute).
@(class|type|kind) matches any attribute named class or type or kind.
@* matches any attribute node.
$xyz matches any node that is present in the value of the variable $xyz.
$xyz//* matches any element that is a descendant of a node that is present in the value of the variable $xyz.
doc('product.xml')//* matches any element within the document whose document URI is product.xml.
[ERR XTSE0340] Where an attribute is defined to contain a pattern, it is a static error if the pattern does not match the production Pattern40.
The complete grammar for patterns is listed in E Pattern Syntax Summary. It uses the notation defined in Section A.1.1 NotationXP.
The lexical rules for patterns are the same as the lexical rules for XPath expressions, as defined in Section A.3 Lexical structureXP. Comments are permitted between tokens, using the syntax (: ... :). All other provisions of the XPath grammar apply where relevant, for example the rules for whitespace handling and extra-grammatical constraints.
Pattern40 | ::= | PredicatePattern | TypePattern | NodePattern |
PredicatePattern | ::= | "." PredicateXP* |
TypePattern | ::= | (WrappedItemTest | AnyItemTestXP | FunctionTypeXP | MapTypeXP | ArrayTypeXP | RecordTypeXP | EnumerationTypeXP) PredicateXP* |
NodePattern | ::= | UnionExprP |
Patterns fall into three groups:
A PredicatePattern matches items according to conditions that the item must satisfy: for example .[. castable as xs:integer] matches any value (it might be an atomic item, a node, or an array) that is castable as an integer.
A TypePattern matches items according to their type. For example type(xs:integer) matches an atomic item that is an instance of xs:integer, while record(longitude, latitude) matches a map that has exactly two entries, with keys "longitude" and "latitude"
A NodePattern matches nodes in a tree, typically by specifying a path that can be used to locate the nodes: for example order matches an element node named order, while billing-address/city matches an element named city whose parent node is an element named billing-address.
The following sections define the rules for each of these groups.
PredicatePattern | ::= | "." PredicateXP* |
Predicate | ::= | "[" ExprXP "]" |
Expr | ::= | (ExprSingleXP ++ ",") |
ExprSingle | ::= | ForExprXP |
ForExpr | ::= | ForClauseXPForLetReturnXP |
ForClause | ::= | "for" (ForBindingXP ++ ",") |
ForLetReturn | ::= | ForExprXP | LetExprXP | ("return" ExprSingleXP) |
LetExpr | ::= | LetClauseXPForLetReturnXP |
LetClause | ::= | "let" (LetBindingXP ++ ",") |
QuantifiedExpr | ::= | ("some" | "every") (QuantifierBindingXP ++ ",") "satisfies" ExprSingleXP |
QuantifierBinding | ::= | VarNameAndTypeXP "in" ExprSingleXP |
IfExpr | ::= | "if" "(" ExprXP ")" (UnbracedActionsXP | BracedActionXP) |
UnbracedActions | ::= | "then" ExprSingleXP "else" ExprSingleXP |
BracedAction | ::= | EnclosedExprXP |
A PredicatePatternPP matches an item J if and only if the XPath expression taking the same form as PP returns a non-empty sequence when evaluated with a singleton focus based on J.
Note:
The pattern ., which is a PredicatePattern with no predicates, matches every item.
A predicate with the numeric value 1 (one) always matches, and a predicate with any other numeric value never matches. Numeric predicates in a PredicatePattern are therefore not useful, but are defined this way in the interests of consistency with XPath.
For example, the pattern .[contains(., "XSLT")] matches any item whose atomized value contains "XSLT" as a substring. It matches values such as the string "XSLT Transformations", the xs:anyURI value http://www.w3.org/TR/XSLT, the attribute node class="XSD XSLT XPath", and the singleton array [ "XSLT 4.0" ].
Note:
Evaluation of this example pattern may fail with a dynamic error if the item in question has an atomized value that is not a string, or that is a sequence of strings: an example might be the array [ "XSLT", 1999 ]. It will also fail if the item cannot be atomized, for example if it is a map. The rules in 6.3.3 Errors in Patterns cause these errors to be masked: they simply result in the pattern being treated as non-matching.
Patterns (especially those used in template rules) can now be defined by reference to item types, so any item type can be used as a match pattern. For example match="record(longitude, latitude, *)" matches any map that includes the key values "longitude" and "latitude". [Issue 400 PR 401 21 March 2023]
TypePattern | ::= | (WrappedItemTest | AnyItemTestXP | FunctionTypeXP | MapTypeXP | ArrayTypeXP | RecordTypeXP | EnumerationTypeXP) PredicateXP* |
WrappedItemTest | ::= | "type" ChoiceItemTypeXP |
ChoiceItemType | ::= | "(" (ItemTypeXP ++ "|") ")" |
ItemType | ::= | RegularItemTypeXP | FunctionTypeXP | TypeNameXP | ChoiceItemTypeXP |
RegularItemType | ::= | AnyItemTestXP | NodeKindTestXP | GNodeTypeXP | JNodeTypeXP | MapTypeXP | ArrayTypeXP | RecordTypeXP | EnumerationTypeXP |
AnyItemTest | ::= | "item" "(" ")" |
NodeKindTest | ::= | DocumentTestXP |
GNodeType | ::= | "gnode" "(" ")" |
JNodeType | ::= | "jnode" "(" SequenceTypeXP? ")" |
MapType | ::= | AnyMapTypeXP | TypedMapTypeXP |
ArrayType | ::= | AnyArrayTypeXP | TypedArrayTypeXP |
RecordType | ::= | AnyRecordTypeXP | TypedRecordTypeXP |
EnumerationType | ::= | "enum" "(" (StringLiteralXP ++ ",") ")" |
FunctionType | ::= | AnyFunctionTypeXP |
AnyFunctionType | ::= | ("function" | "fn") "(" "*" ")" |
TypedFunctionType | ::= | ("function" | "fn") "(" (TypedFunctionParamXP ** ",") ")" "as" SequenceTypeXP |
TypeName | ::= | EQNameXP |
EQName | ::= | QName | URIQualifiedNameXP |
TypedFunctionParam | ::= | ("$" EQNameXP "as")? SequenceTypeXP |
URIQualifiedName | ::= | BracedURILiteralNCName |
| /* ws: explicit */ | ||
SequenceType | ::= | ("empty-sequence" "(" ")") |
OccurrenceIndicator | ::= | "?" | "*" | "+" |
| /* xgs: occurrence-indicators */ | ||
AnyMapType | ::= | "map" "(" "*" ")" |
TypedMapType | ::= | "map" "(" ItemTypeXP "," SequenceTypeXP ")" |
AnyArrayType | ::= | "array" "(" "*" ")" |
TypedArrayType | ::= | "array" "(" SequenceTypeXP ")" |
AnyRecordType | ::= | "record" "(" "*" ")" |
TypedRecordType | ::= | "record" "(" (FieldDeclarationXP ** ",") ExtensibleFlagXP? ")" |
FieldDeclaration | ::= | FieldNameXP "?"? ("as" SequenceTypeXP)? |
FieldName | ::= | NCNameXP | StringLiteralXP |
StringLiteral | ::= | AposStringLiteral | QuotStringLiteral |
| /* ws: explicit */ | ||
ExtensibleFlag | ::= | "," "*" |
AposStringLiteral | ::= | "'" (EscapeApos | [^'])* "'" |
| /* ws: explicit */ | ||
QuotStringLiteral | ::= | '"' (EscapeQuot | [^"])* '"' |
| /* ws: explicit */ | ||
Predicate | ::= | "[" ExprXP "]" |
Expr | ::= | (ExprSingleXP ++ ",") |
ExprSingle | ::= | ForExprXP |
ForExpr | ::= | ForClauseXPForLetReturnXP |
ForClause | ::= | "for" (ForBindingXP ++ ",") |
ForLetReturn | ::= | ForExprXP | LetExprXP | ("return" ExprSingleXP) |
LetExpr | ::= | LetClauseXPForLetReturnXP |
LetClause | ::= | "let" (LetBindingXP ++ ",") |
QuantifiedExpr | ::= | ("some" | "every") (QuantifierBindingXP ++ ",") "satisfies" ExprSingleXP |
QuantifierBinding | ::= | VarNameAndTypeXP "in" ExprSingleXP |
IfExpr | ::= | "if" "(" ExprXP ")" (UnbracedActionsXP | BracedActionXP) |
UnbracedActions | ::= | "then" ExprSingleXP "else" ExprSingleXP |
BracedAction | ::= | EnclosedExprXP |
A type pattern tests whether an item matches a given item type, optionally qualified with one or more predicates that the value must also satisfy.
The general-purpose construct type(ItemType) allows any ItemType to be used in a pattern. Where syntactic constraints permit, many ItemTypes can also be used directly: for example type(item()) can be abbreviated as item().
For example:
type(xs:integer) matches any instance of xs:integer
type(xs:integer)[. gt 0] matches any positive integer.
type(xs:string | xs:untypedAtomic)[matches(., '[0-9]+')] matches any instance of xs:string or xs:untypedAtomic that contains a sequence of decimal digits.
type(node()) matches any node. (This is not the same as the pattern node(), which for historical reasons only matches element, text, comment, and processing instruction nodes).
More formally, an item $J matches a pattern type(T)[P1][P2][P3] if the XPath expression $J instance of T and exists($J[P1][P2][P3]) is true.
Note:
As with predicate patterns, numeric predicates are allowed, but serve no useful purpose.
A pattern written as record(A, B, C) is an abbreviation for type(record(A, B, C)) (retaining any predicates). For example, the pattern record(first, last, *)[?first eq "Sharon"] matches any map having entries with the string-valued keys "first" and "last", where the entry for the key "first" is equal to the string "Sharon".
Note:
The item type in a pattern can be any ItemType, but patterns that match nodes can usually be expressed more economically as a NodeTest: for example match="type(element(PERSON))" has the same meaning as match="element(PERSON)", which in turn is usually abbreviated to match="PERSON".
Although match="type(element(PERSON))" matches exactly the same items as match="PERSON", the priority relative to other template rules (in the absence of an explicit priority attribute) may be different.
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]
The semantics of patterns using the intersect and except operators have been changed to reflect the intuitive meaning: for example a node now matches A except B if it matches A and does not match B. [Issue 402 ]
NodePattern | ::= | 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 |
Node Patterns are used to match XDM nodes.
The names of these constructs are chosen to align with the XPath 3.0 grammar. Constructs whose names are suffixed with P are restricted forms of the corresponding XPath 3.0 construct without the suffix. Constructs labeled with the suffix “XP40” are defined in [XPath 4.0].
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.
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 (/*)
The meaning of a node pattern is defined formally as follows, where “if” is to be read as “if and only if”.
A node matches a UnionExprPA union B (or equivalently, A | B) if it matches either A or B or both.
A node matches an IntersectExceptExprPA intersect B if it matches both A and B.
A node matches an IntersectExceptExprPA except B if it matches A and does not match B.
A node matches a PathExprP under the following conditions:
If the PathExprP consists in its entirety of a ParenthesizedExprP, then the node matches the ParenthesizedExprP if it matches the UnionExprP enclosed within the parentheses.
Otherwise, the PathExprP pattern is converted to an expression, called the equivalent expression. The equivalent expression to a PathExprP is the XPath expression that takes the same lexical form as the PathExprP as written, with the following adjustment:
If any PathExprP in the Pattern is a RelativePathExprP, then the first StepExprPPS of this RelativePathExprP is adjusted to allow it to match a parentless element, attribute, or namespace node. The adjustment depends on the axis used in this step, whether it appears explicitly or implicitly (according to the rules of Section 4.6.7 Abbreviated SyntaxXP), 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 node at all, XSLT 4.0 allows the pattern .[. instance of node()] to be used.
The meaning of the pattern is then defined in terms of the semantics of the equivalent expression, denoted below as EE.
Specifically, an item N matches a PathExprP pattern P if the following applies, where EE is the equivalent expression to P:
N is a node, and the result of evaluating the expression root(.)//(EE) with a singleton focus based on N is a sequence that includes the node N.
If a pattern appears in an attribute of an element that is processed with XSLT 1.0 behavior (see 3.9 Backwards Compatible Processing), then the semantics of the pattern are defined on the basis that the equivalent XPath expression is evaluated with XPath 1.0 compatibility mode set to true.
Note:
This version of the specification includes an incompatible change to the semantics of patterns using the intersect and except operators. This change is made to eliminate cases where the behavior defined in XSLT 3.0 was counter-intuitive.
Consider the pattern para except appendix//para. In XSLT 4.0 this matches any para element that is not the descendant of an appendix element. In XSLT 3.0 it would match the para element in the XML tree shown below:
<appendix> <section> <para/> </section> </appendix>
because there is an element $S (specifically, the section element), such that the expression $S//(para except appendix//para) selects this para element.
It is recommended that processors should report a compatibility warning when such constructs are encountered. The problem arises with patterns using intersect or except where one of the branches uses the descendant axis: it does not arise in simple cases like * except A, or @* except @code, where the branches only use the child or attribute axis.
The change does not affect the meaning of patterns that use the intersect or except operators nested within a path expression, for example a pattern such as A[.//C except B//C].
The node patternp matches any p element, because a p element will always be present in the result of evaluating the expressionroot(.)//(child-or-top::p). Similarly, / matches a document node, and only a document node, because the result of the expressionroot(.)//(/) returns the root node of the tree containing the context node if and only if it is a document node.
The node patternnode() matches all nodes selected by the expression root(.)//(child-or-top::node()), that is, all element, text, comment, and processing instruction nodes, whether or not they have a parent. It does not match attribute or namespace nodes because the expression does not select nodes using the attribute or namespace axes. It does not match document nodes because for backwards compatibility reasons the child-or-top axis does not match a document node.
Note:
The pattern type(node()) matches all nodes.
The node pattern$V matches all nodes selected by the expression root(.)//($V), that is, all nodes in the value of $V (which will typically be a global variable, though when the pattern is used in contexts such as the xsl:number or xsl:for-each-group instructions, it can also be a local variable).
The node patterndoc('product.xml')//product matches all nodes selected by the expression root(.)//(doc('product.xml')//product), that is, all product elements in the document whose URI is product.xml.
The node patternroot(.)/self::E matches an E element that is the root of a tree (that is, an E element with no parent node).
Although the semantics of node patterns are specified formally in terms of expression evaluation, it is possible to understand pattern matching using a different model. A node pattern such as book/chapter/section can be examined from right to left. A node will only match this pattern if it is a section element; and then, only if its parent is a chapter; and then, only if the parent of that chapter is a book. When the pattern uses the // operator, one can still read it from right to left, but this time testing the ancestors of a node rather than its parent. For example appendix//section matches every section element that has an ancestor appendix element.
The formal definition, however, is useful for understanding the meaning of a pattern such as para[1]. This matches any node selected by the expression root(.)//(child-or-top::para[1]): that is, any para element that is the first para child of its parent, or a para element that has no parent.
Note:
An implementation, of course, may use any algorithm it wishes for evaluating patterns, so long as the result corresponds with the formal definition above. An implementation that followed the formal definition by evaluating the equivalent expression and then testing the membership of a specific node in the result would probably be very inefficient.
Note:
Patterns using the intersect and except operators do not always have the intuitive meaning: in particular, it is not always the case that a node matches A except B if it matches A but does not match B.
For example, consider the pattern para except appendix//para. This expands to root(.)/descendant-or-self::node()/(child::para except child::appendix//para). Since for a given parent node, the results of child::para and child::appendix are disjoint, the right-hand operand of except has no effect.
The effect of matching all paragraphs except those within an appendix can be achieved using the pattern para except //appendix//para; alternatively, use para[not(ancestor::appendix)].
Simpler patterns such as @* except @code generally have the expected effect; the complications arise mainly when non-trivial relative paths are used.
A dynamic error or type error that occurs during the evaluation of a pattern against a particular item has the effect that the item being tested is treated as not matching the pattern. The error does not cause the transformation to fail, and cannot be caught by a try/catch expression surrounding the instruction that causes the pattern to be evaluated.
Note:
The reason for this provision is that it is difficult for the stylesheet author to predict which predicates in a pattern will actually be evaluated. In the case of match patterns in template rules, it is not even possible to predict which patterns will be evaluated against a particular node.
There is a risk that ignoring errors in this way may make programming mistakes harder to debug. Implementations may mitigate this by providing warnings or other diagnostics when evaluation of a pattern triggers an error condition.
Static errors in patterns, including dynamic and type errors that are raised statically as permitted by the specification, are raised in the normal way and cause the transformation to fail.
The requirement to detect and raise a circularity as a dynamic error overrides this rule.
The xsl:for-each and xsl:apply-templates instructions acquire an attribute separator that can be used to insert content between adjacent items. [This change was in the editor's draft adopted as a baseline when the WG commenced work.] [ 1 January 2022]
<!-- Category: instruction -->
<xsl:apply-templates
select? = expression
mode? = token
separator? = { string } >
<!-- Content: (xsl:sort | xsl:with-param)* -->
</xsl:apply-templates>
The xsl:apply-templates instruction takes as input a sequence of items (typically nodes in a source tree), and produces as output a sequence of items; these will often be nodes to be added to a result tree.
If the instruction has one or more xsl:sort children, then the input sequence is sorted as described in 13 Sorting. The result of this sort is referred to below as the sorted sequence; if there are no xsl:sort elements, then the sorted sequence is the same as the input sequence.
Each item in the input sequence is processed by finding a template rule whose pattern matches that item. If there is more than one such template rule, the best among them is chosen, using rules described in 6.56.6 Conflict Resolution for Template Rules. If there is no template rule whose pattern matches the item, a built-in template rule is used (see 6.86.9 Built-in Template Rules). The chosen template rule is evaluated. The rule that matches the Nth item in the sorted sequence is evaluated with that item as the context item, with N as the context position, and with the length of the sorted sequence as the context size. Each template rule that is evaluated produces a sequence of items as its result. The resulting sequences (one for each item in the sorted sequence) are then concatenated, to form a single sequence. They are concatenated retaining the order of the items in the sorted sequence. The final concatenated sequence forms the result of the xsl:apply-templates instruction.
Suppose the source document is as follows:
<message>Proceed <emph>at once</emph> to the exit!</message>
This can be processed using the two template rules shown below.
<xsl:template match="message"> <p> <xsl:apply-templates select="child::node()"/> </p> </xsl:template> <xsl:template match="emph"> <b> <xsl:apply-templates select="child::node()"/> </b> </xsl:template>
There is no template rule for the document node; the built-in template rule for this node will cause the message element to be processed. The template rule for the message element causes a p element to be written to the result tree; the contents of this p element are constructed as the result of the xsl:apply-templates instruction. This instruction selects the three child nodes of the message element (a text node containing the value Proceed , an emph element node, and a text node containing the value to the exit!). The two text nodes are processed using the built-in template rule for text nodes, which returns a copy of the text node. The emph element is processed using the explicit template rule that specifies match="emph".
When the emph element is processed, this template rule constructs a b element. The contents of the b element are constructed by means of another xsl:apply-templates instruction, which in this case selects a single node (the text node containing the value at once). This is again processed using the built-in template rule for text nodes, which returns a copy of the text node.
The final result of the match="message" template rule thus consists of a p element node with three children: a text node containing the value Proceed , a b element that is the parent of a text node containing the value at once, and a text node containing the value to the exit!. This result tree might be serialized as:
<p>Proceed <b>at once</b> to the exit!</p>
The default value of the select attribute is child::node(), which causes all the children of the context node to be processed.
[ERR XTTE0510] It is a type error if an xsl:apply-templates instruction with no select attribute is evaluated when the context item is not a node.
A select attribute can be used to process items selected by an expression instead of processing all children. The value of the select attribute is an expression.
The following example processes all of the given-name children of the author elements that are children of author-group:
<xsl:template match="author-group"> <fo:wrapper> <xsl:apply-templates select="author/given-name"/> </fo:wrapper> </xsl:template>
It is also possible to process elements that are not descendants of the context node. This example assumes that a department element has group children and employee descendants. It finds an employee’s department and then processes the group children of the department.
<xsl:template match="employee"> <fo:block> Employee <xsl:apply-templates select="name"/> belongs to group <xsl:apply-templates select="ancestor::department/group"/> </fo:block> </xsl:template>
It is possible to write template rules that are matched according to the schema-defined type of an element or attribute. The following example applies different formatting to the children of an element depending on their type:
<xsl:template match="product"> <table> <xsl:apply-templates select="*"/> </table> </xsl:template> <xsl:template match="product/*" priority="3"> <tr> <td><xsl:value-of select="name()"/></td> <td><xsl:next-match/></td> </tr> </xsl:template> <xsl:template match="product/element(*, xs:decimal) | product/element(*, xs:double)" priority="2"> <xsl:value-of select="format-number(xs:double(.), '#,###0.00')"/> </xsl:template> <xsl:template match="product/element(*, xs:date)" priority="2"> <xsl:value-of select="format-date(., '[Mn] [D], [Y]')"/> </xsl:template> <xsl:template match="product/*" priority="1.5"> <xsl:value-of select="."/> </xsl:template>
The xsl:next-match instruction is described in 6.96.10 Overriding Template Rules.
Multiple xsl:apply-templates elements can be used within a single template to do simple reordering. The following example creates two HTML tables. The first table is filled with domestic sales while the second table is filled with foreign sales.
<xsl:template match="product"> <table> <xsl:apply-templates select="sales/domestic"/> </table> <table> <xsl:apply-templates select="sales/foreign"/> </table> </xsl:template>
It is possible for there to be two matching descendants where one is a descendant of the other. This case is not treated specially: both descendants will be processed as usual.
For example, given a source document
<doc><div><div></div></div></doc>
the rule
<xsl:template match="doc"> <xsl:apply-templates select=".//div"/> </xsl:template>
will process both the outer div and inner div elements.
This means that if the template rule for the div element processes its own children, then these grandchildren will be processed more than once, which is probably not what is required. The solution is to process one level at a time in a recursive descent, by using select="div" in place of select=".//div"
This example reads a non-XML text file and processes it line-by-line, applying different template rules based on the content of each line:
<xsl:template name="main"> <xsl:apply-templates select="unparsed-text-lines('input.txt')"/> </xsl:template> <xsl:template match="type(xs:string)[starts-with(., '==')]"> <h2><xsl:value-of select="replace(., '==', '')"/></h2> </xsl:template> <xsl:template match="type(xs:string)[starts-with(., '::')]"> <p class="indent"><xsl:value-of select="replace(., '::', '')"/></p> </xsl:template> <xsl:template match="type(xs:string)"> <p class="body"><xsl:value-of select="."/></p> </xsl:template>
This example reads a JSON data file and formats it as XHTML.
It takes the following JSON data as input:
[
{ "Title": "Computer Architecture",
"Authors": [ "Enid Blyton"] ,
"Category": "Computers",
"Price": 42.60
},
{ "Title": "Steppenwolf",
"Authors": [ "Hermann Hesse" ],
"Category": "Fiction",
"Price": 12.00
},
{ "Title": "How to Explore Outer Space with Binoculars",
"Authors": [ "Bruce Betts", "Erica Colon" ],
"Category": "Science",
"Price": 10.40
}
]The following template rules are used. The setting expand-text="yes" is assumed:
<xsl:record-type name="book" extensible="yes"> <xsl:field name="Title"/> <xsl:field name="Authors"/> <xsl:field name="Category"/> </xsl:record-type> <xsl:template name="xsl:initial-template"> <xsl:apply-templates select="parse-json('input.json')"/> </xsl:template> <xsl:template match="array(book)"> <h1>Christmas Book Selection</h1> <table> <thead> <tr> <th>Title</th> <th>Authors</th> <th>Category</th> <th>Price</th> </tr> </thead> <tbody> <xsl:apply-templates select="?*"/> </tbody> </table> </xsl:template> <xsl:template match="type(book)"> <tr> <td>{?Title}</td> <td>{?Authors?* => string-join(", ")}</td> <td>{?Category}</td> <td>${?Price}</td> </tr> </xsl:template>
Note:
The xsl:apply-templates instruction is most commonly used to process nodes that are descendants of the context node. Such use of xsl:apply-templates cannot result in non-terminating processing loops. However, when xsl:apply-templates is used to process elements that are not descendants of the context node, the possibility arises of non-terminating loops. For example,
<xsl:template match="foo"> <xsl:apply-templates select="."/> </xsl:template>
Implementations may be able to detect such loops in some cases, but the possibility exists that a stylesheet may enter a non-terminating loop that an implementation is unable to detect. This may present a denial of service security risk.
separator attributeIf the separator attribute of xsl:apply-templates is present, then its effective value is inserted, as a text node, into the output sequence, immediately after the results of processing each item in the sorted sequence other than the last.
For example, if the ARTICLE element has a number of element children named AUTHOR, the following code will produce a sorted, comma-separated list of authors:
<xsl:template match="ARTICLE"> <article> ... <xsl:text>Author(s): </xsl:text> <xsl:apply-templates select="AUTHOR" separator=", "> <xsl:sort select="LAST-NAME"/> <xsl:sort select="FIRST-NAME"/> </xsl:apply-templates> ... </article> </xsl:template> <xsl:template match="AUTHOR" expand-text="yes"> <xsl:text>{FIRST-NAME} {LAST-NAME}</xsl:text> </xsl:template>
The node identity of any text nodes that are inserted is implementation-dependent. Specifically, it is not defined whether all the text nodes inserted in the course of one evaluation of the instruction are identical to each other, nor whether they are identical to the text nodes inserted in the course of another evaluation of this instruction, nor whether they are identical to any other parentless text nodes having the same string value.
If the separator is a zero-length string, then a zero-length text node is inserted into the sequence. (If the sequence is used for constructing the value of a node, then zero-length text nodes will be discarded: see 5.8.25.7.2 Constructing Simple Content and 5.8.15.7.1 Constructing Complex Content.)
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: 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.66.7 Default Priority for Template Rules.]
[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.
Next, if any of the remaining matching rules has a match pattern in the form of a TypePattern, then this set of rules is reduced as follows:
Any rule with a match pattern that is not a type pattern is discarded. (That is, type patterns are chosen in preference to non-type patterns). Call the set of type patterns that remain R.
A TypePattern comprises an ItemType and a possibly empty set of predicates.
Any rule in R whose ItemType is a strict supertype of the ItemType of another rule in R is discarded. A type T is a strict supertype of another type U if U is a subtypeXP of T and T is not a subtypeXP of U.
If there is a rule P in R whose ItemType is the same type as the ItemType of another rule Q in R, and if Q has one or more predicates while P has none, then P is discarded. A type T is the same type as another type U if T is a subtypeXP of U and U is a subtypeXP of T.
If this process leaves a single rule, then that rule is chosen.
Note:
For example, this means that:
The match pattern type(xs:integer) is chosen in preference to type(xs:decimal) which in turn is chosen in preference to type(item()).
The match pattern type(xs:integer)[. gt 0] is chosen in preference to type(xs:integer) which in turn is chosen in preference to type(xs:decimal).
The match pattern type(xs:integer) is chosen in preference to type(xs:integer | xs:double) which in turn is chosen in preference to type(xs:numeric).
The match pattern record(longitude, latitude, altitude) is chosen in preference to the pattern record(longitude, latitude, *), which in turn is chosen in preference to the pattern type(map(*)).
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 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: If no priority attribute is specified on an xsl:template element, a default priority is computed, based on the syntax of the pattern supplied in the match attribute.] The rules are as follows.
If the top-level pattern is a ParenthesizedExprP then the outer parentheses are effectively stripped; these rules are applied recursively to the UnionExprP contained in the ParenthesizedExprP.
If the top-level pattern is a UnionExprP consisting of multiple alternatives separated by | or union, then the default priority is the maximum of the default priorities of the alternatives.
Note:
This is a backwards incompatible change from XSLT 3.0 and earlier versions, which treated the template rule as equivalent to multiple template rules with different priorities.
The change is made because of the increasing complexity of extending the rule to patterns like @(a|b), or attribute(a|b, xs:integer) which are defined to be semantically identical to equivalent union patterns; and to prevent confusion with type patterns such as type(element(a)|element(b)), where different rules apply.
The change affects any template rule with a union pattern that (a) has no explicit priority attribute, and (b) has multiple branches with different default priority. It is recommended that processors should output a compatibility warning when such template rules are encountered.
The change has two effects. Firstly, if two alternatives in a union pattern have different priority (for example in a pattern such as a | b/c, the priority of one of the branches will be raised to that of the other branch. Secondly, in cases where the same item matches both branches, a call on xsl:next-match will never cause the same template rule to be evaluated repeatedly.
If the top-level pattern is an IntersectExceptExprP containing two or more PathExprP operands separated by intersect or except operators, then the priority of the pattern is that of the first PathExprP.
If the pattern is a PredicatePattern then its priority is 1 (one), unless there are no predicates, in which case the priority is −1 (minus one).
If the pattern is a PathExprP taking the form /, then the priority is −0.5 (minus 0.5).
If the pattern is a PathExprP taking the form of an EQName optionally preceded by a ForwardAxisP or has the form processing-instruction(StringLiteralXP) or processing-instruction(NCNameNames) optionally preceded by a ForwardAxisP, then the priority is 0 (zero).
If the pattern is a PathExprP taking the form of an ElementTestXP or AttributeTestXP, optionally preceded by a ForwardAxisP, then the priority is as shown in the table below. In this table:
The symbols E, A, and T represent an arbitrary element name, attribute name, and type name respectively;
The symbol W represents a WildcardXP other than * (for example prefix:* or *:local);
The symbol * represents itself.
The presence or absence of the symbol ? following a type name does not affect the priority.
| Format | Priority | Notes |
|---|---|---|
element() | −0.5 | (equivalent to *) |
element(*) | −0.5 | (equivalent to *) |
attribute() | −0.5 | (equivalent to @*) |
attribute(*) | −0.5 | (equivalent to @*) |
element(W) | −0.25 | |
attribute(W) | −0.25 | |
element(E) | 0 | (equivalent to E) |
element(*,T) | 0 | (matches by type only) |
attribute(A) | 0 | (equivalent to @A) |
attribute(*,T) | 0 | (matches by type only) |
element(W,T) | 0.125 | |
element(E,T) | 0.25 | (matches by name and type) |
schema-element(E) | 0.25 | (matches by substitution group and type) |
attribute(W,T) | 0.125 | |
attribute(A,T) | 0.25 | (matches by name and type) |
schema-attribute(A) | 0.25 | (matches by name and type) |
If the pattern is a PathExprP taking the form of a DocumentTestXP, then if it includes no ElementTestXP or SchemaElementTestXP the priority is −0.5. If it does include an ElementTestXP or SchemaElementTestXP, then the priority is the same as the priority of that ElementTestXP or SchemaElementTestXP, computed according to the table above.
If the pattern is a PathExprP taking the form of an NCNameNames:*, BracedURILiteralXP*, or *:NCNameNames, optionally preceded by a ForwardAxisP, then the priority is −0.25. [XSLT 3.0 Erratum E37, bug 30375].
If the pattern is a PathExprP taking the form of any other NodeTestXP, optionally preceded by a ForwardAxisP, then the priority is −0.5.
If the pattern is a TypePattern, then the priority is 0 (zero).
In all other cases, the priority is +0.5.
Note:
In many cases this means that highly selective patterns have higher priority than less selective patterns. The most common kind of pattern (a pattern that tests for a node of a particular kind, with a particular expanded QName or a particular type) has priority 0. The next less specific kind of pattern (a pattern that tests for a node of a particular kind and an expanded QName with a particular namespace URI) has priority −0.25. Patterns less specific than this (patterns that just test for nodes of a given kind) have priority −0.5. Patterns that specify both the name and the required type have a priority of +0.25, putting them above patterns that only specify the name or the type. Patterns more specific than this, for example patterns that include predicates or that specify the ancestry of the required node, have priority 0.5.
However, it is not invariably true that a more selective pattern has higher priority than a less selective pattern. For example, the priority of the pattern node()[self::*] is higher than that of the pattern salary. Similarly, the patterns attribute(*, xs:decimal) and attribute(*, xs:short) have the same priority, despite the fact that the latter pattern matches a subset of the nodes matched by the former. Therefore, to achieve clarity in a stylesheet it is good practice to allocate explicit priorities.
[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.
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 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? = boolean | "strict" | "lax" | "unspecified"〔'unspecified'〕
copy-namespaces? = boolean〔'yes'〕
visibility? = "public" | "private" | "final"〔'private'〕 >
<!-- Content: (xsl:template*) -->
</xsl:mode>
[Definition: The unnamed mode is the default mode used when no mode attribute is specified on an xsl:apply-templates instruction or xsl:template declaration, unless a different default mode has been specified using the [xsl:]default-mode attribute of a containing element.]
Every mode other than the unnamed mode is identified by an expanded QName.
A stylesheet may contain multiple xsl:mode declarations and may include or import stylesheet modules that also contain xsl:mode declarations. The name of an xsl:mode declaration is the value of its name attribute, if any.
[Definition: All the xsl:mode declarations in a package that share the same name are grouped into a named mode definition; those that have no name are grouped into a single unnamed mode definition.]
The declared-modes attribute of the xsl:package element determines whether implicit mode declarations are allowed, as described in 3.5.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 6.7.76.8.7 Streamable Templates. | ||||
| use-accumulators | List of accumulator names, or #all (default is an 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 18.2.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.86.9 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.46.8.4 Declaring the Type of Nodes 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.86.9 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.5.4.1 Visibility of Components. If the mode is unnamed, that is, if the name attribute is absent, then the visibility attribute if present must have the value private.
| ||||
[Definition: A streamable mode is a mode that is declared in an xsl:mode declaration with the attribute streamable="yes".]
For any named mode, the effective value of each attribute is taken from an xsl:mode declaration that has a matching name in its name attribute, and that specifies an explicit value for the required attribute. If there is no such declaration, the default value of the attribute is used. If there is more than one such declaration, the one with highest import precedence is used.
For the unnamed mode, the effective value of each attribute is taken from an xsl:mode declaration that has no name attribute, and that specifies an explicit value for the required attribute. If there is no such declaration, the default value of the attribute is used. If there is more than one such declaration, the one with highest import precedence is used.
[ERR XTSE0545] It is a static error if for any named or unnamed mode, a package explicitly specifies two conflicting values for the same attribute in different xsl:mode declarations having the same import precedence, unless there is another definition of the same attribute with higher import precedence. The attributes in question are the attributes other than name on the xsl:mode element.
[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: 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.96.10 Overriding Template Rules).
apply-templates FunctionSometimes it is useful to be able to apply templates from within an XPath expression. A common example is when using XPath expressions to construct maps and arrays. For example, an array of maps might be constructed by the following code:
<xsl:array> <xsl:for-each select="*"> <xsl:array-member> <xsl:map> <xsl:for-each select="@*"> <xsl:map-entry key="local-name()"> <xsl:apply-templates select="."/> </xsl:map-entry> </xsl:for-each> </xsl:map> </xsl:array-member> </xsl:for-each> </xsl:array>
Such code can become verbose, and it is difficult to read because the XML form of the instructions bears literal relationship to the serialized form (typically JSON) of the result. XSLT 4.0 offers the alternative of writing it like this:
<xsl:select> array{ * ! map:build(@*, local-name#1, apply-templates#1) } </xsl:select>
Note:
Explanation: this constructs an array with one member for each element child E of the context node. The member is a map constructed using the map:build function. The map has one entry for each attribute A of element E. The key of this entry is the local name of the attribute, and the corresponding value is obtained by applying templates to the attribute node.
To make this possible, a subset of the functionality of the xsl:apply-templates instruction is available via the (XSLT-only) apply-templates function, whose specification follows.
Applies template rules to selected items.
fn:apply-templates( | ||
$select | as item()*, | |
$options | as map(*)? | := {} |
) as item()* | ||
This function is deterministicFO, context-dependentFO, and focus-independentFO.
The function call apply-templates(X), used within an XPath expression, returns the same result as the instruction <xsl:apply-templates select="X"/>
The entries that may appear in the $options map are as follows. The option parameter conventionsFO apply.
$params as map(xs:QName, item()*), $tunnel-params as map(xs:QName, item()*), $mode as (xs:QName | enum("#current", "#unnamed"))</record>| Key | Value | Meaning |
|---|---|---|
| Supplies values for non-tunnel parameters. Each entry in the params map binds a parameter (identified by an xs:QName value) to a supplied value.
| |
| Supplies values for tunnel parameters. Each entry in the tunnel-params map binds a tunnel parameter (identified by an xs:QName value) to a supplied value.
| |
| Selects the mode to be used. The value may be set to an xs:QName that matches a declared mode in the stylesheet, or to one of the special values #current or #unnamed.
| |
xs:QName | Selects a declared mode by name. | |
#current | Selects the current mode. | |
#unnamed | Selects the unnamed mode. | |
For each item in the value of the $select argument, the function finds the best matching template rule in the selected mode and invokes that template rule with the supplied parameters (if any). The result of the function is the sequence concatenation of the results of performing this process for each item in the selected input, in turn.
Errors may arise in the same situations as for the xsl:apply-templates instruction: for example, if the xsl:mode declaration specifies on-no-match="fail" and no matching template rule is found.
[ERR XTDE0565] It is a dynamic error if a call on the apply-templates function selects a mode that is not explicitly declared in the containing package, or accepted from a used package, or whose visibility is private.
Note:
Modes are private by default: for a mode to be available for reference by the apply-templates function, it must be explicitly declared with visibility="public".
Unlike the xsl:apply-templates instruction, the name of the required mode, and the names of the supplied parameters, can be evaluated dynamically.
If no mode is specified, the function uses the unnamed mode. It does not use the default mode (as defined by a containing [xsl:]default-mode attribute). This decision was made in order to avoid having to retain the default mode for each XPath expression at evaluation time, and to avoid complex rules for edge cases involving dynamic function calls.
See also the rules in 3.5.4.6 Dynamic References to Components, which are relevant to resolution of the mode name.
The function call: | |
| |
has the same effect as the instruction: | |
<xsl:apply-templates select="*" mode="#current"> <xsl:with-param name="expand" select="false()"/> </xsl:apply-templates> |
Typically the template rules in a particular mode will be designed to process a specific kind of input document. The typed attribute of xsl:mode gives the stylesheet author the opportunity to provide information about this document to the processor. This information may enable the processor to improve diagnostics or to optimize performance.
The typed attribute of xsl:mode informs the processor whether the nodes to be processed by template rules in this mode are to be typed or untyped.
If the value yes is specified (synonyms true or 1), then all nodes processed in this mode must be typed. A dynamic error occurs if xsl:apply-templates in this mode selects an element or attribute node whose type annotation is xs:untyped or xs:untypedAtomic.
If the value no is specified (synonyms false or 0), then all nodes processed in this mode must be untyped. A dynamic error occurs if xsl:apply-templates in this mode selects an element or attribute whose type annotation is anything other than xs:untyped or xs:untypedAtomic.
The value strict is equivalent to yes, with the additional provision that in the match pattern of any template rule that is applicable to this mode, any NameTest used in the ForwardStepP of the first StepExprP of a RelativePathExprP is interpreted as follows:
If the NameTest is an EQNameE, and the principal node kind of the axis of this step is Element, then:
It is a static error if the in-scope schema declarations do not include a global element declaration for element name E
When matching templates in this mode, the element name E appearing in this step is interpreted as schema-element(E). (Informally, this means that it will only match an element if it has been validated against this element declaration).
Otherwise (the NameTest is a wildcard or the principal node kind is Attribute or Namespace), the template matching proceeds as if the typed attribute were absent.
The value lax is equivalent to yes, with the additional provision that in the match pattern of any template rule that is applicable to this mode, any NameTest used in the ForwardStepP of the first StepExprP of a RelativePathExprP is interpreted as follows:
If the NameTest is an EQNameE, and the principal node kind of the axis of this step is Element, and the in-scope schema declarations include a global element declaration for element name E, then:
When matching templates in this mode, the element name E appearing in this step is interpreted as schema-element(E). (Informally, this means that it will only match an element if it has been validated against this element declaration).
Otherwise (the NameTest is a wildcard, or the principal node kind is Attribute or Namespace, or there is no element declaration for E), the template matching proceeds as if the typed attribute were absent.
[ERR XTTE3100] It is a type error if an xsl:apply-templates instruction in a particular mode selects an element or attribute whose type is xs:untyped or xs:untypedAtomic when the typed attribute of that mode specifies the value yes, strict, or lax.
[ERR XTSE3105] It is a static error if a template rule applicable to a mode that is defined with typed="strict" uses a match pattern that contains a RelativePathExprP whose first StepExprP is an AxisStepP whose ForwardStepP uses an axis whose principal node kind is Element and whose NodeTest is an EQName that does not correspond to the name of any global element declaration in the in-scope schema components.
[ERR XTTE3110] It is a type error if an xsl:apply-templates instruction in a particular mode selects an element or attribute whose type is anything other than xs:untyped or xs:untypedAtomic when the typed attribute of that mode specifies the value no.
Traditionally, template rules have most commonly been used to construct XDM nodes, and the xsl:apply-templates instruction has been used to add nodes to a result tree. However, it is also possible to use template rules to produce other kinds of value, for example strings, booleans, or maps. For the xsl:apply-templates instruction to be useful, it will generally be the case that all template rules in a mode produce the same kind of value: for example, if one rule delivers a boolean, then the other rules will also deliver a boolean.
XSLT 4.0 therefore allows the result type of the template rules in a mode to be declared using the as attribute on the xsl:mode declaration. If this is absent, it defaults to item()*. The presence of an as attribute on a mode provides useful documentation and consistency checking, and enables the XSLT processor to infer a static type for an xsl:apply-templates instruction, which can be useful for optimization.
If a template rule R is applicable to a mode M, and M is declared with an as attribute whose value is the SequenceTypeT, then:
If R has an as attribute, the SequenceTypeS declared by R must be a subtype of T.
[ERR XTSE4040] It is a static error if a template ruleR has an as attribute S, and the template rule is applicable to a modeM that is declared with an as attribute T, and the sequence type S is not a subtype of the sequence type T as defined by the relationship subtype(S, T) in Section 3.3.1 Subtypes of Sequence TypesXP.
If R has no as attribute, then it is treated as if it had an as attribute set to T. This means that a type error[see ERR XTTE0505] is raised if the result of the template rule cannot be coerced to a value of type T.
If R is applicable to more than one mode, then it must meet the requirements of each one, which implies that these requirements must be consistent with each other: for example, if one mode specifies as="node()" and another specifies as="map(*)", then a type error is inevitable if the template rule is actually evaluated, and like other type errors this can be raised statically if detected statically. An implausibilityXPmay be reported if the only value that would satisfy both types is an empty sequence, map, or array.
Note:
In practice the best way to satisfy this rule is to ensure that if a template rule is applicable to more than one mode (including the case mode="#all"), then either (a) all those modes should have the same declared result type, or (b) the template rule should declare an explicit result type that is compatible with each one of the relevant modes.
The requirement to return values of the correct type extends also to the built-in template rule for the mode (see 6.86.9 Built-in Template Rules). Since it is not possible to determine statically whether the explicit template rules for a mode provide complete coverage of all possible inputs, any failure of the built-in template rule to return a value that can be coerced to the expected type must be raised dynamically [see ERR XTTE0505].
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: 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>
A template rule that is applicable to a mode M is guaranteed-streamable if and only if all the following conditions are satisfied:
Mode M is declared in an xsl:mode declaration that specifies streamable="yes".
The pattern defined in the match attribute of the xsl:template element is a motionless pattern as defined in 19.8.10 Classifying Patterns.
The sweep of the sequence constructor forming the body of the xsl:template element is either motionless or consuming.
The type-adjusted posture of the sequence constructor forming the body of the xsl:template element, with respect to the U-type that corresponds to the declared return type of the template (defaulting to item()*), is grounded.
Note:
This means that either (a) the sequence constructor is grounded as written (that is, it does not return streamed nodes), or (b) it effectively becomes grounded because the declared result type of the template is atomic, leading to implicit atomization of the result.
Every expression and contained sequence constructor in a contained xsl:param element (the construct that provides the default value of the parameter) is motionless.
Specifying streamable="yes" on an xsl:mode declaration declares an intent that every template rule to which that mode is applicable (explicitly or implicitly, including by specifying #all), should be streamable, either because it is guaranteed-streamable, or because it takes advantage of streamability extensions offered by a particular processor. The consequences of declaring the mode to be streamable when there is such a template rule that is not guaranteed streamable depend on the conformance level of the processor, and are explained in 19.10 Streamability Guarantees.
Processing of a document using streamable templates may be initiated using code such as the following, where S is a mode declared with streamable="yes":
<xsl:source-document streamable="yes" href="bigdoc.xml"> <xsl:apply-templates mode="S"/> </xsl:source-document>
Alternatively, streamed processing may be initiated by invoking the transformation with an initial mode declared as streamable, while supplying the initial match selection (in an implementation-defined way) as a streamed document.
Note:
Invoking a streamable template using the construct <xsl:apply-templates select="doc('bigdoc.xml')"/> does not ensure streamed processing. As always, processors may use streamed processing if they are able to do so, but when the doc or document functions are used, processors are obliged to ensure that the results are deterministic, which may be difficult to reconcile with streaming (if the same document is read twice, the results must be identical). The use of xsl:source-document with streamable="yes" does not offer the same guarantees of determinism.
For an example of processing a collection of documents by use of the function uri-collection in conjunction with xsl:source-document, see 18.1.2 Examples of xsl:source-document.
When an item is selected by xsl:apply-templates and there is no user-specified template rule in the stylesheet that can be used to process that item, then a built-in template rule is evaluated instead.
The built-in template rules have lower import precedence than all other template rules. Thus, the stylesheet author can override a built-in template rule by including an explicit template rule.
There are seven sets of built-in template rules available. The set that is chosen is a property of the mode selected by the xsl:apply-templates instruction. This property is set using the on-no-match attribute of the xsl:mode declaration, which takes one of the values deep-copy, shallow-copy, shallow-copy-all,deep-skip, shallow-skip, text-only-copy, or fail, the default being text-only-copy. The effect of these seven sets of built-in template rules is explained in the following subsections.
The effect of processing a tree using a mode that specifies on-no-match="text-only-copy" is that the textual content of the source document is retained while losing the markup, except where explicit template rules dictate otherwise. When an element is encountered for which there is no explicit template rule, the processing continues with the children of that element. Text nodes are copied to the output.
The built-in rule for document nodes and element nodes is equivalent to calling xsl:apply-templates with no select attribute, and with the mode attribute set to #current. If the built-in rule was invoked with parameters, those parameters are passed on in the implicit xsl:apply-templates instruction.
This is equivalent to the following in the case where there are no parameters:
<xsl:template match="document-node()|element()" mode="M"> <xsl:apply-templates mode="#current"/> </xsl:template>
The built-in template rule for text and attribute nodes returns a text node containing the string value of the context node. It is effectively:
<xsl:template match="text()|@*" mode="M"> <xsl:value-of select="string(.)"/> </xsl:template>
Note:
This text node may have a string value that is zero-length.
The built-in template rule for atomic items returns a text node containing the value. It is effectively:
<xsl:template match=".[. instance of xs:anyAtomicType]" mode="M"> <xsl:value-of select="string(.)"/> </xsl:template>
Note:
This text node may have a string value that is zero-length.
The built-in template rule for processing instructions, comments, and namespace nodes does nothing (it returns the empty sequence).
<xsl:template match="processing-instruction()|comment()|namespace-node()" mode="M"/>
The built-in template rule for functions (including maps) does nothing (it returns the empty sequence).
<xsl:template match=".[. instance of fn(*)]" mode="M"/>
The built-in template rule for arrays (see 22 Arrays) is to apply templates to the members of the array. It is equivalent to invoking xsl:apply-templates with the select attribute set to ?* (which selects the members of the array), and with the mode attribute set to #current. If the built-in rule was invoked with parameters, those parameters are passed on in the implicit xsl:apply-templates instruction.
This is equivalent to the following in the case where there are no parameters:
<xsl:template match=".[. instance of array(*)]" mode="M"> <xsl:apply-templates mode="#current" select="?*"/> </xsl:template>
The following example illustrates the use of built-in template rules when there are parameters.
Suppose the stylesheet contains the following instruction:
<xsl:apply-templates select="title" mode="M"> <xsl:with-param name="init" select="10"/> </xsl:apply-templates>
If there is no explicit template rule that matches the title element, then the following implicit rule is used:
<xsl:template match="title" mode="M"> <xsl:param name="init"/> <xsl:apply-templates mode="#current"> <xsl:with-param name="init" select="$init"/> </xsl:apply-templates> </xsl:template>
The effect of processing a tree using a mode that specifies on-no-match="deep-copy" is that an unmatched element in the source tree is copied unchanged to the output, together with its entire subtree. Other unmatched items are also copied unchanged. The subtree is copied unconditionally, without attempting to match nodes in the subtree against template rules.
When this default action is selected for a mode M, all items (nodes, atomic items, and functions, including maps and arrays) are processed using a template rule that is equivalent to the following:
<xsl:template match="." mode="M"> <xsl:copy-of select="." validation="preserve" copy-namespaces="CN"/> </xsl:template>
where CN is the value of the copy-namespaces attribute of the relevant xsl:mode declaration, defaulting to yes.
The effect of processing a tree using a mode that specifies on-no-match="shallow-copy" is that the source tree is copied unchanged to the output, except for nodes where different processing is specified using an explicit template rule.
When this default action is selected for a mode M, all items (nodes, atomic items, and functions, including maps and arrays) are processed using a template rule that is equivalent to the following, except that all parameters supplied in xsl:with-param elements are passed on implicitly to the called templates:
<xsl:template match="." mode="M"> <xsl:copy validation="preserve" copy-namespaces="CN"> <xsl:apply-templates select="@*" mode="M"/> <xsl:apply-templates select="node()" mode="M"/> </xsl:copy> </xsl:template>
where CN is the value of the copy-namespaces attribute of the relevant xsl:mode declaration, defaulting to yes.
This rule is often referred to as the identity template, though it should be noted that it does not preserve node identity.
Note:
This rule differs from the traditional identity template rule by using two xsl:apply-templates instructions, one to process the attributes and one to process the children. The only observable difference from the traditional select="node() | @*" is that with two separate instructions, the value of position() in the called templates forms one sequence starting at 1 for the attributes, and a new sequence starting at 1 for the children.
The following stylesheet transforms an input document by deleting all elements named note, together with their attributes and descendants:
<xsl:stylesheet version="3.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> <xsl:mode on-no-match="shallow-copy" streamable="true"/> <xsl:template match="note"> <!-- no action --> </xsl:template> </xsl:stylesheet>
This processing mode is introduced in XSLT 4.0 as a variant of shallow-copy to enable recursive descent processing of trees involving maps and arrays, such as might result from parsing JSON input.
For all items other than maps and arrays, the effect of shallow-copy-all is exactly the same as shallow-copy.
For arrays, the processing is as follows. A new result array is created, and its content is populated by decomposing the input array to a sequence of value records using the function array:members. Each of these value records is processed by a call on xsl:apply-templates (using the current mode, and passing on the values of all template parameters); the result of the called template is expected to be a value record.
That is, the template rule is equivalent to the following, except that this does not show the propagation of template parameters:
<xsl:array use="?value"> <xsl:apply-templates select="array:members(.)" mode="#current"/> </xsl:array>
Note:
A value record is a single-entry map: it has a single key-value pair with the key "value", the corresponding value being a member of the original array. The default processing for a value record, unless specified otherwise, is to apply templates to the value, as indicated by the rules that follow.
For maps, the processing is as follows:
If the map contains two or more entries, then a new result map is created, and its content is populated by decomposing the input map using the function map:entries to produce a sequence of single-entry maps (each containing one key and one value), and then applying templates to this sequence, using the current mode, and passing on the values of all template parameters.
If the map contains a single entry { K : V0 }, then a new single entry map { K: V1 } is constructed in which V1 is the result of applying templates to V0 (using the current mode, and passing on the values of all template parameters).
Note:
This rule has the effect that if the input is a value record, the output will also be a value record.
If the map is empty, the result is an empty map.
In the first case, the template rule is equivalent to the following, except that this does not show the propagation of template parameters:
<xsl:map> <xsl:apply-templates select="map:entries(.)" mode="#current"/> </xsl:map>
In the second case, the template rule is equivalent to the following, except that this does not show the propagation of template parameters:
<xsl:map-entry key="map:keys(.)"> <xsl:apply-templates select="map:items(.)" mode="#current"/> </xsl:map-entry>
The reason there is a special rule for maps with one entry is to ensure that the process terminates.
The overall effect is best understood with an example.
The following stylesheet transforms a supplied JSON document by deleting all properties named "Note", appearing at any level:
<xsl:stylesheet version="3.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> <xsl:mode on-no-match="shallow-copy-all"/> <xsl:template match="record(Note)"> <!-- no action --> </xsl:template> </xsl:stylesheet>
Consider the following JSON input, converted to an array of maps by calling the function parse-json:
[
{ "Title": "Computer Architecture",
"Authors": [ "Enid Blyton", { "Note": "possibly misattributed" } ],
"Category": "Computers",
"Price": 42.60
},
{ "Title": "Steppenwolf",
"Authors": [ "Hermann Hesse" ],
"Category": "Fiction",
"Price": 12.00,
"Note": "out of print"
},
{ "Title": "How to Explore Outer Space with Binoculars",
"Authors": [ "Bruce Betts", "Erica Colon" ],
"Category": "Science",
"Price": 10.40
}
]The logic proceeds as follows:
The outermost array is processed by applying templates to a sequence of value records, the first being in the form:
{ "value": map: { "Title": ..., "Author": ..., ... }The result of applying templates to these value records is expected to comprise a new sequence of value records, which is used to construct the final output array.
Each of the value records is processed using the rule for single-entry maps. This rule produces a new value record by applying templates to the value, that is, to a map of the form map: { "Title": ..., "Author": ..., ... } representing a book.
Each of these books, being represented by a map with more than two entries, is processed by a template rule that splits the map into its multiple entries, each represented as a singleton map (a map with one key and one value). One of these single-entry maps, for example, would be {"Title": "Steppenwolf"}.
The default processing for a single-entry map of the form { "Title": "Steppenwolf" } is to return the value unchanged. This is achieved by applying templates to the string "Steppenwolf"; the default template rule for strings returns the string unchanged.
When a single-entry map in the form { "Note": "out of print" } is encountered, no output is produced, meaning that entry in the parent map is effectively dropped. This is because there is an explicit template rule with match="record(Note)" that matches such single-entry maps.
When a single-entry map in the form "Authors": [ "Bruce Betts", "Erica Colon" ] is encountered, a new single-entry map is produced; it has the same key ("Authors"), and a value obtained by applying templates to the array [ "Bruce Betts", "Erica Colon" ]. The default processing for an array, in which none of the constituents are matched by explicit template rules, ends up delivering a copy of the array.
When the single-entry map "Authors": [ "Enid Blyton", { "Note": "possibly misattributed" } ] is encountered, the recursive processing results in templates being applied to the map { "Note": "possibly misattributed" }. This matches the template rule having match="record(Note)", which returns no output, so the entry is effectively deleted.
Note:
The map entry is deleted, but the map itself remains, so the value becomes "Authors": [ "Enid Blyton", map: {} ].
The effect of processing a tree using a mode that specifies on-no-match="deep-skip" is that where no explicit template rule is specified for an element, that element and all its descendants are ignored, and are not copied to the result tree.
The effect of choosing on-no-match="deep-skip" is as follows:
The built-in rule for document nodes is equivalent to calling xsl:apply-templates with no select attribute, and with the mode attribute set to #current. If the built-in rule was invoked with parameters, those parameters are passed on in the implicit xsl:apply-templates instruction.
In the case where there are no parameters, this is equivalent to the following rule:
<xsl:template match="document-node()" mode="M"> <xsl:apply-templates mode="#current"/> </xsl:template>
The built-in rule for all items other than document nodes (that is, for all other kinds of node, as well as atomic items and functions, including maps and and arrays) is to do nothing, that is, to return an empty sequence (without applying templates to any children or ancestors).
This is equivalent to the following rule:
<xsl:template match="." mode="M"/>
The effect of processing a tree using a mode that specifies on-no-match="shallow-skip" is to drop both the textual content and the markup from the result document, except where there is an explicit user-written template rule that dictates otherwise.
The built-in rule for document nodes and element nodes applies templates (in the current mode) first to the node’s attributes and then to its children. If the built-in rule was invoked with parameters, those parameters are passed on in the implicit xsl:apply-templates instructions.
In the case where there are no parameters, this is equivalent to the following rule:
<xsl:template match="document-node()|element()" mode="M"> <xsl:apply-templates select="@*" mode="#current"/> <xsl:apply-templates mode="#current"/> </xsl:template>
The built-in template rule for all other kinds of node, and for atomic items and functions (including maps, but not arrays) is empty: that is, when the item is matched, the built-in template rule returns an empty sequence.
This is equivalent to the following rule:
<xsl:template match="." mode="M"/>
The built-in template rule for arrays (see 22 Arrays) is to apply templates to the members of the array. It is equivalent to invoking xsl:apply-templates with the select attribute set to ?* (which selects the members of the array), and with the mode attribute set to #current. If the built-in rule was invoked with parameters, those parameters are passed on in the implicit xsl:apply-templates instruction.
This is equivalent to the following in the case where there are no parameters:
<xsl:template match=".[. instance of array(*)]" mode="M"> <xsl:apply-templates mode="#current" select="?*"/> </xsl:template>
The effect of choosing on-no-match="fail" for a mode is that every item selected in an xsl:apply-templates instruction must be matched by an explicit user-written template rule.
The built-in template rule is effectively:
<xsl:template match="." mode="M"> <xsl:message terminate="yes" error-code="err:XTDE0555"/> </xsl:template>
with an implementation-dependent message body.
[ERR XTDE0555] It is a dynamic error if xsl:apply-templates, xsl:apply-imports or xsl:next-match is used to process an item using a mode whose declaration specifies on-no-match="fail" when there is no template rule in the stylesheet whose match pattern matches that item.
The xsl:apply-imports and xsl:next-match instructions automatically pass supplied parameters to the overridden template rule. [Issue 1861 ]
<!-- 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.56.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.86.9 Built-in Template Rules) if no other template rule is found.
[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.76.8 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.56.6 Conflict Resolution for Template Rules.
This process could be implemented by the following algorithm:
Set a flag active to false.
Follow the rules in 6.56.6 Conflict Resolution for Template Rules to find the best matching rule, without raising any errors or warnings if there are multiple matches.
If the template rule identified is the current template rule, discard this rule, and repeat the process from step 2 with the flag active set to true.
Otherwise, if active is set to false, discard this rule, and repeat the process from step 2, with the flag active still set to false
Otherwise (if active is set to true) use the selected rule.
Note:
An alternative implementation would be to maintain, not just the current template rule, but a list of rules that have been used to process the context item. The implementation of xsl:next-match can then eliminate these rules from the search.
In the absence of type patterns, it is possible to define a total ordering of template rules for each mode, and to exclude those rules that appear before the current template rule in this ordering. The introduction of type patterns makes this approach more challenging, since types are partially ordered.
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.5.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.86.9 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.
A template rule may have parameters. The parameters are declared in the body of the template using xsl:param elements, as described in 9.2 Parameters.
Values for these parameters may be supplied in the calling xsl:apply-templates, xsl:apply-imports, or xsl:next-match instruction by means of xsl:with-param elements appearing as children of the calling instruction. The expanded QName represented by the name attribute of the xsl:with-param element must match the expanded QName represented by the name attribute of the corresponding xsl:param element.
It is not an error for these instructions to supply a parameter that does not match any parameter declared in the template rule that is invoked; unneeded parameter values are simply ignored.
A parameter may be declared as a tunnel parameter by specifying tunnel="yes" in the xsl:param declaration; in this case the caller must supply the value as a tunnel parameter by specifying tunnel="yes" in the corresponding xsl:with-param element. Tunnel parameters differ from ordinary template parameters in that they are passed transparently through multiple template invocations. They are fully described in 10.1.6 Tunnel Parameters.
XSLT offers two constructs for processing each entry in a collection: xsl:for-each and xsl:iterate.
Both instructions can be used to process the items in a sequence, the elements in an array, or the entries in a map. Arrays and maps are processed by reducing them to a sequence of items, so in what follows, the terms item and sequence are used generically.
The main difference between the two constructs is that with xsl:for-each, the processing applied to each item in the sequence is independent of the processing applied to any other item; this means that the items may be processed in any order or in parallel, though the order of the output sequence is well defined and corresponds to the order of the input (sorted if so requested). By contrast, with xsl:iterate, the processing is explicitly sequential: while one item is being processed, values may be computed which are then available for use while the next item is being processed. This makes xsl:iterate suitable for tasks such as creating a running total over a sequence of financial transactions.
A further difference is that xsl:for-each permits sorting of the input sequence, while xsl:iterate does not.
xsl:for-each instruction The xsl:for-each and xsl:apply-templates instructions acquire an attribute separator that can be used to insert content between adjacent items. [This change was in the editor's draft adopted as a baseline when the WG commenced work.] [ 1 January 2022]
<!-- Category: instruction -->
<xsl:for-each
select = expression
separator? = { string } >
<!-- Content: (xsl:sort*, sequence-constructor) -->
</xsl:for-each>
The xsl:for-each instruction processes each in a sequence of items, evaluating the sequence constructor within the xsl:for-each instruction once for each item in that sequence.
The select attribute is required; it contains an expression which is evaluated to produce a sequence, called the input sequence. If there is an xsl:sort element present (see 13 Sorting) the input sequence is sorted to produce a sorted sequence. Otherwise, the sorted sequence is the same as the input sequence.
The xsl:for-each instruction contains a sequence constructor. The sequence constructor is evaluated once for each item in the sorted sequence, with the focus set as follows:
The context item is the item being processed.
The context position is the position of this item in the sorted sequence.
The context size is the size of the sorted sequence (which is the same as the size of the input sequence).
For each item in the input sequence, evaluating the sequence constructor produces a sequence of items (see 5.85.7 Sequence Constructors). These output sequences are concatenated; if item Q follows item P in the sorted sequence, then the result of evaluating the sequence constructor with Q as the context item is concatenated after the result of evaluating the sequence constructor with P as the context item. The result of the xsl:for-each instruction is the concatenated sequence of items.
xsl:for-each to process a sequenceFor example, given an XML document with this structure
<customers> <customer> <name>...</name> <order>...</order> <order>...</order> </customer> <customer> <name>...</name> <order>...</order> <order>...</order> </customer> </customers>
the following would create an HTML document containing a table with a row for each customer element
<xsl:template match="/"> <html> <head> <title>Customers</title> </head> <body> <table> <tbody> <xsl:for-each select="customers/customer"> <tr> <th> <xsl:apply-templates select="name"/> </th> <xsl:for-each select="order"> <td> <xsl:apply-templates/> </td> </xsl:for-each> </tr> </xsl:for-each> </tbody> </table> </body> </html> </xsl:template>
xsl:for-each to process an arrayConsider a JSON document of the form:
[
{ "city": "London", "latitude": 51.5099, "longitude": -0.1181 },
{ "city": "Paris", "latitude": 48.8647, "longitude": 2.3488 },
{ "city": "Berlin", "latitude": 52.5200, "longitude": 13.4049 }
]The following code processes this array to produce an XML representation of the same information. The cities are sorted by name:
<xsl:for-each select="json-doc('input.json')?*"> <xsl:sort select="?city"/> <city number="{position()}" name="{?city}" latitude="{?latitude}" longitude="{?longitude}"/> </xsl:for-each>
In this example it is possible to use the expression $array?* to convert an array to a sequence. This works because the members of the array are all single items. In the more general case (a member of the array might be an empty sequence, corresponding to the JSON value null, or it might be a sequence containing several items), the function array:members can be used to deliver the contents of the array as a sequence of value records. This is illustrated in the next example.
xsl:for-each to process an array containing nullsConsider a JSON document of the form:
[
{ "city": "London", "data": [12.3, 15.6, null, 18.2] },
{ "city": "Paris", "data": [7.9, 19.1, 23.0, null] },
{ "city": "Berlin", "data": [5.6, null, 14.6, 9.5] }
]The requirement is to convert this to the following XML:
<cities> <city name="London" Q1="12.3" Q2="15.6" Q3="" Q4="18.2"/> <city name="Paris" Q1="7.9" Q2="19.1" Q3="23.0" Q4=""/> <city name="Berlin" Q1="5.6" Q2="" Q3="14.6" Q4="9.5"/> </cities>
The following code achieves this transformation:
<xsl:for-each select="json-doc('input.json')?*"> <city name="{?city}"> <xsl:for-each select="array:members(?data)"> <xsl:attribute name="Q{position()}" select="?value"/> </xsl:for-each> </city> </xsl:for-each>
In this example the expression $array?* cannot be used on the inner arrays because JSON nulls (which translate to an empty sequence in XDM) would be lost. Instead the function array:members is used to create a sequence of value records: a non-null entry is represented by a value such as { 'value': 12.3 }, while a null entry would be { 'value': () }.
xsl:for-each to process a mapConsider a JSON document of the form:
{
"London": { "latitude": 51.5099, "longitude": -0.1181 },
"Paris": { "latitude": 48.8647, "longitude": 2.3488 },
"Berlin": { "latitude": 52.5200, "longitude": 13.4049 }
}The following code processes this map to produce an XML representation of the same information. The cities are sorted by name:
<xsl:for-each select="map:pairs(json-doc('input.json'))"> <xsl:sort select="?key"/> <city number="{position()}" name="{?key}" latitude="{?value?latitude}" longitude="{?value?longitude}"/> </xsl:for-each>
In this example the map is decomposed to a sequence of key-value pairs, each represented as a map with two entries, "key" and "value", which can be accessed using the lookup expressions ?key and ?value.
separator attributeIf the separator attribute is present, then its effective value is inserted, as a text node, into the output sequence, immediately after the results of processing each item in the sorted sequence other than the last.
For example, the following instruction:
<xsl:for-each select="6, 3, 9" separator="|"> <xsl:sort select="."/> <xsl:sequence select="., . + 1"/> </xsl:for-each>
produces a sequence comprising, in order: the integer 3, the integer 4, a text node with string value "|", the integer 6, the integer 7, another text node with string value "|", the integer 9, and the integer 10.
The node identity of any text nodes that are inserted is implementation-dependent. Specifically, it is not defined whether all the text nodes inserted in the course of one evaluation of the instruction are identical to each other, nor whether they are identical to the text nodes inserted in the course of another evaluation of this instruction, nor whether they are identical to any other parentless text nodes having the same string value.
If the separator is a zero-length string, then a zero-length text node is inserted into the sequence. (If the sequence is used for constructing the value of a node, then zero-length text nodes will be discarded: see 5.8.25.7.2 Constructing Simple Content and 5.8.15.7.1 Constructing Complex Content.)
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. These facilities are available whether or not streaming is in use, but they are introduced to the language specifically to make streaming easier.
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-streamable, 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-streamable, 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-streamable, 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.
Note:
In some cases, similar effects can be achieved by using the has-children function, which tests whether an element has child nodes without consuming the children. However, use of has-children has the drawback that the function is unselective: it cannot be used to test whether there are any children of relevance to the application. In particular, it returns true if an element contains comments or whitespace text nodes that the application might consider to be insignificant.
Note:
There are no special streamability rules for the three instructions xsl:where-populated, xsl:on-empty, or xsl:on-non-empty. The general streamability rules apply. In many cases the xsl:on-empty and xsl:on-non-empty instructions will generate content that does not depend on the source document, and they will therefore be motionless, but this is not required.
xsl:on-empty and xsl:on-non-empty InstructionsThe following non-normative algorithm explains one possible strategy for streamed evaluation of a sequence constructor containing xsl:on-empty and/or xsl:on-non-empty instructions.
The algorithm makes use of the following mutable variables:
L : a list of instructions awaiting evaluation. Initially empty.
R : a list of items to act as the result of the evaluation. Initially empty.
F : a boolean flag, initially false, to indicate whether any non-vacuous items have been written to R by ordinary instructions. The term ordinary instruction means any node in the sequence constructor other than an xsl:on-empty or xsl:on-non-empty instruction.
The algorithm is as follows:
The nodes in the sequence constructor are evaluated in document order.
When an xsl:on-non-empty instruction is encountered, then:
If F is true, the instruction is evaluated and the result is appended to R.
Otherwise, the instruction is appended to L.
When an ordinary instruction is evaluated:
The results of the evaluation are appended to R, in order.
When a non-vacuous item is about to be appended to R, and F is false, then before appending the item to R, the following actions are taken:
Any xsl:on-non-empty instructions in L are evaluated, in order, and their results are appended to R.
F is set to true.
When an xsl:on-empty instruction is encountered, then:
If F is true, the instruction is ignored.
Otherwise, the existing contents of R are discarded, the instruction is evaluated, and its results are appended to R.
Note:
The need to discard items from R arises only when all the items in R are vacuous. Streaming implementations may therefore need a limited amount of buffering to retain insignificant items until it is known whether they will be needed. However, in many common cases an optimized implementation will be able to discard vacuous items such as empty text nodes immediately, because when a node is being constructed using the rules in 5.8.15.7.1 Constructing Complex Content or 5.8.25.7.2 Constructing Simple Content, such items have no effect on the final outcome.
Otherwise, the instruction is evaluated and its results are appended to R.
The result of the sequence constructor is the list of items in R.
[Definition: The two elements xsl:variable and xsl:param are referred to as variable-binding elements.]
[Definition: The xsl:variable element declares a variable, which may be a global variable or a local variable.]
[Definition: The xsl:param element declares a parameter, which may be a stylesheet parameter, a template parameter, a function parameter, or an xsl:iterate parameter. A parameter is a variable with the additional property that its value can be set by the caller.]
[Definition: A variable is a binding between a name and a value. The value of a variable is any sequence (of nodes, atomic items, and/or function items), as defined in [XDM 3.0].]
A variable-binding with no as or select attribute no longer attempts to create an implicit document node if the sequence constructor contains an xsl:map, xsl:array, or xsl:select child instruction. [Issue 2009 PR 2015 20 May 2025]
A variable-binding element may specify the supplied value of a variable or the default value of a parameter in four different ways.
If the variable-binding element has a select attribute, then the value of the attribute must be an expression and the supplied value of the variable is the value that results from evaluating the expression. In this case, the content of the variable-binding element must be empty.
If the variable-binding element has empty content and has neither a select attribute nor an as attribute, then the supplied value of the variable is a zero-length string. Thus
<xsl:variable name="x"/>
is equivalent to
<xsl:variable name="x" select="''"/>
If a variable-binding element satisfies all the following conditions:
The element has no select attribute
The element has no as attribute
The element has non-empty content (that is, the variable-binding element has one or more child nodes)
There is no xsl:map, xsl:array, or xsl:select element among the element's children
then the content of the variable-binding element specifies the supplied value. The content of the variable-binding element is a sequence constructor; a new document is constructed with a document node having as its children the sequence of nodes that results from evaluating the sequence constructor and then applying the rules given in 5.8.15.7.1 Constructing Complex Content. The value of the variable is then a singleton sequence containing this document node. For further information, see 9.4 Creating Implicit Document Nodes.
Otherwise, the supplied value is the sequence that results from evaluating the (possibly empty) sequence constructor contained within the variable-binding element (see 5.85.7 Sequence Constructors).
These combinations are summarized in the table below.
| select attribute | as attribute | content | Effect |
|---|---|---|---|
| present | absent | empty | Value is obtained by evaluating the select attribute |
| present | present | empty | Value is obtained by evaluating the select attribute, coerced to the type required by the as attribute |
| present | absent | present | Static error |
| present | present | present | Static error |
| absent | absent | empty | Value is a zero-length string |
| absent | present | empty | Value is an empty sequence, provided the as attribute permits an empty sequence |
| absent | absent | includes xsl:map, xsl:array, or xsl:select | Value is obtained by evaluating the sequence constructor |
| absent | absent | present and does not include xsl:map, xsl:array, or xsl:select | Value is a document node whose content is obtained by evaluating the sequence constructor |
| absent | present | present | Value is obtained by evaluating the sequence constructor, coerced to the type required by the as attribute |
[ERR XTSE0620] It is a static error if a variable-binding element has a select attribute and has non-empty content.
The value of the following variable is the sequence of integers (1, 2, 3):
<xsl:variable name="i" as="xs:integer*" select="1 to 3"/>
The value of the following variable is an integer, assuming that the attribute @size exists, and is annotated either as an integer, or as xs:untypedAtomic:
<xsl:variable name="i" as="xs:integer" select="@size"/>
The value of the following variable is a zero-length string:
<xsl:variable name="z"/>
The value of the following variable is a document node containing an empty element as a child:
<xsl:variable name="doc"><c/></xsl:variable>
The value of the following variable is a sequence of integers (2, 4, 6):
<xsl:variable name="seq" as="xs:integer*"> <xsl:for-each select="1 to 3"> <xsl:sequence select=".*2"/> </xsl:for-each> </xsl:variable>
The value of the following variable is a sequence of parentless attribute nodes:
<xsl:variable name="attset" as="attribute()+"> <xsl:attribute name="x">2</xsl:attribute> <xsl:attribute name="y">3</xsl:attribute> <xsl:attribute name="z">4</xsl:attribute> </xsl:variable>
The value of the following variable is an empty sequence:
<xsl:variable name="empty" as="empty-sequence()"/>
The actual value of the variable depends on the supplied value, as described above, and the required type, which is determined by the value of the as attribute.
When a variable is used to select nodes by position, be careful not to do:
<xsl:variable name="n">2</xsl:variable> ... <xsl:value-of select="td[$n]"/>
This will output the values of all the td elements, space-separated (or with XSLT 1.0 behavior, the value of the first td element), because the variable n will be bound to a node, not a number. Instead, do one of the following:
<xsl:variable name="n" select="2"/> ... <xsl:value-of select="td[$n]"/>
or
<xsl:variable name="n">2</xsl:variable> ... <xsl:value-of select="td[position()=$n]"/>
or
<xsl:variable name="n" as="xs:integer">2</xsl:variable> ... <xsl:value-of select="td[$n]"/>
A document node is created implicitly when evaluating an xsl:variable, xsl:param, or xsl:with-param element that has non-empty content and that has no as attribute. The value of the variable is this newly constructed document node. The content of the document node is formed from the result of evaluating the sequence constructor contained within the variable-binding element, as described in 5.8.15.7.1 Constructing Complex Content.
Note:
The construct:
<xsl:variable name="tree"> <a/> </xsl:variable>
can be regarded as a shorthand for:
<xsl:variable name="tree" as="document-node()"> <xsl:document validation="preserve"> <a/> </xsl:document> </xsl:variable>
The base URI of the document node is taken from the base URI of the variable binding element in the stylesheet. (See Section 5.2 base-uri Accessor DM30 in [XDM 3.0])
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.8.15.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.76.8 Modes). Typically, the template rules in module phase1.xsl will be declared with mode="phase1", while those in module phase2.xsl will be declared with mode="phase2":
<xsl:stylesheet version="3.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> <xsl:import href="phase1.xsl"/> <xsl:import href="phase2.xsl"/> <xsl:variable name="intermediate"> <xsl:apply-templates select="/" mode="phase1"/> </xsl:variable> <xsl:template match="/"> <xsl:apply-templates select="$intermediate" mode="phase2"/> </xsl:template> </xsl:stylesheet>
Note:
The algorithm for matching nodes against template rules is exactly the same regardless which tree the nodes come from. If different template rules are to be used when processing different trees, then unless nodes from different trees can be distinguished by means of patterns, it is a good idea to use modes to ensure that each tree is processed using the appropriate set of template rules.
This section describes three constructs that can be used to provide subroutine-like functionality that can be invoked from anywhere in the stylesheet: named templates (see 10.1 Named Templates), named attribute sets (see 10.2 Named Attribute Sets), and stylesheet functions (see 10.3 Stylesheet Functions).
[Definition: The following constructs are classified as invocation constructs: the instructions xsl:call-template, xsl:apply-templates, xsl:apply-imports, and xsl:next-match; XPath function calls that bind to stylesheet functions; XPath dynamic function calls; the functions accumulator-before and accumulator-after; the [xsl:]use-attribute-sets attribute. These all have the characteristic that they can cause evaluation of constructs that are not lexically contained within the calling construct.]
<!-- Category: instruction -->
<xsl:call-template
name = eqname >
<!-- Content: xsl:with-param* -->
</xsl:call-template>
An xsl:call-template instruction invokes a template by name; it has a requiredname attribute that identifies the template to be invoked. Unlike xsl:apply-templates, the xsl:call-template instruction does not change the focus.
[ERR XTSE0650] It is a static error if a package contains an xsl:call-template instruction whose name attribute does not match the name attribute of any named template visible in the containing package (this includes any template defined in this package, as well as templates accepted from used packages whose visibility in this package is not hidden). For more details of the process of binding the called template, see 3.5.4.5 Binding References to Components.
The target template for an xsl:call-template instruction is established using the binding rules described in 3.5.4.5 Binding References to Components. This will always be a template whose name attribute matches the name attribute of the xsl:call-template instruction. It may be a template defined in the same package that has higher import precedence than any other template with this name, or it may be a template accepted from a used package, or (if the template is not defined as private or final) it may be an overriding template in a package that uses the containing package. The result of evaluating an xsl:call-template instruction is the sequence produced by evaluating the sequence constructor contained in its target template (see 5.85.7 Sequence Constructors).
Parameters for a named template can be supplied using xsl:with-param elements as children of the xsl:call-template instruction: see 9.10 Setting Parameter Values.
[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. [XSLT 3.0 Erratum E23, bug 30240].
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.86.9 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: 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.
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: 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.5.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.5.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.8.15.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.
Parameters on functions declared using xsl:function can now be defined as optional, with a default value supplied. [Issue 155 PR 159 30 September 2022]
[Definition: An xsl:function declaration declares the name, parameters, and implementation of a family of stylesheet functions that can be called from any XPath expression within the stylesheet (subject to visibility rules).]
<!-- Category: declaration -->
<xsl:function
name = eqname
as? = sequence-type〔'item()*'〕
visibility? = "public" | "private" | "final" | "abstract"〔'private'〕
streamability? = "unclassified" | "absorbing" | "inspection" | "filter" | "shallow-descent" | "deep-descent" | "ascent" | eqname〔'unclassified'〕
override-extension-function? = boolean〔'yes'〕
[override]? = boolean〔'yes'〕
new-each-time? = "yes" | "true" | "1" | "no" | "false" | "0" | "maybe"
cache? = boolean〔'no'〕 >
<!-- Content: (xsl:param*, sequence-constructor) -->
</xsl:function>
The effect of an xsl:function declaration is to add a function definition to the static context for all XPath expressions used in the stylesheet (including an XPath expression used within a predicate in a pattern).
The content of the xsl:function element consists of zero or more xsl:param elements that specify the formal parameters of the function, followed by a sequence constructor that defines the value to be returned by the function.
The children and attributes of the xsl:function declaration translate directly into properties of the function definition:
The xsl:function/@name attribute defines the function’s name.
The xsl:param children define the function’s parameters:
The xsl:param/@name attribute defines the name of the parameter.
The xsl:param/@required attribute determines whether the parameter is mandatory or optional.
The xsl:param/@as attribute determines the required type of the parameter.
The xsl:param/@select attribute determines a default value for an optional parameter.
The xsl:function/@as attribute defines the return type of the function.
The implementation of the function is defined by the sequence constructor content of the xsl:function element.
An xsl:function declaration can only appear as a top-level element in a stylesheet module.
The result of the function, if all arguments are supplied, is the result of evaluating the contained sequence constructor.
If a reduced-arity form of the function is invoked by omitting optional arguments, then the result of the function is obtained by evaluating the sequence constructor after binding the omitted arguments to their default values, which are obtained by evaluating the select attribute or sequence constructor of the relevant xsl:param element, as described in 9.2.2 Default Values of Parameters.
Within the sequence constructor, the focus is initially absent; this means that any attempt to reference the context item, context position, or context size is a type error. (See [ERR XPDY0002] XP40.)
It is not possible within the body of the stylesheet function to access the values of local variables that were in scope in the place where the function call was written. Global variables, however, remain available.
The optional as attribute indicates the required type of the result of the function. The value of the as attribute is a SequenceType.
[ERR XTTE0780] If the as attribute is specified, then the result evaluated by the sequence constructor (see 5.85.7 Sequence Constructors) is converted to the required type, using the coercion rules. It is a type error if this conversion fails. If the as attribute is omitted, the calculated result is used as supplied, and no conversion takes place.
Note:
Using the xsl:value-of instruction to deliver the function result is generally a mistake, except in the rare case where the function is actually intended to return a text node. For functions that return atomic items such as strings, numbers, or booleans, using xsl:sequence or xsl:select is generally better because it avoids wrapping the value in a text node and then immediately unwrapping it again, with possible loss of type information.
This section describes instructions that directly create new nodes.
[Definition: In a sequence constructor, an element in the stylesheet that does not belong to the XSLT namespace and that is not an extension instruction (see 24.2 Extension Instructions) is classified as a literal result element.] A literal result element is evaluated to construct a new element node with the same expanded QName (that is, the same namespace URI, local name, and namespace prefix). The result of evaluating a literal result element is a node sequence containing one element, the newly constructed element node.
The content of the element is a sequence constructor (see 5.85.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.8.15.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.)
Attribute nodes for a literal result element may be created by including xsl:attribute instructions within the sequence constructor. Additionally, attribute nodes are created corresponding to the attributes of the literal result element in the stylesheet, and as a result of expanding the xsl:use-attribute-sets attribute of the literal result element, if present.
The sequence that is used to construct the content of the literal result element (as described in 5.8.15.7.1 Constructing Complex Content) is the concatenation of the following four sequences, in order:
The sequence of namespace nodes produced as described in 11.1.3 Namespace Nodes for Literal Result Elements.
The sequence of attribute nodes produced by expanding the xsl:use-attribute-sets attribute (if present) following the rules given in 10.2 Named Attribute Sets
The attributes produced by processing the attributes of the literal result element itself, other than attributes in the XSLT namespace. The way these are processed is described below.
The sequence produced by evaluating the contained sequence constructor, if the element is not empty.
Note:
The significance of this order is that an attribute produced by an xsl:attribute, xsl:copy, or xsl:copy-of instruction in the content of the literal result element takes precedence over an attribute produced by expanding an attribute of the literal result element itself, which in turn takes precedence over an attribute produced by expanding the xsl:use-attribute-sets attribute. This is because of the rules in 5.8.15.7.1 Constructing Complex Content, which specify that when two or more attributes in the sequence have the same name, all but the last of the duplicates are discarded.
Although the above rules place namespace nodes before attributes, this is not strictly necessary, because the rules in 5.8.15.7.1 Constructing Complex Content allow the namespaces and attributes to appear in any order so long as both come before other kinds of node. The order of namespace nodes and attribute nodes in the sequence has no effect on the relative position of the nodes in document order once they are added to a tree.
Each attribute of the literal result element, other than an attribute in the XSLT namespace, is processed to produce an attribute for the element in the result tree.
The value of such an attribute is interpreted as an attribute value template: it can therefore contain expressions contained in curly brackets ({}). The new attribute node will have the same expanded QName (that is, the same namespace URI, local name, and namespace prefix) as the attribute in the stylesheet tree, and its string value will be the same as the effective value of the attribute in the stylesheet tree. The type annotation on the attribute will initially be xs:untypedAtomic, and the typed value of the attribute node will be the same as its string value.
Note:
The eventual type annotation of the attribute in the result tree depends on the xsl:validation and xsl:type attributes of the parent literal result element, and on the instructions used to create its ancestor elements. If the xsl:validation attribute is set to preserve or strip, the type annotation will be xs:untypedAtomic, and the typed value of the attribute node will be the same as its string value. If the xsl:validation attribute is set to strict or lax, or if the xsl:type attribute is used, the type annotation on the attribute will be set as a result of the schema validation process applied to the parent element. If neither attribute is present, the type annotation on the attribute will be xs:untypedAtomic.
If the name of a constructed attribute is xml:id, the processor must perform attribute value normalization by effectively applying the normalize-space function to the value of the attribute, and the resulting attribute node must be given the is-id property.
Note:
If the attribute name is xml:space, it is not an error when the value is something other than default or preserve. Although the XML specification states that other values are erroneous, a document containing such values is well-formed; if erroneous values are to be rejected, schema validation should be used.
Note:
The xml:base, xml:lang, xml:space, and xml:id attributes have two effects in XSLT. They behave as standard XSLT attributes, which means for example that if they appear on a literal result element, they will be copied to the result tree in the same way as any other attribute. In addition, they have their standard meaning as defined in the core XML specifications. Thus, an xml:base attribute in the stylesheet affects the base URI of the element on which it appears, and an xml:space attribute affects the interpretation of whitespace text nodes within that element. One consequence of this is that it is inadvisable to write these attributes as attribute value templates: although an XSLT processor will understand this notation, the XML parser will not. See also 11.1.4 Namespace Aliasing which describes how to use xsl:namespace-alias with these attributes.
The same is true of the schema-defined attributes xsi:type, xsi:nil, xsi:noNamespaceSchemaLocation, and xsi:schemaLocation. If the stylesheet is processed by a schema processor, these attributes will be recognized and interpreted by the schema processor, but in addition the XSLT processor treats them like any other attribute on a literal result element: that is, their effective value (after expanding attribute value templates) is copied to the result tree in the same way as any other attribute. If the result tree is validated, the copied attributes will again be recognized and interpreted by the schema processor.
None of these attributes will be generated in the result tree unless the stylesheet writes them to the result tree explicitly, in the same way as any other attribute.
[ERR XTSE0805] It is a static error if an attribute on a literal result element is in the XSLT namespace, unless it is one of the attributes explicitly defined in this specification.
Note:
If there is a need to create attributes in the XSLT namespace, this can be achieved using xsl:attribute, or by means of the xsl:namespace-alias declaration.
The created element node will have a copy of the namespace nodes that were present on the element node in the stylesheet tree with the exception of any namespace node whose string value is designated as an excluded namespace. Special considerations apply to aliased namespaces: see 11.1.4 Namespace Aliasing.
The following namespaces are designated as excluded namespaces:
The XSLT namespace URI (http://www.w3.org/1999/XSL/Transform)
A namespace URI declared as an extension namespace (see 24.2 Extension Instructions)
A namespace URI designated by using an [xsl:]exclude-result-prefixes attribute either on the literal result element itself or on an ancestor element. The attribute must be in the XSLT namespace only if its parent element is not in the XSLT namespace.
The value of the attribute is either #all, or a whitespace-separated list of tokens, each of which is either a namespace prefix or #default. The namespace bound to each of the prefixes is designated as an excluded namespace.
[ERR XTSE0808] It is a static error if a namespace prefix is used within the [xsl:]exclude-result-prefixes attribute and there is no namespace binding in scope for that prefix.
Note:
The prefix must be declared in a native namespace binding, not in a fixed namespace binding.
The default namespace of the parent element of the [xsl:]exclude-result-prefixes attribute (see Section 6.2 Element Nodes DM30) may be designated as an excluded namespace by including #default in the list of namespace prefixes.
[ERR XTSE0809] It is a static error if the value #default is used within the [xsl:]exclude-result-prefixes attribute and the parent element of the [xsl:]exclude-result-prefixes attribute has no default namespace.
The value #all indicates that all namespaces that are in scope for the stylesheet element that is the parent of the [xsl:]exclude-result-prefixes attribute are designated as excluded namespaces.
The designation of a namespace as an excluded namespace is effective within the subtree of the stylesheet module rooted at the element bearing the [xsl:]exclude-result-prefixes attribute; a subtree rooted at an xsl:stylesheet element does not include any stylesheet modules imported or included by children of that xsl:stylesheet element.
The excluded namespaces, as described above, only affect namespace nodes copied from the stylesheet when processing a literal result element. There is no guarantee that an excluded namespace will not appear on the result tree for some other reason. Namespace nodes are also written to the result tree as part of the process of namespace fixup (see 5.8.35.7.3 Namespace Fixup), or as the result of instructions such as xsl:copy and xsl:element.
Note:
When a stylesheet uses a namespace declaration only for the purposes of addressing a source tree, specifying the prefix in the [xsl:]exclude-result-prefixes attribute will avoid superfluous namespace declarations in the serialized result tree. The attribute is also useful to prevent namespaces used solely for the naming of stylesheet functions or extension functions from appearing in the serialized result tree.
In XSLT 4.0, a simpler approach is to declare such namespaces in a fixed-namespaces attribute on the xsl:stylesheet element: see 3.7.1 The fixed-namespaces Attribute. Namespace prefixes declared in that way are not eligible to be used in the names of literal result elements and their attributes, and they are not copied into the result tree.
Consider the following stylesheet:
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:a="a.uri" xmlns:b="b.uri" exclude-result-prefixes="#all"> <xsl:template match="/"> <foo xmlns:c="c.uri" xmlns:d="d.uri" xmlns:a2="a.uri" xsl:exclude-result-prefixes="c"/> </xsl:template> </xsl:stylesheet>
The result of this stylesheet will be:
<foo xmlns:d="d.uri"/>
The namespaces a.uri and b.uri are excluded by virtue of the exclude-result-prefixes attribute on the xsl:stylesheet element, and the namespace c.uri is excluded by virtue of the xsl:exclude-result-prefixes attribute on the foo element. The setting #all does not affect the namespace d.uri because d.uri is not an in-scope namespace for the xsl:stylesheet element. The element in the result tree does not have a namespace node corresponding to xmlns:a2="a.uri" because the effect of exclude-result-prefixes is to designate the namespace URI a.uri as an excluded namespace, irrespective of how many prefixes are bound to this namespace URI.
If the stylesheet is changed so that the literal result element has an attribute b:bar="3", then the element in the result tree will typically have a namespace declaration xmlns:b="b.uri" (the processor may choose a different namespace prefix if this is necessary to avoid conflicts). The exclude-result-prefixes attribute makes b.uri an excluded namespace, so the namespace node is not automatically copied from the stylesheet, but the presence of an attribute whose name is in the namespace b.uri forces the namespace fixup process (see 5.8.35.7.3 Namespace Fixup) to introduce a namespace node for this namespace.
A literal result element may have an optional xsl:inherit-namespaces attribute, with the value yes or no. The default value is yes. If the value is set to yes, or is omitted, then the namespace nodes created for the newly constructed element are copied to the children and descendants of the newly constructed element, as described in 5.8.15.7.1 Constructing Complex Content. If the value is set to no, then these namespace nodes are not automatically copied to the children. This may result in namespace undeclarations (such as xmlns="" or, in the case of XML 1.1, xmlns:p="") appearing on the child elements when they are serialized.
xsl:element<!-- Category: instruction -->
<xsl:element
name = { qname }
namespace? = { uri }
inherit-namespaces? = boolean〔'yes'〕
use-attribute-sets? = eqnames〔''〕
type? = eqname
validation? = "strict" | "lax" | "preserve" | "strip" >
<!-- Content: sequence-constructor -->
</xsl:element>
The xsl:element instruction allows an element to be created with a computed name. The expanded QName of the element to be created is specified by a requiredname attribute and an optional namespace attribute.
The result of evaluating the xsl:element instruction, in usual circumstances, is the newly constructed element node.
The content of the xsl:element instruction is a sequence constructor for the children, attributes, and namespaces of the created element. The sequence obtained by evaluating this sequence constructor (see 5.85.7 Sequence Constructors) is used to construct the content of the element, as described in 5.8.15.7.1 Constructing Complex Content.
The xsl:element element may have a use-attribute-sets attribute, whose value is a whitespace-separated list of QNames that identify xsl:attribute-set declarations. If this attribute is present, it is expanded as described in 10.2 Named Attribute Sets to produce a sequence of attribute nodes. This sequence is prepended to the sequence produced as a result of evaluating the sequence constructor, as described in 5.8.15.7.1 Constructing Complex Content.
The name attribute is interpreted as an attribute value template, whose effective valuemust be a lexical QName.
[ERR XTDE0820] It is a dynamic error if the effective value of the name attribute is not a lexical QName.
[ERR XTDE0830] In the case of an xsl:element instruction with no namespace attribute, it is a dynamic error if the effective value of the name attribute is a lexical QName whose prefix is not declared in the applicable static namespaces for the xsl:element instruction.
Note:
If a fixed-namespaces attribute is present on the containing xsl:stylesheet or xsl:package element, then the prefix must be declared in that attribute, not in a native namespace binding.
If the namespace attribute is not present then the lexical QName is expanded into an expanded QName using the namespace declarations in effect for the xsl:element element, including any default namespace declaration.
If the namespace attribute is present, then it too is interpreted as an attribute value template. The effective valuemust be in the lexical space of the xs:anyURI type. If the string is zero-length, then the expanded QName of the element has a null namespace URI. Otherwise, the string is used as the namespace URI of the expanded QName of the element to be created. The local part of the lexical QName specified by the name attribute is used as the local part of the expanded QName of the element to be created.
[ERR XTDE0835] It is a dynamic error if the effective value of the namespace attribute is not in the lexical space of the xs:anyURI datatype or if it is the string http://www.w3.org/2000/xmlns/.
Note:
The XDM data model requires the name of a node to be an instance of xs:QName, and XML Schema defines the namespace part of an xs:QName to be an instance of xs:anyURI. However, the schema specification, and the specifications that it refers to, give implementations some flexibility in how strictly they enforce these constraints.
The prefix of the lexical QName specified in the name attribute (or the absence of a prefix) is copied to the prefix part of the expanded QName representing the name of the new element node. In the event of a conflict a prefix may subsequently be added, changed, or removed during the namespace fixup process (see 5.8.35.7.3 Namespace Fixup). The term conflict here means any violation of the constraints defined in [XDM 3.0], for example the use of the same prefix to refer to two different namespaces in the element and in one of its attributes, the use of the prefix xml to refer to a namespace other than the XML namespace, or any use of the prefix xmlns.
The xsl:element instruction has an optional inherit-namespaces attribute, with the value yes or no. The default value is yes. If the value is set to yes, or is omitted, then the namespace nodes created for the newly constructed element (whether these were copied from those of the source node, or generated as a result of namespace fixup) are copied to the children and descendants of the newly constructed element, as described in 5.8.15.7.1 Constructing Complex Content. If the value is set to no, then these namespace nodes are not automatically copied to the children. This may result in namespace undeclarations (such as xmlns="" or, in the case of XML Namespaces 1.1, xmlns:p="") appearing on the child elements when the element is serialized.
The base URI of the new element is copied from the base URI of the xsl:element instruction 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) against the base URI of the xsl:element instruction in the stylesheet. (Note, however, that this is only relevant when creating parentless elements. When the new element is copied to form a child of an element or document node, the base URI of the new copy is taken from that of its new parent.)
The values of the nilled, is-id, and is-idrefs properties of the new element depend on the type and validation attributes of the xsl:element instruction, as explained in 25.4 Validation.
xsl:attribute<!-- Category: instruction -->
<xsl:attribute
name = { qname }
namespace? = { uri }
select? = expression
separator? = { string }
type? = eqname
validation? = "strict" | "lax" | "preserve" | "strip" >
<!-- Content: sequence-constructor -->
</xsl:attribute>
The xsl:attribute element can be used to add attributes to result elements whether created by literal result elements in the stylesheet or by instructions such as xsl:element or xsl:copy. The expanded QName of the attribute to be created is specified by a requiredname attribute and an optional namespace attribute. Except in error cases, the result of evaluating an xsl:attribute instruction is the newly constructed attribute node.
The string value of the new attribute node may be defined either by using the select attribute, or by the sequence constructor that forms the content of the xsl:attribute element. These are mutually exclusive: if the select attribute is present then the sequence constructor must be empty, and if the sequence constructor is non-empty then the select attribute must be absent. If the select attribute is absent and the sequence constructor is empty, then the string value of the new attribute node will be a zero-length string. The way in which the value is constructed is specified in 5.8.25.7.2 Constructing Simple Content.
[ERR XTSE0840] It is a static error if the select attribute of the xsl:attribute element is present unless the element has empty content.
If the separator attribute is present, then the effective value of this attribute is used to separate adjacent items in the result sequence, as described in 5.8.25.7.2 Constructing Simple Content. In the absence of this attribute, the default separator is U+0020 (SPACE) when the content is specified using the select attribute, or a zero-length string when the content is specified using a sequence constructor.
The name attribute is interpreted as an attribute value template, whose effective valuemust be a lexical QName.
[ERR XTDE0850] It is a dynamic error if the effective value of the name attribute is not a lexical QName.
[ERR XTDE0855] In the case of an xsl:attribute instruction with no namespace attribute, it is a dynamic error if the effective value of the name attribute is the string xmlns.
[ERR XTDE0860] In the case of an xsl:attribute instruction with no namespace attribute, it is a dynamic error if the effective value of the name attribute is a lexical QName whose prefix is not declared in the applicable static namespaces for the xsl:attribute instruction.
Note:
If a fixed-namespaces attribute is present on the containing xsl:stylesheet or xsl:package element, then the prefix must be declared in that attribute, not in a native namespace binding.
If the namespace attribute is not present, then the lexical QName is expanded into an expanded QName using the namespace declarations in effect for the xsl:attribute element, not including any default namespace declaration.
If the namespace attribute is present, then it too is interpreted as an attribute value template. The effective valuemust be in the lexical space of the xs:anyURI type. If the string is zero-length, then the expanded QName of the attribute has a null namespace URI. Otherwise, the string is used as the namespace URI of the expanded QName of the attribute to be created. The local part of the lexical QName specified by the name attribute is used as the local part of the expanded QName of the attribute to be created.
[ERR XTDE0865] It is a dynamic error if the effective value of the namespace attribute is not in the lexical space of the xs:anyURI datatype or if it is the string http://www.w3.org/2000/xmlns/.
Note:
The same considerations apply as for elements: [see ERR XTDE0835] in 11.2 Creating Element Nodes Using xsl:element.
The prefix of the lexical QName specified in the name attribute (or the absence of a prefix) is copied to the prefix part of the expanded QName representing the name of the new attribute node. In the event of a conflict this prefix may subsequently be added, changed, or removed during the namespace fixup process (see 5.8.35.7.3 Namespace Fixup). If the attribute is in a non-null namespace and no prefix is specified, then the namespace fixup process will invent a prefix. The term conflict here means any violation of the constraints defined in [XDM 3.0], for example the use of the same prefix to refer to two different namespaces in the element and in one of its attributes, the use of the prefix xml to refer to a namespace other than the XML namespace, or any use of the prefix xmlns.
If the name of a constructed attribute is xml:id, the processor must perform attribute value normalization by effectively applying the normalize-space function to the value of the attribute, and the resulting attribute node must be given the is-id property. This applies whether the attribute is constructed using the xsl:attribute instruction or whether it is constructed using an attribute of a literal result element. This does not imply any constraints on the value of the attribute, or on its uniqueness, and it does not affect the type annotation of the attribute, unless the containing document is validated.
Note:
The effect of setting the is-id property is that the parent element can be located within the containing document by use of the id function. In effect, XSLT when constructing a document performs some of the functions of an xml:id processor, as defined in [xml:id]; the other aspects of xml:id processing are performed during validation.
The following instruction creates the attribute colors="red green blue":
<xsl:attribute name="colors" select="'red', 'green', 'blue'"/>
It is not an error to write:
<xsl:attribute name="xmlns:xsl" namespace="file://some.namespace" select="'http://www.w3.org/1999/XSL/Transform'"/>
However, this will not result in the namespace declaration xmlns:xsl="http://www.w3.org/1999/XSL/Transform" being output. Instead, it will produce an attribute node with local name xsl, and with a system-allocated namespace prefix mapped to the namespace URI file://some.namespace. This is because the namespace fixup process is not allowed to use xmlns as the name of a namespace node.
As described in 5.8.15.7.1 Constructing Complex Content, in a sequence that is used to construct the content of an element, any attribute nodes must appear in the sequence before any element, text, comment, or processing instruction nodes. Where the sequence contains two or more attribute nodes with the same expanded QName, the one that comes last is the only one that takes effect.
Note:
If a collection of attributes is generated repeatedly, this can be done conveniently by using named attribute sets: see 10.2 Named Attribute Sets
This section describes three different ways of creating text nodes: by means of literal text nodes in the stylesheet, or by using the xsl:text and xsl:value-of instructions. It is also possible to create text nodes using the xsl:number instruction described in 12 Numbering.
If and when the sequence that results from evaluating a sequence constructor is used to form the content of a node, as described in 5.8.25.7.2 Constructing Simple Content and 5.8.15.7.1 Constructing Complex Content, adjacent text nodes in the sequence are merged. Within the sequence itself, however, they exist as distinct nodes.
The following function returns a sequence of three text nodes:
<xsl:function name="f:wrap"> <xsl:param name="s"/> <xsl:text>(</xsl:text> <xsl:value-of select="$s"/> <xsl:text>)</xsl:text> </xsl:function>
When this function is called as follows:
<xsl:value-of select="f:wrap('---')"/>
the result is:
(---)
No additional spaces are inserted, because the calling xsl:value-of instruction merges adjacent text nodes before atomizing the sequence. However, the result of the instruction:
<xsl:value-of select="data(f:wrap('---'))"/>
is:
( --- )
because in this case the three text nodes are atomized to form three strings, and spaces are inserted between adjacent strings.
It is possible to construct text nodes whose string value is zero-length. A zero-length text node, when atomized, produces a zero-length string. However, zero-length text nodes are ignored when they appear in a sequence that is used to form the content of a node, as described in 5.8.15.7.1 Constructing Complex Content and 5.8.25.7.2 Constructing Simple Content.
xsl:text<!-- Category: instruction -->
<xsl:text
[disable-output-escaping]? = boolean〔'no'〕 >
<!-- Content: #PCDATA -->
</xsl:text>
The xsl:text element is evaluated to construct a new text node.
If the element or one of its ancestors has an [xsl:]expand-text attribute, and the nearest ancestor with such an attribute has the value yes, then any unescaped curly brackets in the value of the element indicate the presence of text value templates, which are expanded as described in 5.7.25.6.2 Text Value Templates.
In the absence of such an attribute, or if the effective value is no, the content of the xsl:text element is a single text node whose value forms the string value of the new text node. An xsl:text element may be empty, in which case the result of evaluating the instruction is a text node whose string value is the zero-length string.
The result of evaluating an xsl:text instruction is the newly constructed text node.
A text node that is an immediate child of an xsl:text instruction will not be stripped from the stylesheet tree, even if it consists entirely of whitespace (see 4.3.2 Stripping Whitespace from a Source Tree).
For the effect of the deprecateddisable-output-escaping attribute, see 26.5 Disabling Output Escaping
Note:
It is not always necessary to use the xsl:text instruction to write text nodes to the result tree. Literal text can be written to the result tree by including it anywhere in a sequence constructor, while computed text can be output using the xsl:value-of instruction. The principal reason for using xsl:text is that it offers improved control over whitespace handling.
xsl:value-ofWithin a sequence constructor, the xsl:value-of instruction can be used to generate computed text nodes. The xsl:value-of instruction computes the text using an expression that is specified as the value of the select attribute, or by means of contained instructions. This might, for example, extract text from a source tree or insert the value of a variable.
<!-- Category: instruction -->
<xsl:value-of
select? = expression
separator? = { string }
[disable-output-escaping]? = boolean〔'no'〕 >
<!-- Content: sequence-constructor -->
</xsl:value-of>
The xsl:value-of instruction is evaluated to construct a new text node; the result of the instruction is the newly constructed text node.
The string value of the new text node may be defined either by using the select attribute, or by the sequence constructor (see 5.85.7 Sequence Constructors) that forms the content of the xsl:value-of element. These are mutually exclusive: if the select attribute is present then the sequence constructor must be empty, and if the sequence constructor is non-empty then the select attribute must be absent. If the select attribute is absent and the sequence constructor is empty, then the result of the instruction is a text node whose string value is zero-length. The way in which the value is constructed is specified in 5.8.25.7.2 Constructing Simple Content.
[ERR XTSE0870] It is a static error if the select attribute of the xsl:value-of element is present when the content of the element is non-empty.
If the separator attribute is present, then the effective value of this attribute is used to separate adjacent items in the result sequence, as described in 5.8.25.7.2 Constructing Simple Content. In the absence of this attribute, the default separator is U+0020 (SPACE) when the content is specified using the select attribute, or a zero-length string when the content is specified using a sequence constructor.
Special rules apply when the instruction is processed with XSLT 1.0 behavior. If no separator attribute is present, and if the select attribute is present, then all items in the atomized result sequence other than the first are ignored.
The instruction:
<x><xsl:value-of select="1 to 4" separator="|"/></x>
produces the output:
<x>1|2|3|4</x>
Note:
The xsl:copy-of element can be used to copy a sequence of nodes to the result tree without atomization. See 11.9.2 Deep Copy.
For the effect of the deprecateddisable-output-escaping attribute, see 26.5 Disabling Output Escaping
<!-- Category: instruction -->
<xsl:document
validation? = "strict" | "lax" | "preserve" | "strip"
type? = eqname >
<!-- Content: sequence-constructor -->
</xsl:document>
The xsl:document instruction is used to create a new document node. The content of the xsl:document element is a sequence constructor for the children of the new document node. A document node is created, and the sequence obtained by evaluating the sequence constructor is used to construct the content of the document, as described in 5.8.15.7.1 Constructing Complex Content.
Except in error situations, the result of evaluating the xsl:document instruction is a single node, the newly constructed document node.
Note:
The new document is not serialized. To construct a document that is to form a final result rather than an intermediate result, use the xsl:result-document instruction described in 25.1 Creating Secondary Results.
The optional attributes type and validation may be used on the xsl:document instruction to validate the contents of the new document, and to determine the type annotation that elements and attributes within the result tree will carry. The permitted values and their semantics are described in 25.4.2 Validating Document Nodes.
The base URI of the new document node is taken from the base URI of the xsl:document instruction.
The document-uri and unparsed-entities properties of the new document node are set to empty.
The following example creates a temporary tree held in a variable. The use of an enclosed xsl:document instruction ensures that uniqueness constraints defined in the schema for the relevant elements are checked.
<xsl:variable name="tree" as="document-node()"> <xsl:document validation="strict"> <xsl:apply-templates/> </xsl:document> </xsl:variable>
<!-- Category: instruction -->
<xsl:processing-instruction
name = { ncname }
select? = expression >
<!-- Content: sequence-constructor -->
</xsl:processing-instruction>
The xsl:processing-instruction element is evaluated to create a processing instruction node.
The xsl:processing-instruction element has a requiredname attribute that specifies the name of the processing instruction node. The value of the name attribute is interpreted as an attribute value template.
The string value of the new processing-instruction node may be defined either by using the select attribute, or by the sequence constructor that forms the content of the xsl:processing-instruction element. These are mutually exclusive: if the select attribute is present then the sequence constructor must be empty, and if the sequence constructor is non-empty then the select attribute must be absent. If the select attribute is absent and the sequence constructor is empty, then the string value of the new processing-instruction node will be a zero-length string. The way in which the value is constructed is specified in 5.8.25.7.2 Constructing Simple Content.
[ERR XTSE0880] It is a static error if the select attribute of the xsl:processing-instruction element is present unless the element has empty content.
Except in error situations, the result of evaluating the xsl:processing-instruction instruction is a single node, the newly constructed processing instruction node.
This instruction:
<xsl:processing-instruction name="xml-stylesheet" select="('href="book.css"', 'type="text/css"')"/>
creates the processing instruction
<?xml-stylesheet href="book.css" type="text/css"?>
Note that the xml-stylesheet processing instruction contains pseudo-attributes in the form name="value". Although these have the same textual form as attributes in an element start tag, they are not represented as XDM attribute nodes, and cannot therefore be constructed using xsl:attribute instructions.
[ERR XTDE0890] It is a dynamic error if the effective value of the name attribute is not both an NCNameNames and a PITargetXML.
Note:
Because these rules disallow the name xml, the xsl:processing-instruction cannot be used to output an XML declaration. The xsl:output declaration should be used to control this instead (see 26 Serialization).
If the result of evaluating the content of the xsl:processing-instruction contains the string ?>, this string is modified by inserting a space between the ? and > characters.
The base URI of the new processing-instruction is copied from the base URI of the xsl:processing-instruction element in the stylesheet. (Note, however, that this is only relevant when creating a parentless processing instruction. When the new processing instruction is copied to form a child of an element or document node, the base URI of the new copy is taken from that of its new parent.)
<!-- Category: instruction -->
<xsl:namespace
name = { ncname }
select? = expression >
<!-- Content: sequence-constructor -->
</xsl:namespace>
The xsl:namespace element is evaluated to create a namespace node. Except in error situations, the result of evaluating the xsl:namespace instruction is a single node, the newly constructed namespace node.
The xsl:namespace element has a requiredname attribute that specifies the name of the namespace node (that is, the namespace prefix). The value of the name attribute is interpreted as an attribute value template. If the effective value of the name attribute is a zero-length string, a namespace node is added for the default namespace.
The string value of the new namespace node (that is, the namespace URI) may be defined either by using the select attribute, or by the sequence constructor that forms the content of the xsl:namespace element. These are mutually exclusive: if the select attribute is present then the sequence constructor must be empty, and if the sequence constructor is non-empty then the select attribute must be absent. Since the string value of a namespace node cannot be a zero-length string, either a select attribute or a non-empty sequence constructor must be present. The way in which the value is constructed is specified in 5.8.25.7.2 Constructing Simple Content.
[ERR XTDE0905] It is a dynamic error if the string value of the new namespace node is not valid in the lexical space of the datatype xs:anyURI, or if it is the string http://www.w3.org/2000/xmlns/.
[ERR XTSE0910] It is a static error if the select attribute of the xsl:namespace element is present when the element has content other than one or more xsl:fallback instructions, or if the select attribute is absent when the element has empty content.
Note the restrictions described in 5.8.15.7.1 Constructing Complex Content for the position of a namespace node relative to other nodes in the node sequence returned by a sequence constructor.
This literal result element:
<data xsi:type="xs:integer" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> <xsl:namespace name="xs" select="'http://www.w3.org/2001/XMLSchema'"/> <xsl:text>42</xsl:text> </data>
would typically cause the output document to contain the element:
<data xsi:type="xs:integer" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">42</data>
In this case, the element is constructed using a literal result element, and the namespace xmlns:xs="http://www.w3.org/2001/XMLSchema" could therefore have been added to the result tree simply by declaring it as one of the in-scope namespaces in the stylesheet. In practice, the xsl:namespace instruction is more likely to be useful in situations where the element is constructed using an xsl:element instruction, which does not copy all the in-scope namespaces from the stylesheet.
[ERR XTDE0920] It is a dynamic error if the effective value of the name attribute is neither a zero-length string nor an NCNameNames, or if it is xmlns.
[ERR XTDE0925] It is a dynamic error if the xsl:namespace instruction generates a namespace node whose name is xml and whose string value is not http://www.w3.org/XML/1998/namespace, or a namespace node whose string value is http://www.w3.org/XML/1998/namespace and whose name is not xml.
[ERR XTDE0930] It is a dynamic error if evaluating the select attribute or the contained sequence constructor of an xsl:namespace instruction results in a zero-length string.
For details of other error conditions that may arise, see 5.85.7 Sequence Constructors.
Note:
It is rarely necessary to use xsl:namespace to create a namespace node in the result tree; in most circumstances, the required namespace nodes will be created automatically, as a side-effect of writing elements or attributes that use the namespace. An example where xsl:namespace is needed is a situation where the required namespace is used only within attribute values in the result document, not in element or attribute names; especially where the required namespace prefix or namespace URI is computed at run-time and is not present in either the source document or the stylesheet.
Adding a namespace node to the result tree will never change the expanded QName of any element or attribute node in the result tree: that is, it will never change the namespace URI of an element or attribute. It might, however, constrain the choice of prefixes when namespace fixup is performed.
Namespace prefixes for element and attribute names are initially established by the rules of the instruction that creates the element or attribute node, and in the event of conflicts, they may be changed by the namespace fixup process described in 5.8.35.7.3 Namespace Fixup. The fixup process ensures that an element has in-scope namespace nodes for the namespace URIs used in the element name and in its attribute names, and the serializer will typically use these namespace nodes to determine the prefix to use in the serialized output. The fixup process cannot generate namespace nodes that are inconsistent with those already present in the tree. This means that it is not possible for the processor to decide the prefix to use for an element or for any of its attributes until all the namespace nodes for the element have been added.
If a namespace prefix is mapped to a particular namespace URI using the xsl:namespace instruction, or by using xsl:copy or xsl:copy-of to copy a namespace node, this prevents the namespace fixup process (and hence the serializer) from using the same prefix for a different namespace URI on the same element.
Given the instruction:
<xsl:element name="p:item" xmlns:p="http://www.example.com/p"> <xsl:namespace name="p">http://www.example.com/q</xsl:namespace> </xsl:element>
a possible serialization of the result tree is:
<ns0:item xmlns:ns0="http://www.example.com/p" xmlns:p="http://www.example.com/q"/>
The processor must invent a namespace prefix for the URI p.uri; it cannot use the prefix p because that prefix has been explicitly associated with a different URI.
Note:
The xsl:namespace instruction cannot be used to generate a namespace undeclaration of the form xmlns="" (nor the new forms of namespace undeclaration permitted in [Namespaces in XML 1.1]). Namespace undeclarations are generated automatically by the serializer if undeclare-prefixes="yes" is specified on xsl:output, whenever a parent element has a namespace node for the default namespace prefix, and a child element has no namespace node for that prefix.
<!-- Category: instruction -->
<xsl:comment
select? = expression >
<!-- Content: sequence-constructor -->
</xsl:comment>
The xsl:comment element is evaluated to construct a new comment node. Except in error cases, the result of evaluating the xsl:comment instruction is a single node, the newly constructed comment node.
The string value of the new comment node may be defined either by using the select attribute, or by the sequence constructor that forms the content of the xsl:comment element. These are mutually exclusive: if the select attribute is present then the sequence constructor must be empty, and if the sequence constructor is non-empty then the select attribute must be absent. If the select attribute is absent and the sequence constructor is empty, then the string value of the new comment node will be a zero-length string. The way in which the value is constructed is specified in 5.8.25.7.2 Constructing Simple Content.
[ERR XTSE0940] It is a static error if the select attribute of the xsl:comment element is present unless the element has empty content.
For example, this
<xsl:comment>This file is automatically generated. Do not edit!</xsl:comment>
would create the comment
<!--This file is automatically generated. Do not edit!-->
In the generated comment node, the processor must insert a space after any occurrence of x2D (hyphen) that is followed by another occurrence of x2D (hyphen) or that ends the comment.
<!-- Category: instruction -->
<xsl:copy
select? = expression
copy-namespaces? = boolean〔'yes'〕
inherit-namespaces? = boolean〔'yes'〕
use-attribute-sets? = eqnames〔''〕
type? = eqname
validation? = "strict" | "lax" | "preserve" | "strip" >
<!-- Content: sequence-constructor -->
</xsl:copy>
The xsl:copy instruction provides a way of copying a selected item. The selected item is the item selected by evaluating the expression in the select attribute if present, or the context item otherwise. If the selected item is a node, evaluating the xsl:copy instruction constructs a copy of the selected node, and the result of the xsl:copy instruction is this newly constructed node. By default, the namespace nodes of the context node are automatically copied as well, but the attributes and children of the node are not automatically copied.
[ERR XTTE0945] It is a type error to use the xsl:copy instruction with no select attribute when the context item is absent.
If the select expression returns an empty sequence, the xsl:copy instruction returns an empty sequence, and the contained sequence constructor is not evaluated.
[ERR XTTE3180] It is a type error if the result of evaluating the select expression is a sequence of more than one item.
When the selected item is an atomic item or function item, the xsl:copy instruction returns this value. The sequence constructor is not evaluated.
When the selected item is an attribute node, text node, comment node, processing instruction node, or namespace node, the xsl:copy instruction returns a new node that is a copy of the context node. The new node will have the same node kind, name, and string value as the context node. In the case of an attribute node, it will also have the same values for the is-id and is-idrefs properties. The sequence constructor is not evaluated.
When the selected item is a document node or element node, the xsl:copy instruction returns a new node that has the same node kind and name as the selected node. The content of the new node is formed by evaluating the sequence constructor contained in the xsl:copy instruction. If the select attribute is present then the sequence constructor is evaluated with the selected item as the singleton focus; otherwise it is evaluated using the context of the xsl:copy instruction unchanged. The sequence obtained by evaluating this sequence constructor is used (after prepending any attribute nodes or namespace nodes as described in the following paragraphs) to construct the content of the document or element node, as described in 5.8.15.7.1 Constructing Complex Content.
When the selected item is a document node, the unparsed-entities property of the existing document node is copied to the new document node.
When the selected item is an element or attribute node, the values of the is-id, is-idrefs, and nilled properties of the new element or attribute depend on the values of the validation and type attributes, as defined in 25.4 Validation.
The xsl:copy instruction has an optional use-attribute-sets attribute, whose value is a whitespace-separated list of QNames that identify xsl:attribute-set declarations. This attribute is used only when copying element nodes. This list is expanded as described in 10.2 Named Attribute Sets to produce a sequence of attribute nodes. This sequence is prepended to the sequence produced as a result of evaluating the sequence constructor.
The xsl:copy instruction has an optional copy-namespaces attribute, with the value yes or no. The default value is yes. The attribute is used only when copying element nodes. If the value is set to yes, or is omitted, then all the namespace nodes of the source element are copied as namespace nodes for the result element. These copied namespace nodes are prepended to the sequence produced as a result of evaluating the sequence constructor (it is immaterial whether they come before or after any attribute nodes produced by expanding the use-attribute-sets attribute). If the value is set to no, then the namespace nodes are not copied. However, namespace nodes will still be added to the result element as required by the namespace fixup process: see 5.8.35.7.3 Namespace Fixup.
The xsl:copy instruction has an optional inherit-namespaces attribute, with the value yes or no. The default value is yes. The attribute is used only when copying element nodes. If the value is set to yes, or is omitted, then the namespace nodes created for the newly constructed element (whether these were copied from those of the source node, or generated as a result of namespace fixup) are copied to the children and descendants of the newly constructed element, as described in 5.8.15.7.1 Constructing Complex Content. If the value is set to no, then these namespace nodes are not automatically copied to the children. This may result in namespace undeclarations (such as xmlns="" or, in the case of XML Namespaces 1.1, xmlns:p="") appearing on the child elements when a final result tree is serialized.
[ERR XTTE0950] It is a type error to use the xsl:copy or xsl:copy-of instruction to copy a node that has namespace-sensitive content if the copy-namespaces attribute has the value no and its explicit or implicit validation attribute has the value preserve. It is also a type error if either of these instructions (with validation="preserve") is used to copy an attribute having namespace-sensitive content, unless the parent element is also copied. A node has namespace-sensitive content if its typed value contains an item of type xs:QName or xs:NOTATION or a type derived therefrom. The reason this is an error is because the validity of the content depends on the namespace context being preserved.
Note:
When attribute nodes are copied, whether with xsl:copy or with xsl:copy-of, the processor does not automatically copy any associated namespace information. The namespace used in the attribute name itself will be declared by virtue of the namespace fixup process (see 5.8.35.7.3 Namespace Fixup) when the attribute is added to an element in the result tree, but if namespace prefixes are used in the content of the attribute (for example, if the value of the attribute is an XPath expression) then it is the responsibility of the stylesheet author to ensure that suitable namespace nodes are added to the result tree. This can be achieved by copying the namespace nodes using xsl:copy, or by generating them using xsl:namespace.
The optional attributes type and validation may be used on the xsl:copy instruction to validate the contents of an element, attribute or document node against a type definition, element declaration, or attribute declaration in a schema, and thus to determine the type annotation that the new copy of an element or attribute node will carry. These attributes are ignored when copying an item that is not an element, attribute or document node. When the node being copied is an element or document node, these attributes also affect the type annotation carried by any elements and attributes that have the copied element or document node as an ancestor. These two attributes are both optional, and if one is specified then the other must be omitted. The permitted values of these attributes and their semantics are described in 25.4 Validation.
Note:
The final type annotation of the node in the result tree also depends on the type and validation attributes of the instructions used to create the ancestors of the node.
When a node is copied, its base URI is copied, except when the result of the xsl:copy instruction is an element node having an xml:base attribute, in which case the base URI of the new node is taken as the value of its xml:base attribute, resolved if it is relative against the base URI of the xsl:copy instruction.
When an xml:id attribute is copied, using either the xsl:copy or xsl:copy-of instruction, it is implementation-defined whether the value of the attribute is subjected to attribute value normalization (that is, effectively applying the normalize-space function).
Note:
In most cases the value will already have been subjected to attribute value normalization on the source tree, but if this processing has not been performed on the source tree, it is not an error for it to be performed on the result tree.
<!-- Category: instruction -->
<xsl:copy-of
select = expression
copy-accumulators? = boolean〔'no'〕
copy-namespaces? = boolean〔'yes'〕
type? = eqname
validation? = "strict" | "lax" | "preserve" | "strip" />
The xsl:copy-of instruction can be used to construct a copy of a sequence of nodes, atomic items, and/or function items with each new node containing copies of all the children, attributes, and (by default) namespaces of the original node, recursively. The result of evaluating the instruction is a sequence of items corresponding one-to-one with the supplied sequence, and retaining its order.
The requiredselect attribute contains an expression, whose value may be any sequence of nodes, atomic items, and/or function items. The items in this sequence are processed as follows:
If the item is an element node, a new element is constructed and appended to the result sequence. The new element will have the same expanded QName as the original, and it will have deep copies of the attribute nodes and children of the element node.
The new element will also have namespace nodes copied from the original element node, unless they are excluded by specifying copy-namespaces="no". If this attribute is omitted, or takes the value yes, then all the namespace nodes of the original element are copied to the new element. If it takes the value no, then none of the namespace nodes are copied: however, namespace nodes will still be created in the result tree as required by the namespace fixup process: see 5.8.35.7.3 Namespace Fixup. This attribute affects all elements copied by this instruction: both elements selected directly by the selectexpression, and elements that are descendants of nodes selected by the select expression.
The values of the is-id, is-idrefs, and nilled properties of the new element depend on the values of the validation and type attributes, as defined in 25.4 Validation.
If the item is a document node, the instruction adds a new document node to the result sequence; the children of this document node will be one-to-one copies of the children of the original document node (each copied according to the rules for its own node kind). The unparsed-entities property of the original document node is copied to the new document node.
If the item is an attribute or namespace node, or a text node, a comment, or a processing instruction, the same rules apply as with xsl:copy (see 11.9.1 Shallow Copy).
If the item is an atomic item or a function item, the value is appended to the result sequence, as with xsl:sequence.
The optional attributes type and validation may be used on the xsl:copy-of instruction to validate the contents of an element, attribute or document node against a type definition, element declaration, or attribute declaration in a schema and thus to determine the type annotation that the new copy of an element or attribute node will carry. These attributes are applied individually to each element, attribute, and document node that is selected by the expression in the select attribute. These attributes are ignored when copying an item that is not an element, attribute or document node.
The specified type and validation apply directly only to elements, attributes and document nodes created as copies of nodes actually selected by the select expression, they do not apply to nodes that are implicitly copied because they have selected nodes as an ancestor. However, these attributes do indirectly affect the type annotation carried by such implicitly copied nodes, as a consequence of the validation process.
These two attributes are both optional, and if one is specified then the other must be omitted. The permitted values of these attributes and their semantics are described in 25.4 Validation.
Errors may occur when copying namespace-sensitive elements or attributes using validation="preserve". [see ERR XTTE0950].
If removal of namespaces is requested using copy-namespaces="no", then any validation that is requested is applied to the tree that remains after the relevant namespaces have been removed. This will cause validation to fail if there is namespace-sensitive content that depends on the presence of the removed namespaces.
For any node N that is explicitly selected by the evaluation of the select expression, the base URI of the new copy is as follows:
If N is an element node having an xml:base attribute, the base URI of the new node is taken as the value of the xml:base attribute, resolved if it is relative against the static base URI of the xsl:copy-of instruction.
Otherwise, the base URI of the new copy is the same as the base URI of N.
For any element or processing-instruction node that has N as an ancestor, the base URI of the new copy is set to be the same as that of its new parent, with the following exception: if a copied element has an xml:base attribute, then its base URI is set to the value of that attribute, resolved if it is relative against the base URI of the new parent node.
Note:
If two elements in a subtree have different base URIs for some reason unconnected with xml:base attributes (for example, if they originated in different external entities), then these differences are lost when the subtree is copied.
Note:
As a consequence of rules specified elsewhere (see 5.8.15.7.1 Constructing Complex Content), if a node created using the xsl:copy-of instruction is subsequently attached as a child to a new element or document node, the final copy of the node inherits its base URI from its new parent node, unless this is overridden using an xml:base attribute.
[XSLT 3.0 Erratum E16, bug 30222]
The effect of the copy-accumulators attribute is described in 18.2.2 Applicability of Accumulators.
XSLT 3.0 introduces a number of constructs that are specifically designed to enable streamed applications to be written, but which are also useful in their own right; it also includes some features that are very specialized to streaming.
Accumulators are 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: 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"> <xsl:apply-templates/> <p>Figure <xsl:value-of select="accumulator-before('figNr')"/></p> </xsl:template>
If a dynamic error occurs when evaluating the initial-value expression of xsl:accumulator, or the select expression of xsl:accumulator-rule, or the sequence constructor contained in xsl:accumulator-rule, then the error is raised as an error from any subsequent call on accumulator-before or accumulator-after that references the accumulator. If no such call on accumulator-before or accumulator-after happens, then the error goes unreported. [XSLT 3.0 Erratum E38, bug 30376].
Note:
In the above rule, the phrase subsequent call is to be understood in terms of functional dependency; that is, a call to accumulator-before or accumulator-after raises an error if the accumulator value at the node in question is functionally dependent on a computation that fails with a dynamic error.
Note:
Particularly in the case of streamed accumulators, this may mean that the implementation has to “hold back” the error until the next time the accumulator is referenced, to give applications the opportunity to catch the error using xsl:try and xsl:catch in a predictable way.
Note:
Errors that occur during the evaluation of the pattern in the match attribute of xsl:accumulator-rule are handled as described in 5.4.36.3.3 Errors in Patterns: specifically, the pattern does not match the relevant node, and no error is raised.
This section contains rules that can be used to determine properties of constructs in the stylesheet — specifically, the posture and sweep of a construct — which enable the streamability of the stylesheet to be assessed.
These properties are used to determine the streamability of:
The xsl:source-document instruction: see 18.1 The xsl:source-document Instruction
Stylesheet functions: see 19.8.5 Classifying Stylesheet Functions
The xsl:merge instruction: see 15.4 Streamable Merging
In each case, the conditions for constructs to be guaranteed-streamable are defined in terms of these properties. The result of this analysis in turn (see 19.10 Streamability Guarantees) imposes rules on how the constructs are handled by processors that implement the streaming feature. The analysis has no effect on the behavior of processors that do not implement this feature.
The analysis is relevant to constructs such as streamable template rules and the xsl:source-document instruction that process a single streamed input document. The xsl:merge instruction, which processes multiple streamed inputs, has its own rules.
The rules in this section operate on the expression tree (more properly, construct tree) that is typically output by the XSLT and XPath parser. For the most part, the rules depend only on identifying the syntactic constructs that are present.
The rules in this section generally consider each component in the stylesheet (and in the case of template rules, each template rule) in isolation. The exception is that where a component contains references to other components (such as global variables, functions, or named templates), then information from the signature of the referenced component is sometimes used. This is invariably information that cannot be changed if a component is overridden in a different package. The analysis thus requires as a pre-condition that function calls and calls on named templates have been resolved to the extent that the corresponding function/template signature is known.
The detailed way in which the construct tree is derived from the lexical form of the stylesheet is not described in this specification. There are many ways in which the tree can be optimized without affecting the result of the rules in this section: for example, a sequence constructor containing a single instruction can be replaced by that instruction, and a parenthesized expression can be replaced by its content.
[Definition: The term construct refers to the union of the following: a sequence constructor, an instruction, an attribute set, a value template, an expression, or a pattern.]
These constructs are classified into construct kinds: in particular, instructions are classified according to the name of the XSLT instruction, and expressions are classified according to the most specific production in the XPath grammar that the expression satisfies. (This means, for example, that 2+2 is classified as an AdditiveExpr, rather than say as a UnionExpr; although it also satisfies the production rule for UnionExpr, AdditiveExpr is more specific.)
[Definition: For every construct kind, there is a set of zero or more operand roles.] For example, an AdditiveExpr has two operand roles, referred to as the left-hand operand and the right-hand operand, while an IfExpr has three, referred to as the condition, the then-clause, and the else-clause. A function call with three arguments has three operand roles, called the first, second, and third arguments. The names of the operand roles for each construct kind are not formally listed, but should be clear from the context.
[Definition: In an actual instance of a construct, there will be a number of operands. Each operand is itself a construct; the construct tree can be defined as the transitive relation between constructs and their operands.] Each operand is associated with exactly one of the operand roles for the construct type. There may be operand roles where the operand is optional (for example, the separator attribute of the xsl:value-of instruction), and there may be operand roles that can be occupied by multiple operands (for example, the xsl:when/@test condition in xsl:choose, or the arguments of the concat function).
Operand roles have a number of properties used in the analysis:
The required type of the operand. This is explicit in the case of function calls (the required type is defined in the function signature of the corresponding function). In other cases it is implicit in the detailed rules for the construct in question. In practice streamability analysis makes only modest use of the required type; the main case where it is relevant is for a function or template call, where knowing that the required type is atomic enables the inference that the operand usage for a supplied node is absorption.
[Definition: The operand usage. This gives information, in the case where the operand value contains nodes, about how those nodes are used. The operand usage takes one of the values absorption, inspection, transmission, or navigation.] The meanings of these terms are explained in 19.3 Operand Roles. If the required type of the operand does not permit nodes to be supplied (for example because the required type is a function item or a map), then the operand usage is inspection, because the only run-time operation on a supplied node will be to inspect it, discover it is a node, and raise a type error.
In the particular case where the required type is atomic, and any supplied nodes are atomized, the operand usage will be absorption, because atomize is a special case of absorption.
[Definition: Whether or not the operand is higher-order. For this purpose an operand O of a construct C is higher-order if the semantics of C potentially require O to be evaluated more than once during a single evaluation of C.] More specifically, O is a higher-order operand of C if any of the following conditions is true:
The context item for evaluation of O is different from the context item for evaluation of C.
C is an instruction and O is a pattern (as with the from and count attributes of xsl:number, and the group-starting-with and group-ending-with attributes of xsl:for-each-group).
C is an XPath for, some, or every expression and O is the expression in its return or satisfies clause.
C is an inline function declaration and O is the expression in its body.
Note:
There is one known case where this definition makes an operand higher-order even though it is only evaluated once: specifically, the sequence constructor contained in the body of an xsl:copy instruction that has a select attribute. See 19.8.4.12 Streamability of xsl:copy for further details.
[Definition: For some construct kinds, one or more operand roles may be defined to form a choice operand group. This concept is used where it is known that operands are mutually exclusive (for example the then and else clauses in a conditional expression).]
[Definition: The combined posture of a choice operand group is determined by the postures of the operands in the group (the operand postures), and is the first of the following that applies:
If any of the operand postures is roaming, then the combined posture is roaming.
If all of the operand postures are grounded, then the combined posture is grounded.
If one or more of the operand postures is climbing and the remainder (if any) are grounded, then the combined posture is climbing.
If one or more of the operand postures is striding and the remainder (if any) are grounded, then the combined posture is striding.
If one or more of the operand postures is crawling and each of the remainder (if any) is either striding or grounded, then the combined posture is crawling.
Otherwise (for example, if the group includes both an operand with climbing posture and one with crawling posture), the combined posture is roaming.
]
[Definition: The type-determined usage of an operand is as follows: if the required type (ignoring occurrence indicator) is fn(*) or a subtype thereof, then inspection; if the required type (ignoring occurrence indicator) is an atomic or union type, then absorption; otherwise navigation.]
[Definition: The type-adjusted posture and sweep of a construct C, with respect to a type T, are the posture and sweep established by applying the general streamability rules to a construct D whose single operand is the construct C, where the operand usage of C in D is the type-determined usage based on the required type T.]
Note:
In effect, the type-adjusted posture and sweep are the posture and sweep of the implicit expression formed to apply the coercion rules to the argument of a function or template call, or to the result of a function or template, given knowledge of the required type. For example, an expression such as discount in the function call abs(discount), which would otherwise be striding and consuming, becomes grounded and consuming because of the implicit atomization triggered by the coercion rules.
The process of determining whether a construct is streamable reduces to determining properties of the constructs in the construct tree. The properties in question (which are described in greater detail in subsequent sections) are:
The static type of the construct. When the construct is evaluated, its value will always be an instance of this type. The value is a U-type; although type inferencing is capable of determining information about the cardinality as well as the item type, the streamability analysis makes no use of this.
The context item type: that is, the static type of the context item potentially used as input to the construct. When the construct is evaluated, the context item used to evaluate the construct (if it is used at all) will be an instance of this type.
[Definition: The posture of the expression. This captures information about the way in which the streamed input document is positioned on return from evaluating the construct. The posture takes one of the values climbing, striding, crawling, roaming, or grounded.] The meanings of these terms are explained in 19.4 Determining the Posture of a Construct.
[Definition: The context posture. This captures information about how the context item used as input to the construct is positioned relative to the streamed input. The context posture of a construct C is the posture of the expression whose value sets the focus for the evaluation of C.] Rules for determining the context posture of any construct are given in 19.5 Determining the Context Posture.
The sweep of the construct. The sweep of a construct gives information about whether and how the evaluation of the construct changes the current position in a streamed input document. The possible values are motionless, consuming, and free-ranging. These terms are explained in 19.6 The Sweep of a Construct.
The values of these properties for a top-level construct such as the body of a template rule determine whether the construct is streamable.
The values of these properties are not independent. For example, if the static type is atomic, then the posture will always be grounded; if the sweep is free-ranging, then the posture will always be roaming.
The posture and sweep of a construct, as defined above, are calculated in relation to a particular streamed input document. If there is more than one streamed input document, then a construct that is motionless with respect to one streamed input might be consuming with respect to another. In practice, though, the streamability analysis is only ever concerned with one particular streamed input at a time; constructs are analyzed in relation to the innermost containing xsl:template, xsl:source-document, xsl:accumulator, or xsl:merge-source element, and this container implicitly defines the streamed input document that is relevant. The streamed input document affecting a construct is always the document that contains the context item for evaluation of that construct.
This section defines the properties of every kind of construct that may appear in a stylesheet. It identifies the operand roles and their usage, and it gives the rules that define the posture and sweep of the construct. In cases where the general streamability rules apply, there is still an entry for the construct in order to define its operands and their usages, since this information is needed by the general rules.
The following sections describe this categorization for each kind of construct:
Sequence constructors: see 19.8.3 Classifying Sequence Constructors
Instructions: see 19.8.4 Classifying Instructions
Stylesheet functions: see 19.8.5 Classifying Stylesheet Functions
Attribute sets: see 19.8.6 Classifying Attribute Sets
Value templates: see 19.8.7 Classifying Value Templates
Expressions: see 19.8.8 Classifying Expressions
Patterns: see 19.8.10 Classifying Patterns
Calls to built-in functions: see 19.8.9 Classifying Calls to Built-In Functions
XPath expressions are classified using the rules in this section.
In the analysis that follows, expressions are classified according to the most specific production rule that they match for which there is an entry in this section. A production P is considered more specific than a production Q (Q ≠ P) if every expression that matches P also matches Q. For example:
The expression 3 satisfies the productions NumericLiteral, Literal, and ArithmeticExpression; the most specific of these for which there is an entry in this section is Literal.
The expression text() (appearing as an expression) is a TextTest, and therefore a KindTest, which is itself a NodeTest, and therefore an AxisStep with a defaulted ForwardAxis. The most specific of these for which there is an entry in this section is AxisStep. Although the expression is also a RelativePathExpr, that production is less specific than AxisStep so its rules do not apply.
The expression section/title is a RelativePathExpr, for which there is an entry in this section. Although the expression is also a PathExpr, that production is less specific than RelativePathExpr so its rules do not apply.
The production rules for different kinds of expression are listed (with their names and numbers) in the order in which they appear in Appendix A.1 of the XPath 3.0 specification; rules are also given for new constructs introduced by XPath 3.1. Where two numbers are given, they are the production rule numbers in XPath 3.0 and XPath 3.1 respectively; where there is a single number, it is the production rule number in XPath 3.1.
Many expressions can be analyzed using the general streamability rules. These are indicated in the table below by means of a simple proforma in which the operand roles are represented by a short code (A = absorption, I = inspection, T = transmission, N = navigation). For example the proforma A + A indicates that for an arithmetic expression, both operands have operand usageabsorption, while I or I indicates that for an or expression, both operands have operand usageinspection. For expressions where further explanation is needed, the table contains a link to the relevant section.
| Construct | Proforma or Reference to Detailed Rules | Further Information |
|---|---|---|
| Expr | T, T | |
| ForExpr | See 19.8.8.1 Streamability of for Expressions | |
| LetExpr | let $var := N return T | Binding of variables to streamed nodes is not allowed. |
| QuantifiedExpr | See 19.8.8.2 Streamability of Quantified Expressions | |
| IfExpr | if (I) then T else T | The then-clause and else-clause form a choice operand group with usage transmission |
| OrExpr | I or I | |
| AndExpr | I and I | |
| StringConcatExpr | A || A | |
| RangeExpr | A to A | |
| AdditiveExpr | A + A, A - A | |
| MultiplicativeExpr | A * A, A div A, etc. | |
| UnionExpr | See 19.8.8.4 Streamability of union, intersect, and except Expressions | |
| IntersectExceptExpr | See 19.8.8.4 Streamability of union, intersect, and except Expressions | |
| InstanceOfExpr | See 19.8.8.5 Streamability of instance of Expressions | |
| TreatExpr | See 19.8.8.6 Streamability of treat as Expressions | |
| CastableExpr | A castable as TYPE | |
| CastExpr | A cast as TYPE | |
| UnaryExpr | +A, -A | |
| GeneralComp | A = A, A < A, A != A, etc. | |
| ValueComp | A eq A, A lt A, A ne A, etc. | |
| NodeComp | I is I, I << I, I >> I | See Note 1 below |
| SimpleMapExpr | See 19.8.8.7 Streamability of Simple Mapping Expressions | |
| PathExpr | See 19.8.8.8 Streamability of Path Expressions | |
| RelativePathExpr | See 19.8.8.8 Streamability of Path Expressions | |
| AxisStep | See 19.8.8.9 Streamability of Axis Steps | |
| ForwardStep, ReverseStep | See 19.8.8.9 Streamability of Axis Steps | |
| PostfixExpr: Filter Expression | See 19.8.8.10 Streamability of Filter Expressions | |
| PostfixExpr: Dynamic Function Call | See 19.8.8.11 Streamability of Dynamic Function Calls | |
| Literal | There are no operands, so the construct is grounded and motionless | |
| VarRef | See 19.8.8.12 Streamability of Variable References | |
| ParenthesizedExpr | (T) | |
() | There are no operands, so the construct is grounded and motionless | |
| ContextItemExpr | See 19.8.8.13 Streamability of the Context Item Expression | |
| FunctionCall | See 19.8.8.14 Streamability of Static Function Calls | |
| NamedFunctionRef | See 19.8.8.15 Streamability of Named Function References | |
| InlineFunctionExpr | See 19.8.8.16 Streamability of Inline Function Declarations | |
| MapConstructor | See 19.8.8.17 Streamability of Map Constructors | |
| Lookup (Postfix and Unary) | See 19.8.8.18 Streamability of Lookup Expressions | |
| ArrowExpr | See 19.8.8.14 Streamability of Static Function Calls and 19.8.8.11 Streamability of Dynamic Function Calls: the rules for X => F(Y, Z) are the same as the rules for F(X, Y, Z) | |
| SquareArrayConstructor | [ N, N, ... ] | |
| CurlyArrayConstructor | array { N, N, ... } |
Note:
The operators is, <<, and >> apply to streamed nodes just as to any other nodes, though there are few practical situations where they will be useful. A streamed document conforms to the rules of the XDM data model, and its nodes are therefore distinct and ordered. They follow the usual rules, for example that a parent node precedes its children in document order. Expressions such as .. is parent::X or ancestor::x[1] << ancestor::y[1] are therefore perfectly meaningful. The usefulness of the operators is limited by the fact that variables cannot be bound to nodes in a streamed document. It is permitted, though perhaps not useful, for one of the operands to be consuming: one can write . << child::x, and the resulting expression is (by applying the general rules) consuming and grounded.
The restriction that variables cannot be bound to streamed nodes prevents writing of expressions such as let $x := . return descendant::x[ancestor::y[1] is $x]. As a workaround, the intended effect can be achieved by comparing node identity using the generate-id function: let $x := generate-id(.) return descendant::x[generate-id(ancestor::y[1]) = $x]
The streamability analysis applies after the expansion of the // pseudo-operator to /descendant-or-self::node()/, and after expanding .. to parent::node(), @X to attribute::X, and an omitted axis to the default axis for the node kind.
Following the rules in XPath, a leading "/" is converted to (root(self::node()) treat as document-node())/ (with the final "/" omitted for the expression "/" on its own). This is followed by a rewrite of the call on root, as described in 19.8.9.20 Streamability of the root Function.
Note:
Taken together, these rewrites have the effect that a path expression such as //a is streamable only if the statically determined context item type is document-node(), which will be the case for example immediately within xsl:source-document, or in a template rule with match="/".
A RelativePathExpr with more than two operands (such as a/b/c) is taken as a tree of binary expressions (that is, (a/b)/c).
The sweep of a relative path expression is the wider sweep of the two operands, where the ordering of increasing width is motionless, consuming, free-ranging.
Note:
Examples:
The sweep of a/@code is consuming (the wider of consuming and motionless).
The sweep of a/descendant::b is consuming (the wider of consuming and consuming).
The sweep of ./@code is motionless (the wider of motionless and motionless).
The sweep of ./a is consuming (the wider of motionless and consuming).
The sweep of a/following::b is free-ranging (the wider of consuming and free-ranging).
The sweep of ./. is motionless (the wider of motionless and motionless).
The posture of a relative path expression is assessed in two phases, as follows:
First, the provisional posture is determined as follows: The provisional posture of the expression is the posture of the right-hand operand, assessed with a context posture and type set to the posture and type of the left-hand operand; and the provisional sweep is the wider of the sweeps of the two operands.
If the provisional posture is roaming, then it is reassessed as follows:
[Definition: A RelativePathExpr is a scanning expression if and only if it is syntactically equivalent to some motionlesspattern.]
Note:
This means that a RelativePathExpr is a scanning expression if it conforms to the grammar for a RelativePathExprP in the grammar for patterns (see 5.4.26.3.2 Syntax of Patterns), and if, when considered as a pattern, the pattern is motionless according to the rules in 19.8.10 Classifying Patterns.
In practice, the test as to whether the construct is equivalent to a pattern is likely to be made by examining the structure of the expression tree, rather than by re-parsing the lexical form of the expression against the grammar for patterns; but the outcome is the same.
If the expression is a scanning expression then:
Otherwise (if the provisional posture is not roaming, or the expression is not a scanning expression), the posture of the expression is the provisional posture.
Note:
The special rules for scanning expressions are designed to ensure that expressions such as //section/head are streamable. The problem with such an expression is that it is possible to have two nested sections A and B, where A is the parent of B and thus precedes B in document order, but where there are children of A that come after children of B in document order. This means that a nested-loop strategy for the evaluation of /descendant::section/child::head is not guaranteed to deliver nodes in document order without a sort, and is therefore not a viable strategy for streaming.
However, there is a different strategy for evaluating such an expression, which is in effect to rewrite the expression as /descendant::head[parent::section]; specifically, it is possible to scan all descendants in document order, looking for a head element that has a section parent. Hence the term scanning expressions.
The expressions that qualify as scanning expressions are paths that can be evaluated by scanning all descendants and testing each one (independently) to see whether the elements on its ancestor axis match the specified path. The subset of expressions that qualify as scanning expressions is therefore the same as the subset that qualify as motionless patterns.
Scanning expressions cannot use positional predicates: for example //section/head[1] is not recognized as a scanning expression because this would require information about a streamed node (specifically, about its preceding siblings) that is not retained during streaming.
Note:
Perhaps surprisingly, the expression .//section/head is not a scanning expression and is therefore not guaranteed streamable. This is because it does not take the syntactic form of a pattern. To make it streamable, it can be rewritten as descendant::section/head or as self::node()//section/head.
Similarly, within a streamable stylesheet function whose streaming parameter is $node, the expression $node//section/head is not a scanning expression. In this case the expression does have the syntactic form of a pattern, but the pattern is not classified as motionless. (See 19.8.10 Classifying Patterns — a motionless pattern cannot contain a RootedPath.) A workaround in this case is to rewrite the expression as $node/(descendant::section/head). Assuming that the function in question declares streamability="absorbing", the analysis here is that the left-hand operand ($node) is striding and consuming, while the right hand operand (descendant::section/head) is crawling and consuming (because it is a scanning expression). The expression as a whole is therefore crawling and consuming.
These are cases where an implementation might reasonably choose to relax the rules, insofar as this is permitted by 19.10 Streamability Guarantees.
Note:
Examples:
In each of the following cases, assume that the context posture is striding.
The posture of the expression a/b/c is striding, because (under the rules for AxisStep [38]) a child axis step evaluated with striding context posture creates a new striding posture.
The posture of the expression a/descendant::c is crawling, because a descendant axis step evaluated with striding context posture creates a new crawling posture.
The posture of the expression ../@status is striding, because a parent axis step evaluated with striding context posture creates a new climbing posture, and an attribute axis step evaluated with climbing context posture creates a new striding posture.
The posture of the expression copy-of(.)//a/following-sibling::* is grounded, because the copy-of evaluated with striding posture creates a grounded posture, and all subsequent axis steps leave this posture unchanged.
The expression section//head expands to (section/descendant-or-self::node())/child::head. The posture of the left-hand operand section/descendant-or-self::node() is crawling, because a descendant axis step evaluated with striding context posture creates a new crawling posture. The provisional posture of the expression as a whole is therefore roaming, because a child axis step evaluated with crawling context posture gives a resulting roaming posture. However, the expression is a scanning expression (both section//head and its expansion are motionless patterns), so the expression as a whole has crawling posture.
The expression section//head[1] is free-ranging: unlike the previous example, it contains a positional predicate, which means that the operands do not satisfy the rules for scanning expressions.
This section describes the rules that determine the streamability of calls to built-in functions. These differ from user-written functions because it is known (defined in the specification) how nodes supplied as operands are used. Knowledge of the usage of each operand, together with the posture of the actual operands, is in most cases enough to determine the posture and sweep of the function result.
All the built-in functions are listed below. For most functions, a simple proforma is shown that indicates the operand usage of each argument, using the code (A = absorption, I = inspection, T = transmission, N = navigation). So, for example, the entry fn:remove(T, A) means that for the function fn:remove#2, the operand usage of the first argument is transmission, and the operand usage of the second argument is absorption. By reference to the general rules in 19.8.1 General Rules for Streamability, this demonstrates that if the context posture is striding, the posture and sweep of the expression sum(remove(*,1)) will be grounded and consuming respectively.
For functions that default one of their arguments (typically to the context item), the relevant entry shows the equivalence, and the posture and sweep can in these cases be computed by filling in the default value for the relevant argument.
Some functions do not follow the general rules, and these are listed with a link to the section where the particular rules for that function are described.
array:append(I, N)
array:build(I, I)
array:empty(I)
array:filter(I, I)
array:flatten(A)
array:fold-left(I, N, I)
array:fold-right(I, N, I)
array:foot(I)
array:for-each(I, I)
array:for-each-pair(I, I, I)
array:get(I, A)
array:get(I, A, A)
array:head(I)
array:index-of(A, A, A)
array:index-where(A, A)
array:insert-before(I, A, N)
array:items(A)
array:join(I, N)
array:members(I)
array:of-members(I)
array:put(I, I, N)
array:remove(I, A)
array:reverse(I)
array:size(I)
array:slice(T, A, A, A)
array:sort(N, A, I)
array:sort-by(N, A)
array:split(I)
array:subarray(I, A, A)
array:tail(I)
array:trunk(I)
fn:abs(A)
fn:accumulator-after – See 19.8.9.1 Streamability of the accumulator-after Function
fn:accumulator-before – See 19.8.9.2 Streamability of the accumulator-before Function
fn:adjust-date-to-timezone(A, A)
fn:adjust-dateTime-to-timezone(A, A)
fn:adjust-time-to-timezone(A, A)
fn:all-different(N, A)
fn:all-equal(N, A)
fn:analyze-string(A, A, A)
fn:apply(A, I)
fn:apply-templates(A, A)
fn:atomic-equal(A, A)
fn:atomic-type-annotation(A)
fn:available-environment-variables()
fn:available-system-properties()
fn:avg(A)
fn:base-uri(I)
fn:boolean(I)
fn:build-uri(A, A)
fn:ceiling(A)
fn:char(A)
fn:character-map(A)
fn:characters(A)
fn:civil-timezone(A, A)
fn:codepoint-equal(A, A)
fn:codepoints-to-string(A)
fn:collation(A)
fn:collation-available(A, A)
fn:collation-key(A, A)
fn:collection(A)
fn:compare(A, A, A)
fn:concat(A)
fn:contains(A, A, A)
fn:contains-subsequence(T, T, A)
fn:contains-token(A, A, A)
fn:copy-of(A)
fn:count(I)
fn:csv-doc(A, A)
fn:csv-to-arrays(A, I)
fn:csv-to-xml(A, I)
fn:current – See 19.8.9.3 Streamability of the current Function
fn:current-date()
fn:current-dateTime()
fn:current-group – See 19.8.9.4 Streamability of the current-group Function
fn:current-grouping-key – See 19.8.9.5 Streamability of the current-grouping-key Function
fn:current-merge-group – See 19.8.9.6 Streamability of the current-merge-group Function
fn:current-merge-key – See 19.8.9.7 Streamability of the current-merge-key Function
fn:current-merge-key-array – See 19.8.9.8 Streamability of the current-merge-key-array Function
fn:current-output-uri()
fn:current-time()
fn:data(A)
fn:dateTime(A, A)
fn:day-from-date(A)
fn:day-from-dateTime(A)
fn:days-from-duration(A)
fn:decode-from-uri(A)
fn:deep-equal(A, A, A)
fn:default-collation()
fn:default-language()
fn:distinct-ordered-nodes – See 19.8.9.9 Streamability of the distinct-ordered-nodes Function
fn:distinct-values(A, A)
fn:divide-decimals(A, A, A)
fn:do-until(A, A, A)
fn:doc(A, A)
fn:doc-available(A, A)
fn:document(A, I)
fn:document-uri(I)
fn:duplicate-values(A, A)
fn:element-available(A)
fn:element-to-map(A, I)
fn:element-to-map-plan(A)
fn:element-with-id(A, N)
fn:empty(I)
fn:encode-for-uri(A)
fn:ends-with(A, A, A)
fn:ends-with-subsequence(T, T, A)
fn:environment-variable(A)
fn:error(A, A, N)
fn:escape-html-uri(A)
fn:every(A, A)
fn:exactly-one(T)
fn:exists(I)
fn:expanded-QName(A)
fn:false()
fn:filter(N, I)
fn:floor(A)
fn:fold-left(N, A, I)
fn:fold-right – See 19.8.9.11 Streamability of the fold-right Function
fn:foot(T)
fn:for-each(N, I)
fn:for-each-pair(N, N, I)
fn:format-date(A, A, A, A, A)
fn:format-dateTime(A, A, A, A, A)
fn:format-integer(A, A, A)
fn:format-number(A, A, A)
fn:format-time(A, A, A, A, A)
fn:function-annotations(A)
fn:function-arity(A)
fn:function-available(A, A)
fn:function-identity(A)
fn:function-lookup – See 19.8.9.14 Streamability of the function-lookup Function
fn:function-name(A)
fn:generate-id(I)
fn:graphemes(A)
fn:has-children(I)
fn:hash(A, A, A)
fn:head(T)
fn:highest(N, A, I)
fn:hours-from-dateTime(A)
fn:hours-from-duration(A)
fn:hours-from-time(A)
fn:html-doc(A, A)
fn:id(A, N)
fn:identity(N)
fn:idref(A, N)
fn:implicit-timezone()
fn:in-scope-namespaces(I)
fn:in-scope-prefixes(I)
fn:index-of(A, A, A)
fn:index-where(A, A)
fn:innermost – See 19.8.9.15 Streamability of the innermost Function
fn:insert-before(T, A, T)
fn:invisible-xml(A, A)
fn:iri-to-uri(A)
fn:is-NaN(A)
fn:items-at(T, A)
fn:jnode-content(A)
fn:jnode-position(A)
fn:jnode-selector(A)
fn:json-doc(A, I)
fn:json-to-xml(A, I)
fn:jtree(A)
fn:key(A, A, N)
fn:lang(A, I)
fn:last – See 19.8.9.16 Streamability of the last Function
fn:load-xquery-module(A, I)
fn:local-name(I)
fn:local-name-from-QName(A)
fn:lower-case(A)
fn:lowest(N, A, I)
fn:map-for-key(A, N)
fn:matches(A, A, A)
fn:max(A, A)
fn:message(T, A)
fn:min(A, A)
fn:minutes-from-dateTime(A)
fn:minutes-from-duration(A)
fn:minutes-from-time(A)
fn:month-from-date(A)
fn:month-from-dateTime(A)
fn:months-from-duration(A)
fn:name(I)
fn:namespace-uri(I)
fn:namespace-uri-for-prefix(A, I)
fn:namespace-uri-from-QName(A)
fn:nilled(I)
fn:node-name(I)
fn:node-type-annotation(A)
fn:normalize-space(A)
fn:normalize-unicode(A, A)
fn:not(I)
fn:number(A)
fn:one-or-more(T)
fn:op(A)
fn:outermost – See 19.8.9.17 Streamability of the outermost Function
fn:parse-csv(A, I)
fn:parse-html(A, A)
fn:parse-ietf-date(A)
fn:parse-integer(A, A)
fn:parse-json(A, I)
fn:parse-QName(A)
fn:parse-uri(A, A)
fn:parse-xml(A, A)
fn:parse-xml-fragment(A, A)
fn:partial-apply(A, I)
fn:partition(A, A)
fn:path(N, A)
fn:position – See 19.8.9.18 Streamability of the position Function
fn:prefix-from-QName(A)
fn:QName(A, A)
fn:random-number-generator(A)
fn:regex-group(A)
fn:remove(T, A)
fn:replace(A, A, A, A)
fn:replicate(N, A)
fn:resolve-QName(A, I)
fn:resolve-uri(A, A)
fn:reverse – See 19.8.9.19 Streamability of the reverse Function
fn:root – See 19.8.9.20 Streamability of the root Function
fn:round(A, A, A)
fn:round-half-to-even(A, A)
fn:scan-left(N, A, I)
fn:scan-right(N, A, I)
fn:schema-type(A)
fn:seconds(A)
fn:seconds-from-dateTime(A)
fn:seconds-from-duration(A)
fn:seconds-from-time(A)
fn:sequence-join(N, N)
fn:serialize(A, A)
fn:siblings(N)
fn:slice(T, A, A, A)
fn:snapshot(A)
fn:some(A, A)
fn:sort(N, A, I)
fn:sort-by(N, A)
fn:sort-with(A, A)
fn:starts-with(A, A, A)
fn:starts-with-subsequence(T, T, A)
fn:static-base-uri()
fn:stream-available(A)
fn:string(A)
fn:string-join(A, A)
fn:string-length(A)
fn:string-to-codepoints(A)
fn:subsequence(T, A, A)
fn:subsequence-where(T, A, A)
fn:substring(A, A, A)
fn:substring-after(A, A, A)
fn:substring-before(A, A, A)
fn:sum(A, A)
fn:system-property(A)
fn:tail(T)
fn:take-while(A, A)
fn:timezone-from-date(A)
fn:timezone-from-dateTime(A)
fn:timezone-from-time(A)
fn:tokenize(A, A, A)
fn:trace(T, A)
fn:transform(I)
fn:transitive-closure(A, A)
fn:translate(A, A, A)
fn:true()
fn:trunk(T)
fn:type-available(A)
fn:type-of(I)
fn:unix-dateTime(A)
fn:unordered(T)
fn:unparsed-binary(A)
fn:unparsed-entity-public-id(A, I)
fn:unparsed-entity-uri(A, I)
fn:unparsed-text(A, A)
fn:unparsed-text-available(A, A)
fn:unparsed-text-lines(A, A)
fn:upper-case(A)
fn:uri-collection(A)
fn:void(A)
fn:while-do(A, A, A)
fn:xml-to-json(A, I)
fn:xsd-validator(A)
fn:year-from-date(A)
fn:year-from-dateTime(A)
fn:years-from-duration(A)
fn:zero-or-one(T)
map:build(A, A, A, A)
map:contains(I, A)
map:empty(I)
map:entries(I)
map:entry(A, N)
map:filter(I, I)
map:find(I, A)
map:for-each(I, I)
map:get(I, A, A)
map:items(I)
map:keys(I)
map:keys-where(I, A)
map:merge(I, I)
map:of-pairs(I, A)
map:pair(A, N)
map:pairs(I)
map:put(I, A, N)
map:remove(I, A)
map:size(I)
math:acos(A)
math:asin(A)
math:atan(A)
math:atan2(A, A)
math:cos(A)
math:cosh(A)
math:e()
math:exp(A)
math:exp10(A)
math:log(A)
math:log10(A)
math:pi()
math:pow(A, A)
math:sin(A)
math:sinh(A)
math:sqrt(A)
math:tan(A)
math:tanh(A)
accumulator-after FunctionSee also 18.2.10 Streamability of Accumulators.
The posture of the function call is in all cases grounded.
The sweep is determined by applying the following rules, in order:
If the first argument (the accumulator name) is not motionless, the function is free-ranging.
If the context posture is grounded, the function is motionless.
If the context item type has an empty intersection with U{document-node(), element()} (that is, if the context item cannot have children), the function is motionless.
If the function call is contained in the select expression or contained sequence constructor of an xsl:accumulator-rule specifying phase="start", then it is free-ranging.
If the function call is contained in the select expression or contained sequence constructor of an xsl:accumulator-rule specifying phase="end", then it is motionless.
If no enclosing node of the function call is part of a sequence constructor, then it is free-ranging. For this purpose, the enclosing nodes of a function call are the attribute or text node that immediately contains the XPath expression in which the function call appears, and its ancestors.
If the focus-setting container of the function call is different from the focus-setting container of the innermost containing instruction, then the function is free-ranging.
If no enclosing node N of the function call has a preceding sibling node P such that (a) N and P are part of the same sequence constructor, and (b) the sweep of P is consuming, then the function call is consuming. (The term enclosing node is defined above.)
Otherwise, the function call is motionless.
Note:
The following notes apply to the above rules with matching numbers:
This rule prevents the accumulator name being computed by reading the streamed source document. This is disallowed primarily because there is no conceivable use case for doing it.
If the context posture is grounded, then the target of the accumulator is not a streamed node, so no streaming restrictions apply.
If the context item is a childless node (such as a text node), then both the pre-descent and post-descent values of the accumulator can be computed before evaluating any user-written constructs that access this node; there are therefore no constraints on where a call to accumulator-after can appear.
This rule ensures that when computing the pre-descent value of an accumulator for a particular streamed node, the post-descent values of accumulators for that node are not available.
This rule states that the post-descent value of an accumulator is allowed to depend on the post-descent values of other accumulators for the same node. There is a rule preventing cycles [see ERR XTDE3400].
This rule prevents the use of the function (when applied to a streamed node) in contexts like the use attribute of xsl:key. It allows its use in the attributes of an instruction or literal result element, or in a text value template. It does not allow use in an xsl:sort or xsl:param element, as these elements do not form part of a sequence constructor (see 5.85.7 Sequence Constructors).
This rule prevents the use of the function (when applied to a streamed node) in contexts such as predicates, or the right-hand side of the / operator. The focus for evaluation of the function must be the same as the focus for a containing sequence constructor. Sequence constructors are treated differently from all other constructs for this purpose in that their operands (the contained instructions) are treated as ordered: in conjunction with the next rule, this rule is assuming that instructions in a sequence constructor that follow a consuming instruction are evaluated after the consuming instruction and therefore have access to the post-descent accumulator value.
This rule is subtle, and has a number of consequences. In these notes, the term instruction should be read as including all nodes making up a sequence constructor, including XSLT instructions, extension instructions, literal result elements, and text nodes containing text value templates.
In a sequence constructor that contains a consuming instruction such as <xsl:apply-templates/>, it allows any number of calls on accumulator-after to appear in instructions that follow the call on <xsl:apply-templates/>.
In such a sequence constructor it prevents a call on accumulator-after from appearing in an instruction that precedes the <xsl:apply-templates/>, because there would then be two consuming instructions.
In a sequence constructor that contains calls on accumulator-after, and contains no other consuming construct, the first instruction that contains a call on accumulator-after is consuming (unless it contains more than one such call, in which case it is free-ranging), and subsequent instructions containing such a call are motionless. So it is possible to have two or more calls on accumulator-after provided they appear in different instructions, which allows the analysis to assume an order of execution.
It prevents a call on accumulator-after from appearing in the same instruction as another consuming construct: for example it disallows concat(child::p, accumulator-after('a')). This rule preserves the ability to evaluate the arguments of the concat function in any order.
It disallows a call on accumulator-after from appearing in a sequence constructor that is required to be motionless, for example within xsl:sort.
The reference to a “preceding sibling node within the same sequence constructor” is carefully worded to ensure that preceding siblings among the children of xsl:fork are not taken into account; the children of xsl:fork are sibling instructions, but do not constitute a sequence constructor. The term also excludes elements such as xsl:param and xsl:sort that may precede a sequence constructor but are not part of it.
The final rule states that if none of the previous rules apply, the function is considered motionless. This applies when the accumulator-after appears after a consuming instruction within the same sequence constructor.
Note also that a call to accumulator-after can safely appear within a construct such as a named template or (non-streamable) stylesheet function; this is safe because the rules ensure that in such situations, the context item cannot be a streamed node.
Dynamic invocation of accumulator-after is covered by the rules in 10.3.6 Dynamic Access to Functions. These rules ensure that a function item cannot include a streamed node in its closure; circumventing the streamability rules for accumulator-after by making a dynamic call is therefore not possible.
The examples in this section are intended to illustrate how the streamability rules are applied “top down” to establish whether template rules are guaranteed streamable.
Consider the following template rule, where mode s is defined with streamable="yes":
<xsl:template match="para" mode="s"> <div class="para"> <xsl:apply-templates mode="s"/> </div> </xsl:template>
The processor is required to establish that this template meets the streamability rules. Specifically, as stated in 6.7.76.8.7 Streamable Templates, it must satisfy three conditions:
The match pattern must be motionless.
The body of the template rule must be grounded.
The initializers of any template parameters must be motionless.
The third condition is satisfied trivially because there are no parameters.
The first rule depends on the rules for assessing patterns, which are given in 19.8.10 Classifying Patterns. This pattern is motionless because (a) it does not contain a RootedPath, and (b) it contains no predicates.
So it remains to determine that the body of the template is grounded. The proof of this is as follows:
The sequence constructor forming the body of the template is assessed according to the rules in 19.8.3 Classifying Sequence Constructors, which tell us that there is a single operand (the <div>literal result element) which has operand usageU = transmission.
The assessment of the sequence constructor uses the general streamability rules. These rules require us to determine the type T, sweep S, posture P, and usage U of each operand. We have already established that there is a single operand, with U = transmission. Section 19.1 Determining the Static Type of a Construct tells us that for all instructions, we can take T = U{*}. The postureP and sweepS of the literal result element are established as follows:
The rules for literal result elements (specifically the <div> element) are given in 19.8.4.1 Streamability of Literal Result Elements. This particular literal result element has only one operand (its contained sequence constructor), with operand usageU = absorption.
The general streamability rules again apply. Again the static typeT of the operand is U{*}, and we need to determine the postureP and sweepS.
To determine the posture and sweep of this sequence constructor (the one that contains the xsl:apply-templates instruction) we refer again to the general streamability rules.
The sequence constructor has a single operand (the xsl:apply-templates instruction); again U = transmission, T = U{*}.
The postureP and sweepS of the xsl:apply-templates instruction are established as follows:
The rules that apply are in 19.8.4.5 Streamability of xsl:apply-templates.
Rule 1 does not apply because the select expression (which defaults to child::node()) is not grounded. This is a consequence of the rules in 19.8.8.9 Streamability of Axis Steps, specifically:
The context posture of the axis step is established by the template rule as a whole, as striding.
Therefore rules 1 and 2 do not apply.
The statically inferred context item type is derived from the match pattern (match="para"). This gives a type of U{element()}. The child axis for element nodes is not necessarily empty, so rule 3 does not apply.
Rule 4 does not apply because there are no predicates.
So the posture and sweep of the axis step child::node() are given by the table in rule 5. The entry for (context posture = striding, axis = child) gives a posture of striding and a sweep of consuming.
So the select expression is not grounded. (The same result can be reached intuitively: an expression that selects streamed nodes will never be grounded.)
Rule 2 does not apply because there is no xsl:sort element.
Rule 3 does not apply because the mode is declared with streamable="yes".
So the postureP and sweepS of the xsl:apply-templates instruction are established by the general streamability rules, as follows:
There is a single operand, the implicit select="child::node()" expression, with usage U = absorption.
We have already established that for this operand, the posture P = striding and the sweepS = consuming.
By the rules in 19.1 Determining the Static Type of a Construct, the type T of the select expression is node().
In the general streamability rules, the adjusted sweep S′ for an operand with (P = striding, U = absorption) is consuming,
Rule 2(d) then applies, so the xsl:apply-templates instruction is consuming and grounded.
So the sequence constructor that contains the xsl:apply-templates instruction has one operand with U = transmission, T = item(), P = grounded, S = consuming. Rule 2(d) of the general streamability rules applies, so the sequence constructor itself has P = grounded, S = consuming.
So the literal result element has one operand with U = absorption, T = item(), P = grounded, S = consuming. Rule 2(d) of the general streamability rules applies, so the literal result element has P = grounded, S = consuming.
So the sequence constructor containing the literal result element has one operand with U = transmission, T = item(), P = grounded, S = consuming. Rule 2(d) of the general streamability rules applies, so this sequence constructor itself has P = grounded, S = consuming.
So we have established that the sequence constructor forming the body of the template rule is grounded.
Therefore, since the other conditions are also satisfied, the template is guaranteed-streamable.
The analysis presented above could have been simplified by taking into account the fact that the streamability properties of a sequence constructor containing a single instruction are identical to the properties of that instruction. This simplification will be exploited in the next example.
Consider the following template rule, where mode s is defined with streamable="yes":
<xsl:template match="transactions[@currency='USD']" mode="s"> <total><xsl:value-of select="sum(transaction/@value)"/></total> </xsl:template>
Again, as stated in 6.7.76.8.7 Streamable Templates, it must satisfy three conditions:
The match pattern must be motionless.
The body of the template rule must be grounded.
The initializers of any template parameters must be motionless.
The third condition is satisfied trivially because there are no parameters.
The first rule depends on the rules for assessing patterns, which are given in 19.8.10 Classifying Patterns. This pattern is motionless because (a) it is not a RootedPath, and (b) every predicate is motionless and non-positional. The analysis that proves the predicate is motionless and non-positional proceeds as follows:
First establish that the expression @currency='USD' is motionless, as follows:
The predicate is a general comparison (GeneralComp) which follows the general streamability rules.
There are two operands: an AxisStep with a defaulted ForwardAxis, and a Literal. Both operand roles are absorption.
The left-hand operand has type T = attribute(). Its posture and sweep are determined by the rules in 19.8.8.9 Streamability of Axis Steps. The context posture is striding, so the posture and sweep are determined by the entry in the table (rule 5) with context posture = striding, axis = attribute: that is, the result posture is striding and the sweep is motionless.
The right-hand operand, being a literal, is grounded and motionless.
In the general streamability rules, rule 2(e) applies, so the predicate is grounded and motionless
Now establish that the expression @currency='USD' is non-positional, as follows:
Rule 1 is satisfied: the predicate does not call position, last, or function-lookup.
Rule 2 is satisfied: the expression @currency='USD' is non-numeric. The static type of the expression is determined using the rules in 19.1 Determining the Static Type of a Construct as U{xs:boolean}, and this has no intersection with U{xs:decimal, xs:double, xs:float}.
So both conditions in 19.8.10 Classifying Patterns are satisfied, and the pattern is therefore motionless.
It remains to show that the body of the template rule is grounded. The proof of this is as follows. Unlike the previous example, the analysis is shown in simplified form; in particular the two sequence constructors which each contain a single instruction are ignored, and replaced in the construct tree by their contained instruction.
We need to show that the <total>literal result element is grounded.
The rules that apply are in 19.8.4.1 Streamability of Literal Result Elements.
These rules refer to the general streamability rules. There is one operand, the xsl:value-of child element, which has operand usageU = absorption, and type T = item().
So we need to determine the posture and sweep of the xsl:value-of instruction.
The rules are given in 19.8.4.42 Streamability of xsl:value-of.
The general streamability rules apply. There is one operand, the expression sum(transaction/@value), which has operand usageU = absorption.
The type T of this operand is the return type defined in the signature of the sum function, that is, xs:anyAtomicType.
The postureP and sweepS are established as follows:
The rules that apply to the call on sum are given in 19.8.9 Classifying Calls to Built-In Functions.
The relevant proforma is fn:sum(A), indicating that the general streamability rules apply, and that there is a single operand with usage U = absorption.
The type T of the operand transaction/@value is determined (by the rules in 19.1 Determining the Static Type of a Construct) as attribute().
The postureP and sweepS of the operand transaction/@value are determined by the rules in 19.8.8.8 Streamability of Path Expressions, as follows:
The expression is expanded to child::transaction/attribute::value.
The posture and sweep of the left-hand operand child::transaction are determined by the rules in 19.8.8.9 Streamability of Axis Steps, as follows:
The context posture is striding, because the focus-setting container is the template rule itself.
The context item type is element(), based on the match type of the pattern match="transactions[@currency='USD']".
Rules 1 and 2 do not apply because the context posture is striding.
Rule 3 does not apply because the child axis applied to an element node is not necessarily empty.
Rule 4 does not apply because there are no predicates.
Rule 5 applies, and the table entry with context posture = striding, axis = child gives a result posture of striding and a sweep of consuming.
The posture of the relative path expression child::transaction/attribute::value is therefore the posture of its right-hand operand attribute::value, assessed with a context posture of striding. This is determined by the rules in 19.8.8.9 Streamability of Axis Steps, as follows:
The context posture, as we have seen, is striding.
The context item type is element(), based on the type of the left-hand operand child::transaction.
Rules 1 and 2 do not apply because the context posture is striding.
Rule 3 does not apply because the attribute axis applied to an element node is not necessarily empty.
Rule 4 does not apply because there are no predicates.
Rule 5 applies, and the table entry with context posture = striding, axis = attribute gives a result posture of striding and a sweep of motionless.
The posture of the relative path expression child::transaction/attribute::value is therefore striding.
The sweep of the relative path expression child::transaction/attribute::value is the wider of the sweeps of its two operands, namely consuming and motionless. That is, it is consuming.
So the first and only operand to the call on sum() has U = absorption, T = attribute(), P = climbing, and S = consuming
Rule 1(b) of the general streamability rules computes the adjusted sweep S′. Rule 1(b)(iii)(A) applies, so the effective operand usageU′ is inspection. Rule 1(b)(iii)(A) then computes the adjusted sweep from the table entry for P = climbing, U′ = inspection; this shows S′ = S, that is, consuming.
Rule 2(d) now applies, so the call on sum() is grounded and consuming.
Since the xsl:value-of instruction has one operand with U = absorption, T = xs:anyAtomicType, P = grounded, and S = consuming, rule 2(d) again applies, and the xsl:value-of instruction is grounded and consuming.
Since the literal result element has one operand with U = absorption, T = item(), P = grounded, and S = consuming, rule 2(d) again applies, and the literal result element is grounded and consuming.
Therefore the body of the template rule is grounded, and since the other conditions are also satisfied, it is guaranteed-streamable.
Consider the following code, which is designed to process a transaction file containing transactions in chronological order, and output the total value of the transactions for each day.
<xsl:template name="go"> <out> <xsl:source-document streamable="yes" href="transactions.xml"> <xsl:for-each-group select="/account/transaction" group-adjacent="xs:date(@timestamp)"> <total date="{current-grouping-key()}" value="{sum(current-group()/@value)}"/> </xsl:for-each-group> </xsl:source-document> </out> </xsl:template>
The rules for xsl:source-document say that the instruction is guaranteed-streamable if the contained sequence constructor is grounded, and the task of streamability analysis is to prove that this is the case. As in the previous example, we will take a short-cut by making the assumption that a sequence constructor containing a single instruction can be replaced by that instruction in the construct tree.
So the task is to show that the xsl:for-each-group instruction is grounded, which we can do as follows:
The relevant rules are to be found in 19.8.4.19 Streamability of xsl:for-each-group.
Note:
Rule numbers may be different in a version of the specification with change markings.
Rule 1 applies only if the select expression is grounded. It is easy to see informally that this is not the case (an expression that returns streamed nodes is never grounded). More formally:
The select expression is a path expression; the rules in 19.8.8.8 Streamability of Path Expressions apply.
The expression is rewritten as ((root(.) treat as document-node())/child::account)/child::transaction
The left-hand operand (root(.) treat as document-node())/child::account is also a path expression, so the rules in 19.8.8.8 Streamability of Path Expressions apply recursively:
The left-hand operand root(.) treat as document-node() follows the rules for a TreatExpr in 19.8.8 Classifying Expressions; the proforma T treat as TYPE indicates that the general streamability rules apply with a single operand having usage transmission.
This single operand root(.) follows the rules in 19.8.9.20 Streamability of the root Function. The item type of the operand . is the context item type, which is the type established by the xsl:source-document instruction, namely document-node(). Under these conditions root(.) is rewritten as ., so the posture is the context posture established by the xsl:source-document instruction, namely striding. The sweep is motionless.
The posture and sweep of the expression root(.) treat as document-node() are the same as the posture and sweep of root(.), namely striding and motionless
The right-hand operand child::account is governed by the rules in 19.8.8.9 Streamability of Axis Steps. The context posture is striding, and the axis is child, so the result posture is striding and the sweep is consuming.
The posture of the path expression is the posture of the right-hand operand, that is striding, and its sweep is the wider sweep of the two operands, that is consuming
Returning to the outer path expression, the posture of the right hand operand child::transaction is striding, and its sweep is consuming.
So the posture of the select expression as a whole is the posture of the right hand operand, that is striding; and its sweep is the wider of the sweeps of the operands, which is consuming.
Rule 2 does not apply: there is no group-by attribute.
Rule 3 does not apply: there is a group-adjacent attribute, but it is motionless. The reasoning is as follows:
The value is a call to the constructor function xs:date. The rules in 19.8.8.14 Streamability of Static Function Calls apply. There is a single operand, whose required type is atomic, so the operand usage is absorption.
These rules refer to the general streamability rules, so we need to determine the context item type, posture, and sweep of the operand expression @timestamp. This is done as follows:
The expression is an AxisStep, so the relevant rules are in 19.8.8.9 Streamability of Axis Steps.
The context posture is the posture of the controlling operand of the focus-setting container, that is, is the select expression of the containing xsl:for-each-group instruction, which as established above is striding. The context item type is similarly the inferred type of the select expression, and is element().
Rules 1 and 2 do not apply because the context posture is striding.
Rule 3 does not apply because the attribute axis for an element node is not necessarily empty.
Rule 4 does not apply because there is no predicate.
So the sweep and posture of the expression @timestamp are given by the table in Rule 5 as striding and motionless.
Returning to the general streamability rules for the expression xs:date(@timestamp), the operand @timestamp has U = absorption, T = attribute(), P = striding, S = motionless.
Under Rule 1(b)(iii)(A), because T = attribute(), the operand usageU′ becomes inspection.
Under Rule 1(b)(iii)(A), S′ = S = motionless.
Under Rule 2(e), the expression xs:date(@timestamp) is grounded and motionless.
Rule 4 (under xsl:for-each-group) does not apply, because there is no xsl:sort child.
So Rule 5 applies. This relies on knowing the posture of the sequence constructor contained in the xsl:for-each-group instruction: that is, the posture of the totalliteral result element. This is calculated as follows:
The rules that apply are in 19.8.4.1 Streamability of Literal Result Elements. The general streamability rules apply; there are two operands, the attribute value templates {current-grouping-key()} and {sum(current-group()/@value)}, and in each case the usage is absorption. We can simplify the analysis by observing that the empty sequence constructor contained in the literal result element can be ignored, since it is grounded and motionless.
Consider first the operand {current-grouping-key()}.
Section 19.8.7 Classifying Value Templates applies. This refers to the general streamability rules; there is a single operand, the expression current-grouping-key(), with usage absorption.
Section 19.8.9.5 Streamability of the current-grouping-key Function applies. This establishes that the expression is grounded and motionless.
It follows that the operand {current-grouping-key()} expression is also grounded and motionless.
Now consider the operand {sum(current-group()/@value)}.
Section 19.8.7 Classifying Value Templates applies. This refers to the general streamability rules; there is a single operand, the expression sum(current-group()/@value), with usage absorption.
The rules for the sum function appear in 19.8.9 Classifying Calls to Built-In Functions. The proforma is given there as fn:sum(A), which means that the general streamability rules apply, and that the single operand current-group()/@value has usage absorption. So we need to establish the posture, sweep, and type of this expression, which we can do as follows:
The expression is a RelativePathExpr, so section 19.8.8.8 Streamability of Path Expressions applies.
The expression is expanded to current-group()/attribute::value.
The posture and sweep of the left-hand operand current-group() are defined in 19.8.9.4 Streamability of the current-group Function. Since all the required conditions are satisfied, the posture of current-group() is the posture of the select expression, that is striding, and its sweep is the sweep of the select expression, that is consuming.
The posture and sweep of the right hand operand @value are defined in 19.8.8.9 Streamability of Axis Steps. The context posture is the posture of the left-hand operand current-group(), namely striding; the table in Rule 5 applies, giving the result climbing and motionless
The posture of the RelativePathExpr is the posture of the right hand operand, namely striding. The sweep of the RelativePathExpr is the wider of the sweeps of its operands, which is consuming
The type of the expression current-group()/@value is determined using the rules in 19.1 Determining the Static Type of a Construct as attribute().
So the sum function has a single operand with U = absorption, P = striding, S = consuming, T = attribute().
In the general streamability rules, Rule 1(b)(iii)(A) gives the adjusted usage as U′ = inspection, and Rule 1(b)(iii)(B) gives the adjusted sweep as S′ = S = consuming. Rule 2(d) gives the posture and sweep of the call to sum as grounded and consuming.
So the literal result element has two operands, one of which is grounded and motionless, the other grounded and consuming. Rule 2(d) of the general streamability rules determines that the literal result element is grounded and consuming.
So the content of the xsl:source-document instruction is grounded, which means that the instruction is guaranteed-streamable.
<!-- Category: instruction -->
<xsl:message
select? = expression
terminate? = { boolean }〔'no'〕
error-code? = { eqname }〔'Q{http://www.w3.org/2005/xqt-errors}XTMM9000'〕 >
<!-- Content: sequence-constructor -->
</xsl:message>
The xsl:message instruction sends a message in an implementation-defined way. The xsl:message instruction causes the creation of a new document, which is typically serialized and output to an implementation-defined destination. The result of the xsl:message instruction is an empty sequence.
The content of the message may be specified by using either or both of the optional select attribute and the sequence constructor that forms the content of the xsl:message instruction.
If the xsl:message instruction contains a sequence constructor, then the sequence obtained by evaluating this sequence constructor is used to construct the content of the new document node, as described in 5.8.15.7.1 Constructing Complex Content.
If the xsl:message instruction has a select attribute, then the value of the attribute must be an XPath expression. The effect of the xsl:message instruction is then the same as if a single xsl:copy-of instruction with this select attribute were added to the start of the sequence constructor.
If the xsl:message instruction has no content and no select attribute, then an empty message is produced.
The tree produced by the xsl:message instruction is not technically a final result tree. The tree has no URI and processors are not required to make the tree accessible to applications.
Note:
In many cases, the XML document produced using xsl:message will consist of a document node owning a single text node. However, it may contain a more complex structure.
Note:
An implementation might implement xsl:message by popping up an alert box or by writing to a log file. Because the order of execution of instructions is implementation-defined, the order in which such messages appear is not predictable.
The terminate attribute is interpreted as an attribute value template.
If the effective value of the terminate attribute is yes, then the processormust raise a dynamic error after sending the message. This error may be caught in the same way as any other dynamic error using xsl:catch. The default value is no. Note that because the order of evaluation of instructions is implementation-dependent, this gives no guarantee that any particular instruction will or will not be evaluated before processing terminates.
The optional error-code attribute (also interpreted as an attribute value template) may be used to indicate the error code associated with the message. This may be used irrespective of the value of terminate. The effective value of the error code attribute is expected to be an EQName. If no error code is specified, or if the effective value is not a valid EQName, the error code will have local part XTMM9000 and namespace URI http://www.w3.org/2005/xqt-errors. User-defined error codes should be in a namespace other than http://www.w3.org/2005/xqt-errors. When the value of terminate is yes, the error code may be matched in an xsl:catch element to catch the error and cause processing to continue normally.
[ERR XTMM9000] When a transformation is terminated by use of <xsl:message terminate="yes"/>, the effect is the same as when a dynamic error occurs during the transformation. The default error code is XTMM9000; this may be overridden using the error-code attribute of the xsl:message instruction.
One convenient way to do localization is to put the localized information (message text, etc.) in an XML document, which becomes an additional input file to the stylesheet. For example, suppose messages for a language L are stored in an XML file resources/L.xml in the form:
<messages> <message name="problem">A problem was detected.</message> <message name="error">An error was detected.</message> </messages>
Then a stylesheet could use the following approach to localize messages:
<xsl:param name="lang" select="'en'"/> <xsl:variable name="messages" select="document(concat('resources/', $lang, '.xml'))/messages"/> <xsl:template name="localized-message"> <xsl:param name="name"/> <xsl:message select="string($messages/message[@name=$name])"/> </xsl:template> <xsl:template name="problem"> <xsl:call-template name="localized-message"> <xsl:with-param name="name">problem</xsl:with-param> </xsl:call-template> </xsl:template>
Any dynamic error that occurs while evaluating the select expression or the contained sequence constructor, and any serialization error that occurs while processing the result, does not cause the transformation to fail; at worst, it means that no message is output, or that the only message that is output is one that relates to the error that occurred.
Note:
An example of such an error is the serialization error that occurs when processing the instruction <xsl:message select="@code"/> (on the grounds that free-standing attributes cannot be serialized). Making such errors recoverable means that it is implementation-defined whether or not they are raised to the user and whether they cause termination of the transformation. If the processor chooses to recover from the error, the content of any resulting message is implementation-dependent.
One possible recovery action is to include a description of the error in the generated message text.
A processormay output a final result tree as a sequence of octets, although it is not required to be able to do so (see 27 Conformance). This process is described as serialization. Stylesheet authors can use xsl:output declarations to specify how they wish result trees to be serialized. If a processor serializes a final result tree, it must do so as specified by these declarations.
The rules governing the output of the serializer are defined in [XSLT and XQuery Serialization]. 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.
Normally, when using the XML, HTML, or XHTML output method, the serializer will escape special characters such as & and < when outputting text nodes. This ensures that the output is well-formed. However, it is sometimes convenient to be able to produce output that is almost, but not quite well-formed XML; for example, the output may include ill-formed sections which are intended to be transformed into well-formed XML by a subsequent non-XML-aware process. For this reason, XSLT defines a mechanism for disabling output escaping.
This feature is deprecated.
This is an optional feature: it is not required that an XSLT processor that implements the serialization option should offer the ability to disable output escaping, and there is no conformance level that requires this feature.
This feature requires the serializer (described in [XSLT and XQuery Serialization]) to be extended as follows. Conceptually, the final result tree provides an additional boolean property disable-escaping associated with every character in a text node. When this property is set, the normal action of the serializer to escape special characters such as & and < is suppressed.
An xsl:value-of or xsl:text element may have a disable-output-escaping attribute; the allowed values are yes or no. The default is no; if the value is yes, then every character in the text node generated by evaluating the xsl:value-of or xsl:text element should have the disable-escaping property set.
For example,
<xsl:text disable-output-escaping="yes"><</xsl:text>
should generate the single character <.
If output escaping is disabled for an xsl:value-of or xsl:text instruction evaluated when temporary output state is in effect, the request to disable output escaping is ignored.
Similarly, if an xsl:value-of or xsl:text instruction specifies that output escaping is to be disabled when writing to a final result tree that is not being serialized, the request to disable output escaping is ignored.
Note:
Furthermore, a request to disable output escaping has no effect when the newly constructed text node is used to form the value of an attribute, comment, processing instruction, or namespace node. This is because the rules for constructing such nodes (see 5.8.25.7.2 Constructing Simple Content) cause the text node to be atomized, and the process of atomizing a text node takes no account of the disable-escaping property.
If output escaping is disabled for text within an element that would normally be output using a CDATA section, because the element is listed in the cdata-section-elements, then the relevant text will not be included in a CDATA section. In effect, CDATA is treated as an alternative escaping mechanism, which is disabled by the disable-output-escaping option.
For example, if <xsl:output cdata-section-elements="title"/> is specified, then the following instructions:
<title> <xsl:text disable-output-escaping="yes">This is not <hr/> good coding practice</xsl:text> </title>
should generate the output:
<title><![CDATA[This is not ]]><hr/><![CDATA[ good coding practice]]></title>
The disable-output-escaping attribute may be used with the html output method as well as with the xml output method. The text output method ignores the disable-output-escaping attribute, since this method does not perform any output escaping.
A processor will only be able to disable output escaping if it controls how the final result tree is output. This might not always be the case. For example, the result tree might be used as a source tree for another XSLT transformation instead of being output. It is implementation-defined whether (and under what circumstances) disabling output escaping is supported. If disabling output escaping is not supported, any request to disable output escaping is ignored.
If output escaping is disabled for a character that is not representable in the encoding that the processor is using for output, the request to disable output escaping is ignored in respect of that character.
Since disabling output escaping might not work with all implementations and can result in XML that is not well-formed, it should be used only when there is no alternative.
Note:
When disable-output-escaping is used, there is no guarantee that the serialized output will be well-formed XML (or HTML). Furthermore, the fact that the result tree was validated against a schema gives no guarantee that the serialized output will still be valid against the same schema. Conversely, it is possible to use disable-output-escaping to produce schema-valid output from a result tree that would fail validation.
Note:
The facility to define character maps for use during serialization, as described in 26.3 Character Maps, has been produced as an alternative mechanism that can be used in many situations where disabling of output escaping was previously necessary, without the same difficulties.
A component of the context that has no value is said to be absent.
An operand usage of absorption indicates that the construct reads the subtree(s) rooted at a supplied node(s).
An accumulator defines a series of values associated with the nodes of the tree. If an accumulator is applicable to a particular tree, then for each node in the tree, other than attribute and namespace nodes, there will be two values available, called the pre-descent and post-descent values. These two values are available via a pair of functions, accumulator-before and accumulator-after.
The functions accumulator-before and accumulator-after are referred to as the accumulator functions.
A stylesheet can use the xsl:namespace-alias element to declare that a literal namespace URI is being used as an alias for a target namespace URI.
A template rule is applicable to one or more modes. The modes to which it is applicable are defined by the mode attribute of the xsl:template element. If the attribute is omitted, then the template rule is applicable to the default mode specified in the [xsl:]default-mode attribute of the innermost containing element that has such an attribute, which in turn defaults to the unnamed mode. If the mode attribute is present, then its value must be a non-empty whitespace-separated list of tokens, each of which defines a mode to which the template rule is applicable.
The applicable static namespaces for an element in a stylesheet module are the fixed namespace bindings for the module if the root element of the module has a fixed-namespaces attribute, or the native namespace bindings of the element otherwise.
A function definition has an arity range, which defines the minimum and maximum number of arguments that must be supplied in a call to the function. The static context can contain multiple function definitions with the same name, provided that their arity ranges do not overlap.
The term atomization is defined in Section 2.5.3 AtomizationXP. It is a process that takes as input a sequence of items, and returns a sequence of atomic items, in which the nodes are replaced by their typed values as defined in [XDM 3.0]. Arrays (see 22 Arrays) are atomized by atomizing their members, recursively.
An attribute set is defined as a set of xsl:attribute-set declarations in the same package that share the same expanded QName.
An attribute set invocation is a pseudo-instruction corresponding to a single EQName appearing within an [xsl:]use-attribute-sets attribute; the effect of the pseudo-instruction is to cause the referenced attribute set to be evaluated.
In an attribute that is designated as an attribute value template, such as an attribute of a literal result element, an expression can be used by surrounding the expression with curly brackets ({}), following the general rules for value templates
An element is processed with backwards compatible behavior if its effective version is less than 4.0.
The base output URI is a URI to be used as the base URI when resolving a relative URI reference allocated to a final result tree. If the transformation generates more than one final result tree, then typically each one will be allocated a URI relative to this base URI.
A basic XSLT processor is an XSLT processor that implements all the mandatory requirements of this specification with the exception of constructs explicitly associated with an optional feature.
A character map allows a specific character appearing in a text or attribute node in the final result tree to be substituted by a specified string of characters during serialization.
For some construct kinds, one or more operand roles may be defined to form a choice operand group. This concept is used where it is known that operands are mutually exclusive (for example the then and else clauses in a conditional expression).
A circularity is said to exist if a construct such as a global variable, an attribute set, or a key, cannot be evaluated without reference to its own value. For example, if the expression or sequence constructor specifying the value of a global variableX references a global variable Y, then the value for Ymust be computed before the value of X. A circularity exists if it is impossible to do this for all global variable definitions.
Climbing: indicates that streamed nodes returned by the construct are reached by navigating the parent, ancestor[-or-self], attribute, and/or namespace axes from the node at the current streaming position.
The term coercion rules means the coercion rules defined in [XPath 4.0], applied unless otherwise specified with XPath 1.0 compatibility mode set to false.
Facilities in XSLT 3.0 and XPath 3.0 that require strings to be ordered rely on the concept of a named collation. A collation is a set of rules that determine whether two strings are equal, and if not, which of them is to be sorted before the other.
The ordered collection of merge key values computed for one item in a merge input sequence (one for each merge key component within the merge key specification) is referred to as a combined merge key value.
The combined posture of a choice operand group is determined by the postures of the operands in the group (the operand postures), and is the first of the following that applies:
If any of the operand postures is roaming, then the combined posture is roaming.
If all of the operand postures are grounded, then the combined posture is grounded.
If one or more of the operand postures is climbing and the remainder (if any) are grounded, then the combined posture is climbing.
If one or more of the operand postures is striding and the remainder (if any) are grounded, then the combined posture is striding.
If one or more of the operand postures is crawling and each of the remainder (if any) is either striding or grounded, then the combined posture is crawling.
Otherwise (for example, if the group includes both an operand with climbing posture and one with crawling posture), the combined posture is roaming.
The signatures of two components are compatible if they present the same interface to the user of the component. The additional rules depend on the kind of component.
The term component is used to refer to any of the following: a stylesheet function, a named template, a mode, an accumulator, an attribute set, a key, global variable, or a mode.
The term construct refers to the union of the following: a sequence constructor, an instruction, an attribute set, a value template, an expression, or a pattern.
A consuming construct is any construct deemed consuming by the rules in this section (19 Streamability).
A component declaration results in multiple components, one in the package in which the declaration appears, and potentially one in each package that uses the declaring package, directly or indirectly, subject to the visibility of the component. Each of these multiple components has the same declaring package, but each has a different containing package. For the original component, the declaring package and the containing package are the same; for a copy of a component made as a result of an xsl:use-package declaration, the declaring package will be the original package, and the containing package will be the package in which the xsl:use-package declaration appears.
The context item is the item currently being processed. An item (see [XDM 3.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.
For every expression, it is possible to establish by static analysis, information about the item type of the context item for evaluation of that expression. This is called the context item type of the expression.
If the context item is a node (as distinct from an atomic item such as an integer), then it is also referred to as the context node. The context node is not an independent variable, it changes whenever the context item changes. When the context item is an atomic item or a function item, there is no context node.
The context position is the position of the context item within the sequence of items currently being processed. It changes whenever the context item changes. When an instruction such as xsl:apply-templates or xsl:for-each is used to process a sequence of items, the first item in the sequence is processed with a context position of 1, the second item with a context position of 2, and so on.
The context posture. This captures information about how the context item used as input to the construct is positioned relative to the streamed input. The context posture of a construct C is the posture of the expression whose value sets the focus for the evaluation of C.
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).
Within a focus-changing construct there are one or more operands that are evaluated with a focus determined by the controlling operand (or in some cases such as xsl:on-completion, with an absentfocus); these are referred to as controlled operands.
Within a focus-changing construct there is in many cases one operand whose value determines the focus for evaluating other operands; this is referred to as the controlling operand.
Crawling: typically indicates that streamed nodes returned by a construct are reached by navigating the descendant[-or-self] axis.
While the xsl:matching-substring instruction is active, a set of current captured groups is available, corresponding to the capturing subexpressions of the regular expression.
The current group is the group itself, as a sequence of items
The current grouping key is a single atomic item, or in the case of a composite key, a sequence of atomic items, containing the grouping key of the items in the current group.
The current merge group is a map. During evaluation of an xsl:merge instruction, as each group of items with equal combined merge key values is processed, the current merge group is set to a map whose keys are the names of the various merge sources, and whose associated values are the items from each merge source having the relevant composite merge key value.
The current merge key is a an array, whose members are sequences of atomic items. There is one member in the array for each xsl:merge-key element in the merge key specification. During evaluation of an xsl:merge instruction, as each group of items with equal combined merge key values is processed, the current merge key is set to the combined merge key value that these items have in common.
At any point in the processing of a stylesheet, there is a current mode. When the transformation is initiated, the current mode is the initial mode, as described in 2.3 Initiating a Transformation. Whenever an xsl:apply-templates instruction is evaluated, the current mode becomes the mode selected by this instruction.
The current output URI is the URI associated with the principal result or secondary result that is currently being written.
At any point in the processing of a stylesheet, there may be a current template rule. Whenever a template rule is chosen as a result of evaluating xsl:apply-templates, xsl:apply-imports, or xsl:next-match, the template rule becomes the current template rule for the evaluation of the rule’s sequence constructor.
All the xsl:decimal-format declarations in a package that share the same name are grouped into a named decimal format; those that have no name are grouped into a single unnamed decimal format.
Top-level elements fall into two categories: declarations, and user-defined data elements. Top-level elements whose names are in the XSLT namespace are declarations. Top-level elements in any other namespace are user-defined data elements (see 3.7.4 User-defined Data Elements)
The declarations within a stylesheet level have a total ordering known as declaration order. The order of declarations within a stylesheet level is the same as the document order that would result if each stylesheet module were inserted textually in place of the xsl:include element that references it.
The above constructs (template rules belonging to a mode declared with streamable="yes"; and xsl:source-document, xsl:attribute-set, xsl:function, xsl:merge-source, and xsl:accumulator elements specifying streamable="yes") are said to be declared-streamable.
The declaring package of a component is the package that contains the declaration (or, in the case of xsl:attribute-set and xsl:key, multiple declarations) of the component.
In this specification the term default collation means the collation that is used by XPath operators such as eq and lt appearing in XPath expressions within the stylesheet.
The [xsl:]default-mode attribute defines the default mode, which is used as the default value for the mode attribute of all xsl:template and xsl:apply-templates elements within its scope.
If no priority attribute is specified on an xsl:template element, a default priority is computed, based on the syntax of the pattern supplied in the match attribute.
A string in the form of a lexical QName may occur as the value of an attribute node in a stylesheet module, or within an XPath expression contained in an attribute or text node within a stylesheet module, or as the result of evaluating an XPath expression contained in such a node. The element containing this attribute or text node is referred to as the defining element of the lexical QName.
Some constructs defined in this specification are described as being deprecated. The use of this term implies that stylesheet authors should not use the construct, and that the construct may be removed in a later version of this specification.
An error that is not capable of detection until a source document is being transformed is referred to as a dynamic error.
A processor that claims conformance with the dynamic evaluation featuremust evaluate the xsl:evaluate function as described in this specification.
An xsl:function declaration F is said to be eclipsed if the containing package includes an xsl:function declaration G such that F and G have the same name, F has lower import precedence than G, and the arity range of G includes the totality of the arity range of F.
The effective value of an attribute or text node in the stylesheet is the value after any required expansion or normalization.
The effective version of an element in a stylesheet module or package manifest is the decimal value of the [xsl:]version attribute (see 3.4 Standard Attributes) on that element or on the innermost ancestor element that has such an attribute, subject to special rules for the xsl:output and xsl:fallback elements.
A stylesheet module whose outermost element is the child of a non-XSLT element in a host document is referred to as an embedded stylesheet module. See 3.12 Embedded Stylesheet Modules.
A mode declared by an xsl:mode declaration that has one or more contained xsl:template declarations is referred to as an enclosing mode.
An EQName is a string representing an expanded QName where the string, after removing leading and trailing whitespace, is in the form defined by the EQNameXP production in the XPath specification.
An expanded QName is a value in the value space of the xs:QName datatype as defined in the XDM data model (see [XDM 3.0]): that is, a triple containing namespace prefix (optional), namespace URI (optional), and local name. Two expanded QNames are equal if the namespace URIs are the same (or both absent) and the local names are the same. The prefix plays no part in the comparison, but is used only if the expanded QName needs to be converted back to a string.
An explicit default for a parameter is indicated by the presence of either a select attribute or a non-empty sequence constructor.
A parameter is explicitly mandatory if it is a function parameterwith no required attribute, or if the required attribute is present and has the value yes.
Within this specification, the term XPath expression, or simply expression, means a string that matches the production ExprXP defined in [XPath 4.0].
An element from the XSLT namespace may have any attribute not from the XSLT namespace, provided that the expanded QName (see [XPath 4.0]) of the attribute has a non-null namespace URI. These attributes are referred to as extension attributes.
An extension function is a named function introduced to the static or dynamic context by mechanisms outside the scope of this specification.
An extension instruction is an element within a sequence constructor that is in a namespace (not the XSLT namespace) designated as an extension namespace.
The extension instruction mechanism allows namespaces to be designated as extension namespaces. When a namespace is designated as an extension namespace and an element with a name from that namespace occurs in a sequence constructor, then the element is treated as an instruction rather than as a literal result element.
The first of the two output states is called final output state. This state applies when instructions are writing to a final result tree.
A final result tree is a result tree that forms part of the output of a transformation: specifically, a tree built by post-processing the items in the principal result or in a secondary result. Once created, the contents of a final result tree are not accessible within the stylesheet itself.
The fixed namespace bindings for a stylesheet module are established using the fixed-namespaces attribute on the xsl:stylesheet, xsl:transform, or xsl:package element enclosing the stylesheet module.
When a sequence constructor is evaluated, the processor keeps track of which items are being processed by means of a set of implicit variables referred to collectively as the focus.
A focus-changing construct is a construct that has one or more operands that are evaluated with a different focus from the parent construct.
The focus-setting container of a construct C is the innermost focus-changing constructF (if one exists) such that C is directly or indirectly contained in a controlled operand of F. If there is no such construct F, then the focus-setting container is the containing declaration, for example an xsl:function or xsl:template element.
An element is processed with forwards compatible behavior if its effective version is greater than 4.0.
A free-ranging construct is any construct deemed free-ranging by the rules in this section (19 Streamability).
The term function definition is defined in Section 2.2.1 Static ContextXP. It is the definition of a function that can be called statically from within an XPath expression: in the case of XSLT it typically means either a stylesheet function, or a built-in function such as those defined in [Functions and Operators 4.0]
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.
There are 28 fundamental item types: the 7 node kinds defined in [XDM 3.0] (element, attribute, etc.), the 19 primitive atomic types defined in [XML Schema Part 2], plus the types fn(*) and xs:untypedAtomic. The fundamental item types are disjoint, and every item is an instance of exactly one of them.
Many constructs share the same streamability rules. These rules, referred to as the general streamability rules, are defined here.
An item that is the global context item for the transformation acts as the context item when evaluating the select expression or sequence constructor of a global variablewhose declaration is within the top-level package, as described in 5.3.3.1 Maintaining Position: the Focus. The global context item may also be available in a named template when the stylesheet is invoked as described in 2.3.4 Call-Template Invocation
A top-levelvariable-binding element declares a global variable that is visible everywhere except within any region where it is shadowed by another variable binding.
Grounded: indicates that the value returned by the construct does not contain nodes from the streamed input document
The xsl:for-each-group instruction allocates the items in an input sequence into groups of items (that is, it establishes a collection of sequences) based either on common values of a grouping key, or on a pattern that the initial or final item in a group must match.
If either of the group-by or group-adjacent attributes is present, then for each item in the population a set of grouping keys is calculated, as follows: the expression contained in the group-by or group-adjacent attribute is evaluated; the result is atomized; and any xs:untypedAtomic items are cast to xs:string. If composite="yes" is specified, there is a single grouping key whose value is the resulting sequence; otherwise, there is a set of grouping keys, consisting of the distinct atomic items present in the result sequence.
A guaranteed-streamable construct is a construct that is declared to be streamable and that follows the particular rules for that construct to make streaming possible, as defined by the analysis in this specification.
Whether or not the operand is higher-order. For this purpose an operand O of a construct C is higher-order if the semantics of C potentially require O to be evaluated more than once during a single evaluation of C.
A xsl:package-location without the attribute is-priority, or with is-priority set to true is a high priority package location.
Two components are said to be homonymous if they have the same symbolic identifier.
Types S and T are considered identical for the purpose of these rules if and only if subtype(S, T) and subtype(T, S) both hold, where the subtype relation is defined in Section 3.3.1 Subtypes of Sequence TypesXP.
The result of evaluating a sequence constructor is the sequence of items formed by concatenating the results of evaluating each of the nodes in the sequence constructor, retaining order. This is referred to as the immediate result of the sequence constructor.
A specific product that performs the functions of an XSLT processor is referred to as an implementation.
In this specification, the term implementation-defined refers to a feature where the implementation is allowed some flexibility, and where the choices made by the implementation must be described in documentation that accompanies any conformance claim.
The term implementation-dependent refers to a feature where the behavior may vary from one implementation to another, and where the vendor is not expected to provide a full specification of the behavior.
If a parameter that is not explicitly mandatory has no explicit default value, then it has an implicit default value, which is the empty sequence if there is an as attribute, or a zero-length string if not.
If a parameter has an implicit default value which cannot be converted to the required type (that is, if it has an as attribute which does not permit the empty sequence), then the parameter is implicitly mandatory.
A declarationD in the stylesheet is defined to have lower import precedence than another declaration E if the stylesheet level containing D would be visited before the stylesheet level containing E in a post-order traversal of the import tree (that is, a traversal of the import tree in which a stylesheet level is visited after its children). Two declarations within the same stylesheet level have the same import precedence.
The stylesheet levels making up a stylesheet are treated as forming an import tree. In the import tree, each stylesheet level has one child for each xsl:import declaration that it contains.
A stylesheet may be evaluated by calling a named stylesheet function, referred to as the initial function.
For each group, the item within the group that is first in population order is known as the initial item of the group.
A stylesheet may be evaluated by supplying a value to be processed, together with an initial mode. The value (which can be any sequence of items) is referred to as the initial match selection. The processing then corresponds to the effect of the xsl:apply-templates instruction.
The initial mode is the mode used to select template rules for processing items in the initial match selection when apply-templates invocation is used to initiate a transformation.
A stylesheet may be evaluated by selecting a named template to be evaluated; this is referred to as the initial named template.
The sequence to be sorted is referred to as the initial sequence.
The initial setting of a component of the dynamic context is used when evaluating global variables and stylesheet parameters, when evaluating the use and match attributes of xsl:key, and when evaluating the initial-value of xsl:accumulator and the select expressions or contained sequence constructors of xsl:accumulator-rule
The schema components that may be referenced by name in a package are referred to as the in-scope schema components.
An operand usage of inspection indicates that the construct accesses properties of a supplied node that are available without reading its subtree.
An instruction is either an XSLT instruction or an extension instruction.
The following constructs are classified as invocation constructs: the instructions xsl:call-template, xsl:apply-templates, xsl:apply-imports, and xsl:next-match; XPath function calls that bind to stylesheet functions; XPath dynamic function calls; the functions accumulator-before and accumulator-after; the [xsl:]use-attribute-sets attribute. These all have the characteristic that they can cause evaluation of constructs that are not lexically contained within the calling construct.
A key is defined as a set of xsl:key declarations in the same package that share the same name.
The expression in the use attribute and the sequence constructor within an xsl:key declaration are referred to collectively as the key specifier. The key specifier determines the values that may be used to find a node using this key.
A lexical QName is a string representing an expanded QName where the string, after removing leading and trailing whitespace, is within the lexical space of the xs:QName datatype as defined in XML Schema (see [XML Schema Part 2]): that is, a local name optionally preceded by a namespace prefix and a colon.
Every package within a stylesheet, other than the top-level package, is referred to as a library package.
A namespace URI in the stylesheet tree that is being used to specify a namespace URI in the result tree is called a literal namespace URI.
In a sequence constructor, an element in the stylesheet that does not belong to the XSLT namespace and that is not an extension instruction (see 24.2 Extension Instructions) is classified as a literal result element.
As well as being allowed as a declaration, the xsl:variable element is also allowed in sequence constructors. Such a variable is known as a local variable.
A xsl:package-location with is-priority set to false is a low priority package location.
The match type of a pattern is the most specific U-type that is known to match all items that the pattern can match.
A merge activation is a single evaluation of the sequence constructor contained within the xsl:merge-action element, which occurs once for each distinct combined merge key value.
A merge input sequence is an arbitrary sequenceDM30 of items which is already sorted according to the merge key specification for the corresponding merge source definition.
A merge key component specifies one component of a merge key specification; it corresponds to a single xsl:merge-key element in the stylesheet.
A merge key specification consists of one or more adjacent xsl:merge-key elements which together define how the merge input sequences selected by a merge source definition are sorted. Each xsl:merge-key element defines one merge key component.
For each item in a merge input sequence, a value is computed for each merge key component within the merge key specification. The value computed for an item by using the Nth merge key component is referred to as the Nth merge key value of that item.
A merge source definition is the definition of one kind of input to the merge operation. It selects zero or more merge input sequences, and it includes a merge key specification to define how the merge key values are computed for each such merge input sequence.
A mode is a set of template rules; when the xsl:apply-templates instruction selects a set of items for processing, it identifies the rules to be used for processing those items by nominating a mode, explicitly or implicitly.
All the xsl:mode declarations in a package that share the same name are grouped into a named mode definition; those that have no name are grouped into a single unnamed mode definition.
A motionless construct is any construct deemed motionless by the rules in this section (19 Streamability).
Templates can be invoked by name. An xsl:template element with a name attribute defines a named template.
The rules for the individual XSLT instructions that construct a result tree (see 11 Creating Nodes) prescribe some of the situations in which namespace nodes are written to the tree. These rules, however, are not sufficient to ensure that the prescribed constraints are always satisfied. The XSLT processor must therefore add additional namespace nodes to satisfy these constraints. This process is referred to as namespace fixup.
The native namespace bindings for any element in an XSLT stylesheet module are the prefix-uri mappings defined by the namespace nodes of that element, according to the rules in [XDM 3.0].
An operand usage of navigation indicates that the construct may navigate freely from the supplied node to other nodes in the same tree, in a way that is not constrained by the streamability rules.
A node pattern uses a subset of the syntax for path expressions, and is defined to match a node if the corresponding path expression would select the node. Node patterns may also be formed by combining other patterns using union, intersection, and difference operators.
The 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 [TERMDEF dt-dynamic-function-invocation IN XP40]dynamic function invocations, (that is calls to function items as permitted by XPath 3.0). It excludes calls to some functions in the namespace http://www.w3.org/2005/xpath-functions, in particular those that explicitly depend on the context, such as the current-group and regex-group functions. It is implementation-defined whether, and under what circumstances, calls to extension functions are non-contextual.
A predicate is a non-positional predicate if it satisfies both of the following conditions:
The predicate does not contain a function call or named function reference to any of the following functions, unless that call or reference occurs within a nested predicate:
Note:
The exception for nested predicates is there to ensure that patterns such as match="p[@code = $status[last()]] are not disqualified.
The expression immediately contained in the predicate is a non-numeric expression. An expression is non-numeric if the intersection of its static type (see 19.1 Determining the Static Type of a Construct) with U{xs:decimal, xs:double, xs:float} is U{}.
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.
In an actual instance of a construct, there will be a number of operands. Each operand is itself a construct; the construct tree can be defined as the transitive relation between constructs and their operands.
For every construct kind, there is a set of zero or more operand roles.
The operand usage. This gives information, in the case where the operand value contains nodes, about how those nodes are used. The operand usage takes one of the values absorption, inspection, transmission, or navigation.
There is a total ordering among groups referred to as the order of first appearance. A group G is defined to precede a group H in order of first appearance if the initial item of G precedes the initial item of H in population order. If two groups G and H have the same initial item (because the item is in both groups) then G precedes H if the grouping key of G precedes the grouping key of H in the sequence that results from evaluating the group-by expression of this initial item.
All the xsl:output declarations within a package that share the same name are grouped into a named output definition; those that have no name are grouped into a single unnamed output definition.
Each instruction in the stylesheet is evaluated in one of two possible output states: final output state or temporary output state.
A component in a using package may override a component in a used package, provided that the visibility of the component in the used package is either abstract or public. The overriding declaration is written as a child of the xsl:override element, which in turn appears as a child of xsl:use-package.
An explicit package is represented by an xsl:package element, which will generally be the outermost element of an XML document. When the xsl:package element is not used explicitly, the entire stylesheet comprises a single implicit package.
The content of the xsl:package element is referred to as the package manifest
The xsl:param element declares a parameter, which may be a stylesheet parameter, a template parameter, a function parameter, or an xsl:iterate parameter. A parameter is a variable with the additional property that its value can be set by the caller.
A pattern specifies a set of conditions on an item. An item that satisfies the conditions matches the pattern; an item that does not satisfy the conditions does not match the pattern.
The picture string is the string supplied as the second argument of the format-number function.
The xsl:number instruction performs two tasks: firstly, determining a place marker (this is a sequence of integers, to allow for hierarchic numbering schemes such as 1.12.2 or 3(c)ii), and secondly, formatting the place marker for output as a text node in the result sequence.
The sequence of items to be grouped, which is referred to as the population, is determined by evaluating the XPath expression contained in the select attribute.
The population is treated as a sequence; the order of items in this sequence is referred to as population order.
The integer literals and the optional NamePart within the version number are referred to as the portions of the version number.
The posture of the expression. This captures information about the way in which the streamed input document is positioned on return from evaluating the construct. The posture takes one of the values climbing, striding, crawling, roaming, or grounded.
An operand is potentially consuming if at least one of the following conditions applies:
The operand usage is transmission and the operand is not grounded.
A predicate pattern is written as . (dot) followed by zero or more predicates in square brackets, and it matches any item for which each of the predicates evaluates to true.
A principal result: this can be any sequence of items (as defined in [XDM 3.0]).
Within a package, one stylesheet module functions as the principal stylesheet module. The complete package is assembled by finding the stylesheet modules referenced directly or indirectly from the principal stylesheet module using xsl:include and xsl:import elements: see 3.11.2 Stylesheet Inclusion and 3.11.3 Stylesheet Import.
The priority of a template rule is specified by the priority attribute on the xsl:template declaration. If no priority is specified explicitly for a template rule, its default priority is used, as defined in 6.66.7 Default Priority for Template Rules.
The first package location whose value of href, when resolved as described in 5.95.8 URI References, allows the system to find the specified resource, and its entry if the resource is an archive, is the optimal package location.
There is another total ordering among groups referred to as processing order. If group R precedes group S in processing order, then in the result sequence returned by the xsl:for-each-group instruction the items generated by processing group R will precede the items generated by processing group S.
The software responsible for transforming source trees into result trees using an XSLT stylesheet is referred to as the processor. This is sometimes expanded to XSLT processor to avoid any confusion with other processors, for example an XML processor.
The result of invoking the selected component, after any required conversion to the declared result type of the component, is referred to as the raw result.
The process of identifying the component to which a symbolic reference applies (possibly chosen from several homonymous alternatives) is called reference binding.
The context within a stylesheet where an XPath expression appears may specify the required type of the expression. The required type indicates the type of the value that the expression is expected to return.
The XSLT namespace, together with certain other namespaces recognized by an XSLT processor, are classified as reserved namespaces and must be used only as specified in this and related specifications.
The term result tree is used to refer to any tree constructed by instructions in the stylesheet. A result tree is either a final result tree or a temporary tree.
Roaming: indicates that the nodes returned by an expression could be anywhere in the tree, which inevitably means that the construct cannot be evaluated using streaming.
A RelativePathExpr is a scanning expression if and only if it is syntactically equivalent to some motionlesspattern.
A schema-aware XSLT processor is an XSLT processor that implements the mandatory requirements of this specification connected with the xsl:import-schema declaration, the [xsl:]validation and [xsl:]type attributes, and the ability to handle input documents whose nodes have type annotations other than xs:untyped and xs:untypedAtomic. The mandatory requirements of this specification are taken to include the mandatory requirements of XPath 4.0, as described in [XPath 4.0]. A requirement is mandatory unless the specification includes wording (such as the use of the words should or may) that clearly indicates that it is optional.
Type definitions and element and attribute declarations are referred to collectively as schema components.
The schema instance namespacehttp://www.w3.org/2001/XMLSchema-instance, with conventional prefix xsi, is used as defined in [XML Schema Part 1]
The schema namespacehttp://www.w3.org/2001/XMLSchema, with conventional prefix xs, is used as defined in [XML Schema Part 1]
Zero or more secondary results: each secondary result can be any sequence of items (as defined in [XDM 3.0]).
A sequence constructor is a sequence of zero or more sibling nodes in the stylesheet that can be evaluated to return a sequence of nodes, atomic items, and function items. The way that the resulting sequence is used depends on the containing instruction.
A SequenceType constrains the type and number of items in a sequence. The term is used both to denote the concept, and to refer to the syntactic form in which sequence types are expressed in the XPath grammar: specifically SequenceTypeXP in [XPath 4.0].
A frequent requirement is to output a final result tree as an XML document (or in other formats such as HTML). This process is referred to as serialization.
If a transformation has successfully produced a principal result or secondary result, it is still possible that errors may occur in serializing that result . For example, it may be impossible to serialize the result using the encoding selected by the user. Such an error is referred to as a serialization error.
A processor that claims conformance with the serialization featuremust support the conversion of a final result tree to a sequence of octets following the rules defined in 26 Serialization.
Within a region of the stylesheet where a binding B1 is visible, B1 shadows another binding B2 having the same name as B1 if B1 occurs at a point where B2 is visible.
A simplified stylesheet, which is a subtree rooted at a literal result element, as described in 3.8 Simplified Stylesheet Modules. This is first converted to a standard stylesheet module by wrapping it in an xsl:stylesheet element using the transformation described in 3.8 Simplified Stylesheet Modules.
A singleton focus based on an item J has the context item (and therefore the context node, if J is a node) set to J, and the context position and context size both set to 1 (one).
A snapshot of a node N is a deep copy of N, as produced by the xsl:copy-of instruction with copy-namespaces set to yes, copy-accumulators set to yes, and validation set to preserve, with the additional property that for every ancestor of N, the copy also has a corresponding ancestor whose name, node-kind, and base URI are the same as the corresponding ancestor of N, and that has copies of the attributes, namespaces and accumulator values of the corresponding ancestor of N. But the ancestor has a type annotation of xs:anyType, has the properties nilled, is-id, and is-idref set to false, and has no children other than the child that is a copy of N or one of its ancestors.
The sequence after sorting as defined by the xsl:sort elements is referred to as the sorted sequence.
Within a sort key specification, each xsl:sort element defines one sort key component.
A sort key specification is a sequence of one or more adjacent xsl:sort elements which together define rules for sorting the items in an input sequence to form a sorted sequence.
For each item in the initial sequence, a value is computed for each sort key component within the sort key specification. The value computed for an item by using the Nth sort key component is referred to as the Nth sort key value of that item.
The term source tree means any tree provided as input to the transformation. This includes the document containing the global context item if any, documents containing nodes present in the initial match selection, documents containing nodes supplied as the values of stylesheet parameters, documents obtained from the results of functions such as document, doc, and collection, documents read using the xsl:source-document instruction, and documents returned by extension functions or extension instructions. In the context of a particular XSLT instruction, the term source tree means any tree provided as input to that instruction; this may be a source tree of the transformation as a whole, or it may be a temporary tree produced during the course of the transformation.
A sort key specification is said to be stable if its first xsl:sort element has no stable attribute, or has a stable attribute whose effective value is yes.
There are a number of standard attributes that may appear on any XSLT element: specifically default-collation, default-mode, default-validation, exclude-result-prefixes, expand-text, extension-element-prefixes, schema-role, use-when, version, and xpath-default-namespace.
The standard error namespacehttp://www.w3.org/2005/xqt-errors, with conventional prefix err, is used for error codes defined in this specification and related specifications. It is also used for the names of certain predefined variables accessible within the scope of an xsl:catch element.
The standard function namespacehttp://www.w3.org/2005/xpath-functions, with conventional prefix fn, is used for functions in the function library defined in [Functions and Operators 4.0] and for standard functions defined in this specification.
A standard stylesheet module, which is a subtree rooted at an xsl:stylesheet or xsl:transform element.
An error that can be detected by examining a stylesheet before execution starts (that is, before the source document and values of stylesheet parameters are available) is referred to as a static error.
A static expression is an XPath expression whose value must be computed during static analysis of the stylesheet.
A static variable declared using an xsl:param element is referred to as a static parameter.
The static type of a construct is such that all values produced by evaluating the construct will conform to that type. The static type of a construct comprises a U-type and a cardinality. A cardinality is a range of integers (from min to max).
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.
Stylesheet functions belong to one of a number of streamability categories: the choice of category characterizes the way in which the function handles streamed input.
A streamable mode is a mode that is declared in an xsl:mode declaration with the attribute streamable="yes".
A streamed document is a source tree that is processed using streaming, that is, without constructing a complete tree of nodes in memory.
A streamed node is a node in a streamed document.
The term streaming refers to a manner of processing in which XML documents (such as source and result documents) are not represented by a complete tree of nodes occupying memory proportional to document size, but instead are processed “on the fly” as a sequence of events, similar in concept to the stream of events notified by an XML parser to represent markup in lexical XML.
A processor that claims conformance with the streaming featuremust use streamed processing in cases where (a) streaming is requested (for example by using the attribute streamable="yes" on xsl:mode, or on the xsl:source-document instruction) and (b) the constructs in question are guaranteed-streamable according to this specification.
The first parameter of a declared-streamablestylesheet function is referred to as a streaming parameter.
Striding: indicates that the result of a construct contains a sequence of streamed nodes, in document order, that are peers in the sense that none of them is an ancestor or descendant of any other.
The term string value is defined in Section 5.13 string-value Accessor DM30. Every node has a string value. For example, the string value of an element is the concatenation of the string values of all its descendant text nodes.
A stylesheet consists of one or more packages: specifically, one top-level package and zero or more library packages.
An xsl:function declaration declares the name, parameters, and implementation of a family of stylesheet functions that can be called from any XPath expression within the stylesheet (subject to visibility rules).
A stylesheet level is a collection of stylesheet modules connected using xsl:include declarations: specifically, two stylesheet modules A and B are part of the same stylesheet level if one of them includes the other by means of an xsl:include declaration, or if there is a third stylesheet module C that is in the same stylesheet level as both A and B.
A package consists of one or more stylesheet modules, each one forming all or part of an XML document.
A top-levelxsl:param element declares a stylesheet parameter. A stylesheet parameter is a global variable with the additional property that its value can be supplied by the caller when a transformation is initiated.
The value of the variable is computed using the expression given in the select attribute or the contained sequence constructor, as described in 9.3 Values of Variables and Parameters. This value is referred to as the supplied value of the variable.
Every construct has a sweep, which is a measure of the extent to which the current position in the input stream moves during the evaluation of the expression. The sweep is one of: motionless, consuming, or free-ranging .
The symbolic identifier of a component is a composite name used to identify the component uniquely within a package. The symbolic identifier comprises the kind of component (stylesheet function, named template, accumulator, attribute set, global variable, key, or mode), the expanded QName of the component (namespace URI plus local name), and in the case of stylesheet functions, the upper bound of the arity range.
The declaration of a component includes constructs that can be interpreted as references to other components by means of their symbolic identifiers. These constructs are generically referred to as symbolic references. Examples of constructs that give rise to symbolic references are the name attribute of xsl:call-template; the [xsl:]use-attribute-sets attribute of xsl:copy, xsl:element, and literal result elements; the explicit or implicit mode attribute of xsl:apply-templates; XPath variable references referring to global variables; XPath static function calls (including partial function applications) referring to stylesheet functions; and named function references (example: my:f#1) referring to stylesheet functions.
An instructionJ is in a tail position within a sequence constructorSC if it satisfies one of the following conditions:
J is the last instruction in SC, ignoring any xsl:fallback instructions.
J is in a tail position within the sequence constructor that forms the body of an xsl:if instruction that is itself in a tail position within SC.
J is in a tail position within the sequence constructor that forms the body of an xsl:when or xsl:otherwise branch of an xsl:chooseor xsl:switch instruction that is itself in a tail position within SC.
J is in a tail position within the sequence constructor that forms the body of an xsl:try instruction that is itself in a tail position within SC (that is, it is immediately followed by an xsl:catch element, ignoring any xsl:fallback elements).
J is in a tail position within the sequence constructor that forms the body of an xsl:catch element within an xsl:try instruction that is itself in a tail position within SC.
The string that results from evaluating the expression in the xpath attribute is referred to as the target expression.
The namespace URI that is to be used in the result tree as a substitute for a literal namespace URI is called the target namespace URI.
An xsl:template declaration defines a template, which contains a sequence constructor; this sequence constructor is evaluated to determine the result of the template. A template can serve either as a template rule, invoked by matching items against a pattern, or as a named template, invoked explicitly by name. It is also possible for the same template to serve in both capacities.
An xsl:param element may appear as a child of an xsl:template element, before any non-xsl:param children of that element. Such a parameter is known as a template parameter. A template parameter is a local variable with the additional property that its value can be set when the template is called, using any of the instructions xsl:call-template, xsl:apply-templates, xsl:apply-imports, or xsl:next-match.
A stylesheet contains a set of template rules (see 6 Template Rules). A template rule has three parts: a pattern that is matched against selected items (often but not necessarily nodes), a (possibly empty) set of template parameters, and a sequence constructor that is evaluated to produce a sequence of items.
The second of the two output states is called temporary output state. This state applies when instructions are writing to a temporary tree or any other non-final destination.
The term temporary tree means any tree that is neither a source tree nor a final result tree.
In a text node that is designated as a text value template, expressions can be used by surrounding each expression with curly brackets ({}).
An element occurring as a child of an xsl:package, xsl:stylesheet, xsl:transform, or xsl:override element is called a top-level element.
For a given transformation, one package functions as the top-level package. The complete stylesheet is assembled by finding the packages referenced directly or indirectly from the top-level package using xsl:use-package declarations: see 3.5.2 Dependencies between Packages.
An operand usage of transmission indicates that the construct will (potentially) return a supplied node as part of its result to the calling construct (that is, to its parent in the construct tree).
A traversal of a tree is a sequence of traversal events.
a traversal event (shortened to event in this section) is a pair comprising a phase (start or end) and a node.
The term tree is used (as in [XDM 3.0]) to refer to the aggregate consisting of a parentless node together with all its descendant nodes, plus all their attributes and namespaces.
A parameter passed to a template may be defined as a tunnel parameter. Tunnel parameters have the property that they are automatically passed on by the called template to any further templates that it calls, and so on recursively.
The type-adjusted posture and sweep of a construct C, with respect to a type T, are the posture and sweep established by applying the general streamability rules to a construct D whose single operand is the construct C, where the operand usage of C in D is the type-determined usage based on the required type T.
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 Section 5.14 type-name Accessor DM30.
The type-determined usage of an operand is as follows: if the required type (ignoring occurrence indicator) is fn(*) or a subtype thereof, then inspection; if the required type (ignoring occurrence indicator) is an atomic or union type, then absorption; otherwise navigation.
The term typed value is defined in Section 5.15 typed-value Accessor DM30. Every node, other than an element whose type annotation identifies it as having element-only content, has a typed value. For example, the typed value of an attribute of type xs:IDREFS is a sequence of zero or more xs:IDREF values.
Certain errors are classified as type errors. A type error occurs when the value supplied as input to an operation is of the wrong type for that operation, for example when an integer is supplied to an operation that expects a node.
A type pattern can be written as type(T) (where T is an ItemTypeXP followed by zero or more predicates in square brackets, and it matches any item of type T which each of the predicates evaluates to true.
The unnamed mode is the default mode used when no mode attribute is specified on an xsl:apply-templates instruction or xsl:template declaration, unless a different default mode has been specified using the [xsl:]default-mode attribute of a containing element.
Within this specification, the term URI Reference, unless otherwise stated, refers to a string in the lexical space of the xs:anyURI datatype as defined in [XML Schema Part 2].
If a package Q contains an xsl:use-package element that references package P, then package Q is said to use package P. In this relationship package Q is referred to as the using package, package P as the used package.
In addition to declarations, the xsl:stylesheet element may contain among its children any element not from the XSLT namespace, provided that the expanded QName of the element has a non-null namespace URI. Such elements are referred to as user-defined data elements.
A U-type is a set of fundamental item types.
An item is vacuous if it is one of the following: a zero-length text node; a document node with no children; an atomic item which, on casting to xs:string, produces a zero-length string; or an array which on flattening using the array:flatten function produces either an empty sequence or a sequence consisting entirely of vacuous items.
A variable is a binding between a name and a value. The value of a variable is any sequence (of nodes, atomic items, and/or function items), as defined in [XDM 3.0].
Collectively, attribute value templates and text value templates are referred to as value templates.
The xsl:variable element declares a variable, which may be a global variable or a local variable.
The two elements xsl:variable and xsl:param are referred to as variable-binding elements.
The visibility of a component is one of: private, public, abstract, final, or hidden.
A whitespace text node is a text node whose content consists entirely of whitespace characters (that is, U+0009 (TAB) , U+000A (NEWLINE) , U+000D (CARRIAGE RETURN) , or U+0020 (SPACE) ).
The XML namespace, defined in [Namespaces in XML] as http://www.w3.org/XML/1998/namespace, is used for attributes such as xml:lang, xml:space, and xml:id.
The term XPath 1.0 compatibility mode is defined in Section 2.2.1 Static ContextXP. This is a setting in the static context of an XPath expression; it has two values, true and false. When the value is set to true, the semantics of function calls and certain other operations are adjusted to give a greater degree of backwards compatibility between XPath 4.0 and XPath 1.0.
An element in the stylesheet is processed with XSLT 1.0 behavior if its effective version is equal to 1.0.
A processor that claims conformance with the XSLT 1.0 compatibility featuremust support the processing of stylesheet instructions and XPath expressions with XSLT 1.0 behavior, as defined in 3.9 Backwards Compatible Processing.
An element is processed with XSLT 2.0 behavior if its effective version is equal to 2.0.
An element is processed with XSLT 3.0 behavior if its effective version is equal to 3.0.
An XSLT element is an element in the XSLT namespace whose syntax and semantics are defined in this specification.
An XSLT instruction is an XSLT element whose syntax summary in this specification contains the annotation <!-- category: instruction -->.
The XSLT namespace has the URI http://www.w3.org/1999/XSL/Transform. It is used to identify elements, attributes, and other names that have a special meaning defined in this specification.
This appendix provides a summary of error conditions that a processor may raise. This list includes all error codes defined in this specification, but this is not an exhaustive list of all errors that can occur. Implementations must raise errors using these error codes, and applications can test for these codes; however, when more than one rule in the specification is violated, different processors will not necessarily raise the same error code. Implementations are not required to raise errors using the descriptive text used here.
Note:
The appendix is non-normative because the same information is given normatively elsewhere.
Static errors
It is a static error if an XSLT-defined element is used in a context where it is not permitted, if a required attribute is omitted, or if the content of the element does not correspond to the content that is allowed for the element.
It is a static error if an attribute (other than an attribute written using curly brackets in a position where an attribute value template is permitted) contains a value that is not one of the permitted values for that attribute.
It is a static error to use a reserved namespace in the name of a named template, a mode, an attribute set, a key, a decimal-format, a variable or parameter, a stylesheet function, a named output definition, an accumulator, or a character map; except that the name xsl:initial-template is permitted as a template name.
It is a static error to use a reserved namespace in the name of any extension function or extension instruction, other than a function or instruction defined in this specification or in a normatively referenced specification. It is a static error to use a prefix bound to a reserved namespace in the [xsl:]extension-element-prefixes attribute.
It is a static error for an element from the XSLT namespace to have an attribute whose namespace is either null (that is, an attribute with an unprefixed name) or the XSLT namespace, other than attributes defined for the element in this document.
The value of the version attribute must be a number: specifically, it must be a valid instance of the type xs:decimal as defined in [XML Schema Part 2].
An xsl:stylesheet, xsl:transform, or xsl:package element must not have any text node children.
It is a static error if a token appearing in the fixed-namespaces attribute takes a form that is not one of the permitted forms, or if it is interpreted as a URI but cannot be dereferenced to locate a namespace well-formed XML document. It is not permitted to bind the prefix xmlns. It is not permitted to bind the prefix xml or the XML namespace URI http://www.w3.org/XML/1998/namespace, other than to each other.
It is a static error if the value of an [xsl:]default-collation attribute, after resolving against the base URI, contains no URI that the implementation recognizes as a collation URI.
It is a static error if an xsl:stylesheet, xsl:transform, or xsl:package element has a child element whose name has a null namespace URI.
It is a static error if the processor is not able to retrieve the resource identified by the URI reference [ in the href attribute of xsl:include or xsl:import ] , or if the resource that is retrieved does not contain a stylesheet module.
An xsl:include element must be a top-level element.
An xsl:import element must be a top-level element.
It is a static error if a stylesheet module directly or indirectly references itself via a chain of xsl:include and xsl:import declarations that contains at least one xsl:import.
It is a static error if an xsl:import-schema element that contains an xs:schema element has a schema-location attribute, or if it has a namespace attribute that conflicts with the target namespace of the contained schema.
It is a static error if the synthetic schema document does not satisfy the constraints described in [XML Schema Part 1] (section 5.1, Errors in Schema Construction and Structure). This includes, without loss of generality, conflicts such as multiple definitions of the same name.
Within an XSLT element that is required to be empty, any content other than comments or processing instructions, including any whitespace text node preserved using the xml:space="preserve" attribute, is a static error.
It is a static error if there is a stylesheet module in a package that specifies input-type-annotations="strip" and another stylesheet module that specifies input-type-annotations="preserve", or if a stylesheet module specifies the value strip or preserve and the same value is not specified on the xsl:package element of the containing package.
It is a static error if within any package the same NameTestXP appears in both an xsl:strip-space and an xsl:preserve-space declaration if both have the same import precedence. Two NameTests are considered the same if they match the same set of names (which can be determined by comparing them after expanding namespace prefixes to URIs).
In the case of a prefixed lexical QName used as the value (or as part of the value) of an attribute in the stylesheet, or appearing within an XPath expression in the stylesheet, it is a static error if the defining element has no namespace node whose name matches the prefix of the lexical QName.
Where an attribute is defined to contain a pattern, it is a static error if the pattern does not match the production Pattern40.
It is a static error if an unescaped left curly bracket appears in a fixed part of a value template without a matching right curly bracket.
It is a static error if an unescaped right curly bracket occurs in a fixed part of a value template.
An xsl:template element must have either a match attribute or a name attribute, or both. An xsl:template element that has no match attribute must have no mode attribute and no priority attribute. An xsl:template element that has no name attribute must have no visibility attribute.
The value of the priority attribute [ of the xsl:template element] must conform to the rules for the xs:decimal type defined in [XML Schema Part 2]. Negative values are permitted.
It is a static error if for any named or unnamed mode, a package explicitly specifies two conflicting values for the same attribute in different xsl:mode declarations having the same import precedence, unless there is another definition of the same attribute with higher import precedence. The attributes in question are the attributes other than name on the xsl:mode element.
It is a static error if the list of modes [in the mode attribute of xsl:template ] is empty, if the same token is included more than once in the list, if the list contains an invalid token, or if the token #all appears together with any other value.
It is a static error if the values of the name attribute of two sibling xsl:param elements represent the same expanded QName.
It is a static error if a variable-binding element has a select attribute and has non-empty content.
It is a static error if a package contains more than one non-hidden binding of a global variable with the same name and same import precedence, unless it also contains another binding with the same name and higher import precedence.
It is a static error if a package contains an xsl:call-template instruction whose name attribute does not match the name attribute of any named template visible in the containing package (this includes any template defined in this package, as well as templates accepted from used packages whose visibility in this package is not hidden). For more details of the process of binding the called template, see 3.5.4.5 Binding References to Components.
It is a static error if a package contains more than one non-hidden template with the same name and the same import precedence, unless it also contains a template with the same name and higher import precedence.
It is a static error if two or more sibling xsl:with-param elements have name attributes that represent the same expanded QName.
In the case of xsl:call-template, it is a static error to pass a non-tunnel parameter named x to a template that does not have a non-tunnel template parameter named x, unless the xsl:call-template instruction is processed with XSLT 1.0 behavior.
It is a static error if a package contains both (a) a named template named T that is not overridden by another named template of higher import precedence and that has an explicitly mandatory non-tunnel parameter named P, and (b) an xsl:call-template instruction whose name attribute equals T and that has no non-tunnel xsl:with-param child element whose name attribute equals P. (All names are compared as QNames.)
It is a static error if the value of the use-attribute-sets attribute of an xsl:copy, xsl:element, or xsl:attribute-set element, or the xsl:use-attribute-sets attribute of a literal result element, is not a whitespace-separated sequence of EQNames, or if it contains an EQName that does not match the name attribute of any xsl:attribute-set declaration in the containing package.
If an xsl:attribute set element specifies streamable="yes" then every attribute set referenced in its use-attribute-sets attribute (if present) must also specify streamable="yes".
It is a static error if a stylesheet function has a name that is in no namespace.
It is a static error if an xsl:param child of an xsl:function element has either a select attribute or non-empty content, unless it specifies required="no".
It is a static error if an xsl:param child of an xsl:function element specifies required="no", unless all following-sibling xsl:param elements also specify required="no".
It is a static error for a package to contain an xsl:function declaration F and an xsl:function declaration G such that F and G have the same expanded QName, F has lower import precedence than G, and the arity range of G includes part but not all of the arity range of F, unless G is itself eclipsed by another xsl:function declaration.
It is a static error for a package to contain an xsl:function declaration F and an xsl:function declaration G such that F and G have the same expanded QName and the same import precedence, if the arity ranges of F and G overlap in whole or in part, unless F and G are both eclipsed by another xsl:function declaration.
It is a static error if an attribute on a literal result element is in the XSLT namespace, unless it is one of the attributes explicitly defined in this specification.
It is a static error if a namespace prefix is used within the [xsl:]exclude-result-prefixes attribute and there is no namespace binding in scope for that prefix.
It is a static error if the value #default is used within the [xsl:]exclude-result-prefixes attribute and the parent element of the [xsl:]exclude-result-prefixes attribute has no default namespace.
It is a static error if within a package there is more than one such declaration [more than one xsl:namespace-alias declaration] with the same literal namespace URI and the same import precedence and different values for the target namespace URI, unless there is also an xsl:namespace-alias declaration with the same literal namespace URI and a higher import precedence.
It is a static error if a value other than #default is specified for either the stylesheet-prefix or the result-prefix attributes of the xsl:namespace-alias element when there is no in-scope binding for that namespace prefix.
It is a static error if the select attribute of the xsl:attribute element is present unless the element has empty content.
It is a static error if the select attribute of the xsl:value-of element is present when the content of the element is non-empty.
It is a static error if the select attribute of the xsl:processing-instruction element is present unless the element has empty content.
It is a static error if the select attribute of the xsl:namespace element is present when the element has content other than one or more xsl:fallback instructions, or if the select attribute is absent when the element has empty content.
It is a static error if the select attribute of the xsl:comment element is present unless the element has empty content.
It is a static error if the value attribute of xsl:number is present unless the select, level, count, and from attributes are all absent.
It is a static error if an xsl:sort element with a select attribute has non-empty content.
It is a static error if an xsl:sort element other than the first in a sequence of sibling xsl:sort elements has a stable attribute.
It is a static error if an xsl:perform-sort instruction with a select attribute has any content other than xsl:sort and xsl:fallback instructions.
It is a static error if the current-group function is used within a pattern.
It is a static error if the current-grouping-key function is used within a pattern.
These five attributes [the group-by, group-adjacent, group-starting-with, group-ending-with, and split-when attributes of xsl:for-each-group ] are mutually exclusive: it is a static error if none of these attributes is present or if more than one of them is present.
It is a static error to specify the collation attribute or the composite attribute if neither the group-by attribute nor group-adjacent attribute is specified.
It is a static error if the xsl:analyze-string instruction contains neither an xsl:matching-substring nor an xsl:non-matching-substring element.
It is a static error if an xsl:key declaration has a use attribute and has non-empty content, or if it has empty content and no use attribute.
It is a static error if the xsl:key declaration has a collation attribute whose value (after resolving against the base URI) is not a URI recognized by the implementation as referring to a collation.
It is a static error if there are several xsl:key declarations in the same package with the same key name and different effective collations. Two collations are the same if their URIs are equal under the rules for comparing xs:anyURI values, or if the implementation can determine that they are different URIs referring to the same collation.
It is a static error if there are several xsl:key declarations in a package with the same key name and different effective values for the composite attribute.
It is a static error if a named or unnamed decimal format contains two conflicting values for the same attribute in different xsl:decimal-format declarations having the same import precedence, unless there is another definition of the same attribute with higher import precedence.
It is a static error if the character specified in the zero-digit attribute is not a digit or is a digit that does not have the numeric value zero.
It is a static error if, for any named or unnamed decimal format, the properties identifying marker characters to be used in a picture string do not identify distinct values. These properties are decimal-separator, grouping-separator, exponent-separator, percent, per-mille, zero-digit, digit, and pattern-separator.
It is a static error if there is no namespace bound to the prefix on the element bearing the [xsl:]extension-element-prefixes attribute or, when #default is specified, if there is no default namespace.
It is a static error if both the [xsl:]type and [xsl:]validation attributes are present on the xsl:element, xsl:attribute, xsl:copy, xsl:copy-of, xsl:document, xsl:result-document, xsl:source-document, or xsl:merge-source elements, or on a literal result element.
It is a static error if the value of the type attribute of an xsl:element, xsl:attribute, xsl:copy, xsl:copy-of, xsl:document, xsl:result-document, xsl:source-document, or xsl:merge-source instruction, or the xsl:type attribute of a literal result element, is not a valid QName, or if it uses a prefix that is not defined in the applicable static namespaces of the containing instruction, or if the QName is not the name of a type definition included in the in-scope schema components for the package. [XSLT 3.0 Erratum E20, bug 30234]
It is a static error if the value of the type attribute of an xsl:attribute instruction refers to a complex type definition
It is a static error if two xsl:output declarations within an output definition specify explicit values for the same attribute (other than cdata-section-elements, suppress-indentation, and use-character-maps), with the values of the attributes being not equal, unless there is another xsl:output declaration within the same output definition that has higher import precedence and that specifies an explicit value for the same attribute.
The value [of the method attribute on xsl:output ] must (if present) be a valid EQName. If it is a lexical QName in no namespace, then it identifies a method specified in [XSLT and XQuery Serialization] and must be one of xml, html, xhtml, text, json, or adaptive.
It is a static error if a package contains two or more character maps with the same name and the same import precedence, unless it also contains another character map with the same name and higher import precedence.
It is a static error if a name in the use-character-maps attribute of the xsl:output or xsl:character-map elements does not match the name attribute of any xsl:character-map in the containing package.
It is a static error if a character map references itself, directly or indirectly, via a name in the use-character-maps attribute.
A non-schema-aware processormust raise a static error if a package includes an xsl:import-schema declaration.
A non-schema-aware processormust raise a static error if a package includes an [xsl:]type attribute; or an [xsl:]validation or [xsl:]default-validation attribute with a value other than strip, preserve, or lax; or an xsl:mode element whose typed attribute is equal to yes or strict; or an as attribute whose value is a SequenceType that can only match nodes with a type annotation other than xs:untyped or xs:untypedAtomic (for example, as="element(*, xs:integer)").
It is a static error if the number of xsl:merge-key children of a xsl:merge-source element is not equal to the number of xsl:merge-key children of another xsl:merge-source child of the same xsl:merge instruction.
It is a static error if after evaluating each xsl:package-location declaration and implementation-defined package location, no priority package location is found.
It is a static error if the package manifest returned by the priority package location does not conform to the rules of the implicit or explicit value of attribute format.
It is a static error if the package manifest returned by the priority package location does not conform to the name and version specified in an xsl:use-package declaration.
It is a static error if the attribute archive-type is present without the attribute path-in-archive, or if it does not have the value zip or an implementation-defined value.
It is a static error if a package is dependent on itself, where package A is defined as being dependent on package B if A contains an xsl:use-package declaration that references B, or if A contains an xsl:use-package declaration that references a package C that is itself dependent on B.
It is a static error if an xsl:use-package declaration appears in a stylesheet module that is not in the same stylesheet level as the principal stylesheet module of the package.
It is a static error if the explicit exposed visibility of a component is inconsistent with its declared visibility, as defined in the above table. (This error occurs only when the component declaration has an explicit visibility attribute, and the component is also listed explicitly by name in an xsl:expose declaration.)
It is a static error if a token in the names attribute of xsl:expose, other than a wildcard, matches no component in the containing package.
It is a static error if the component attribute of xsl:expose specifies * (meaning all component kinds) and the names attribute is not a wildcard.
It is a static error if the effect of an xsl:expose declaration would be to make a component abstract, unless the component is already abstract in the absence of the xsl:expose declaration.
It is a static error if a token in the names attribute of xsl:accept, other than a wildcard, matches no component in the used package.
It is a static error if the component attribute of xsl:accept specifies * (meaning all component kinds) and the names attribute is not a wildcard.
It is a static error if the visibility assigned to a component by an xsl:accept element is incompatible with the visibility of the corresponding component in the used package, as defined by the above table, unless the token that matches the component name is a wildcard, in which case the xsl:accept element is treated as not matching that component.
It is a static error if the xsl:use-package elements in a package manifest cause two or more homonymous components to be accepted with a visibility other than hidden.
It is a static error if a token in the names attribute of xsl:accept, other than a wildcard, matches the symbolic name of a component declared within an xsl:override child of the same xsl:use-package element.
It is a static error if a component declaration appearing as a child of xsl:override is homonymous with any other declaration in the using package, regardless of import precedence, including any other overriding declaration in the package manifest of the using package.
It is a static error if a component declaration appearing as a child of xsl:override does not match (is not homonymous with) some component in the used package.
It is a static error if the component referenced by an xsl:override declaration has visibility other than public or abstract
It is a static error if the signature of an overriding component is not compatible with the signature of the component that it is overriding.
It is a static error to use the component reference xsl:original when the overridden component has visibility="abstract".
It is a static error if a top-level package (as distinct from a library package) contains components whose visibility is abstract.
It is a static error, when the effective value of the declared-modes attribute of an xsl:package element is yes, if the package contains an explicit reference to an undeclared mode, or if it implicitly uses the unnamed mode and the unnamed mode is undeclared.
It is a static error if more than one xsl:global-context-item declaration appears within a stylesheet module, or if several modules within a single package contain inconsistent xsl:global-context-item declarations
It is a static error if the as attribute is present [on the xsl:context-item element] when use="absent" is specified.
It is a static error if the as attribute is present [on the xsl:global-context-item element] when use="absent" is specified.
It is a static error if a template rule applicable to a mode that is defined with typed="strict" uses a match pattern that contains a RelativePathExprP whose first StepExprP is an AxisStepP whose ForwardStepP uses an axis whose principal node kind is Element and whose NodeTest is an EQName that does not correspond to the name of any global element declaration in the in-scope schema components.
It is a static error if an xsl:break or xsl:next-iteration element appears other than in a tail position within the sequence constructor forming the body of an xsl:iterate instruction.
It is a static error if the select attribute of xsl:break or xsl:on-completion is present and the instruction has children.
It is a static error if the name attribute of an xsl:with-param child of an xsl:next-iteration element does not match the name attribute of an xsl:param child of the innermost containing xsl:iterate instruction.
It is a static error if the select attribute of the xsl:try element is present and the element has children other than xsl:catch and xsl:fallback elements.
It is a static error if the select attribute of the xsl:catch element is present unless the element has empty content.
For the elements xsl:sequence, xsl:on-empty, xsl:on-non-empty, xsl:when, xsl:otherwise, xsl:matching-substring, xsl:non-matching-substring, xsl:map, xsl:map-entry, xsl:array, xsl:array-member, and xsl:result-document, it is a static error if the select attribute is present and the instruction has children other than xsl:fallback.
It is a static error if two sibling xsl:merge-source elements have the same name.
If the for-each-item attribute is present then the for-each-source, use-accumulators, and streamable attributes must all be absent. If either or both of the use-accumulators or streamable attributes is present then the for-each-source attribute must be present. If the for-each-source attribute is present then the for-each-item attribute must be absent. [XSLT 3.0 Erratum E40, bugs 30265 and 30378].
It is a static error if an xsl:merge-key element with a select attribute has non-empty content.
It is a static error if the list of accumulator names [in the use-accumulators attribute] contains an invalid token, contains the same token more than once, or contains the token #all along with any other value; or if any token (other than #all) is not the name of a declared-streamable accumulator visible in the containing package.
It is a static error for a package to contain two or more accumulators with the same expanded QName and the same import precedence, unless there is another accumulator with the same expanded QName, and a higher import precedence.
It is a static error for a an xsl:accumulator-rule element to specify capture="yes" unless it also specifies phase="end".
It is a static error if a package contains a construct that is declared to be streamable but which is not guaranteed-streamable, unless the user has indicated that the processor is to handle this situation by processing the stylesheet without streaming or by making use of processor extensions to the streamability rules where available.
In the case of a template rule (that is, an xsl:template element having a match attribute) appearing as a child of xsl:override, it is a static error if the list of modes in the mode attribute contains #all or #unnamed, or if it contains #default and the default mode is the unnamed mode, or if the mode attribute is omitted when the default mode is the unnamed mode.
It is a static error if a variable declared with static="yes" is inconsistent with another static variable of the same name that is declared earlier in stylesheet tree order and that has lower import precedence.
It is a static error if an xsl:apply-imports element appears in a template rule declared within an xsl:override element. (To invoke the template rule that is being overridden, xsl:next-match should therefore be used.)
It is a static error if the current-merge-group function is used within a pattern.
It is a static error if the current-merge-key-array or current-merge-key function is used within a pattern.
It is a static error if a parameter to xsl:iterate is implicitly mandatory.
It is a static error if an xsl:mode declaration with one or more xsl:template children has no name attribute.
It is a static error if an xsl:mode declaration has a child xsl:template element with a name attribute, with a mode attribute, or with no match attribute.
It is a static error if an xsl:mode declaration having one or more child xsl:template elements has a default-mode attribute whose value differs from its name attribute, or if any of those child xsl:template elements has a default-mode attribute that differs from the name attribute of the xsl:mode declaration.
It is a static error if a package contains both (a) an xsl:mode declaration having one or more child xsl:template elements, and (b) an xsl:template declaration that is not one of those children but that references that xsl:mode declaration in its mode attribute.
It is a static error if a package contains (a) an xsl:mode declaration having one or more child xsl:template elements, and (b) a second xsl:mode declaration having the same name and the same import precedence.
It is a static error if a package contains two xsl:item-type or xsl:record-type declarations having the same name and the same import precedence, unless there is another definition with the same name and higher import precedence. It is also a static error if the name of the item type uses a reserved namespace, or if it has the same name as a type in the in-scope schema typesXP of the static context.
It is a static error for an item type named N to contain in its as attribute a reference to N, or to an item type that references N directly or indirectly.
It is a static error if a template ruleR has an as attribute S, and the template rule is applicable to a modeM that is declared with an as attribute T, and the sequence type S is not a subtype of the sequence type T as defined by the relationship subtype(S, T) in Section 3.3.1 Subtypes of Sequence TypesXP.
It is a static error if the value of any [xsl:]schema-role in a stylesheet package does not match the value of the role attribute on some xsl:import-schema element in the same package.
It is a static error if the names of the fields in an xsl:record-type declaration are not distinct.
It is a static error if an xsl:field element has a default attribute unless it specifies required="no".
Type errors
It is a type error if the result sequence contains a function item.
It is a type error if the result of evaluating the sequence constructor cannot be coerced to the required type.
It is a type error if an xsl:apply-templates instruction with no select attribute is evaluated when the context item is not a node.
It is a type error if the supplied value of a variable cannot be converted to the required type.
It is a type error if the conversion of the supplied value of a parameter, or of the context item, does not match the required type, after applying any permitted conversions. [XSLT 3.0 Erratum E22, bug 30238].
If the as attribute [of xsl:function ] is specified, then the result evaluated by the sequence constructor (see 5.85.7 Sequence Constructors) is converted to the required type, using the coercion rules. It is a type error if this conversion fails.
It is a type error to use the xsl:copy instruction with no select attribute when the context item is absent.
It is a type error to use the xsl:copy or xsl:copy-of instruction to copy a node that has namespace-sensitive content if the copy-namespaces attribute has the value no and its explicit or implicit validation attribute has the value preserve. It is also a type error if either of these instructions (with validation="preserve") is used to copy an attribute having namespace-sensitive content, unless the parent element is also copied. A node has namespace-sensitive content if its typed value contains an item of type xs:QName or xs:NOTATION or a type derived therefrom. The reason this is an error is because the validity of the content depends on the namespace context being preserved.
It is a type error if the xsl:number instruction is evaluated, with no value or select attribute, when the context item is not a node.
It is a type error if the result of evaluating the select attribute of the xsl:number instruction is anything other than a single node.
It is a type error if the result of evaluating the group-adjacent expression is an empty sequence or a sequence containing more than one item, unless composite="yes" is specified.
If the validation attribute of an xsl:element, xsl:attribute, xsl:copy, xsl:copy-of, or xsl:result-document instruction, or the xsl:validation attribute of a literal result element, has the effective valuestrict, and schema validity assessment concludes that the validity of the element or attribute is invalid or unknown, a type error occurs. As with other type errors, the error may be raised statically if it can be detected statically.
If the validation attribute of an xsl:element, xsl:attribute, xsl:copy, xsl:copy-of, or xsl:result-document instruction, or the xsl:validation attribute of a literal result element, has the effective valuestrict, and there is no matching top-level declaration in the schema, then a type error occurs. As with other type errors, the error may be raised statically if it can be detected statically.
If the validation attribute of an xsl:element, xsl:attribute, xsl:copy, xsl:copy-of, or xsl:result-document instruction, or the xsl:validation attribute of a literal result element, has the effective valuelax, and schema validity assessment concludes that the element or attribute is invalid, a type error occurs. As with other type errors, the error may be raised statically if it can be detected statically.
It is a type error if the value of the type attribute of an xsl:copy or xsl:copy-of instruction refers to a complex type definition and one or more of the items being copied is an attribute node.
It is a type error if an [xsl:]type attribute is defined for a constructed element or attribute, and the outcome of schema validity assessment against that type is that the validity property of that element or attribute information item is other than valid.
A type error occurs if a type or validation attribute is defined (explicitly or implicitly) for an instruction that constructs a new attribute node, if the effect of this is to cause the attribute value to be validated against a type that is derived from, or constructed by list or union from, the primitive types xs:QName or xs:NOTATION.
A type error occurs [when a document node is validated] unless the children of the document node comprise exactly one element node, no text nodes, and zero or more comment and processing instruction nodes, in any order.
It is a type error if, when validating a document node, document-level constraints (such as ID/IDREF constraints) are not satisfied.
It is a type error if some item selected by a particular merge key in one input sequence is not comparable using the XPath le operator with the corresponding item selected by the corresponding sort key in another input sequence.
It is a type error if the xsl:context-item child of xsl:template specifies that a context item is required and none is supplied by the caller, that is, if the context item is absent at the point where xsl:call-template is evaluated.
It is a type error if an xsl:apply-templates instruction in a particular mode selects an element or attribute whose type is xs:untyped or xs:untypedAtomic when the typed attribute of that mode specifies the value yes, strict, or lax.
It is a type error if an xsl:apply-templates instruction in a particular mode selects an element or attribute whose type is anything other than xs:untyped or xs:untypedAtomic when the typed attribute of that mode specifies the value no.
It is a type error if the result of evaluating the expression in the with-params attribute of the xsl:evaluate instruction is anything other than a single map of type map(xs:QName, item()*).
It is a type error if the result of evaluating the namespace-context attribute of the xsl:evaluate instruction is anything other than a single node.
It is a type error if the result of evaluating the select expression [of the xsl:copy element] is a sequence of more than one item.
A type error occurs if the result of the input sequence [of an xsl:map instruction] is not an instance of the required type map(*)*.
A type error is raised if the result of evaluating the select expression or contained sequence constructor of an xsl:array instruction is not an instance of one of the following sequence types: empty-sequence(), xs:anyAtomicType+, node()+, or record(value as item()*, *)+. As with other type errors, the error may be raised statically if it can be detected statically.
Dynamic errors
It is a dynamic error if the effective value of an attribute written using curly brackets, in a position where an attribute value template is permitted, is a value that is not one of the permitted values for that attribute. If the processor is able to detect the error statically (for example, when any XPath expressions within the curly brackets can be evaluated statically), then the processor may optionally raise this as a static error.
It is a dynamic error if the invocation of the stylesheet specifies a template name that does not match the expanded QName of a named template defined in the stylesheet, whose visibility is public or final.
It is a dynamic error if the invocation of the stylesheet specifies a function name and arity that does not match the expanded QName and arity of a named stylesheet function defined in the stylesheet, whose visibility is public or final.
It is a dynamic error if the invocation of the stylesheet specifies an initial mode when no initial match selection is supplied (either explicitly, or defaulted to the global context item).
It is a dynamic error if the invocation of the stylesheet specifies an initial mode and the specified mode is not eligible as an initial mode (as defined above).
It is a dynamic error if a stylesheet declares a visible stylesheet parameter that is explicitly or implicitly mandatory, and no value for this parameter is supplied when the stylesheet is primed. A stylesheet parameter is visible if it is not masked by another global variable or parameter with the same name and higher import precedence. If the parameter is a static parameter then the value must be supplied prior to the static analysis phase.
It is a dynamic error if an element has an effective version of V (with V < 4.0) when the implementation does not support backwards compatible behavior for XSLT version V.
Where the result of evaluating an XPath expression (or an attribute value template) is required to be a lexical QName, or if it is permitted to be a lexical QName and the actual value takes the form of a lexical QName, then unless otherwise specified it is a dynamic error if the value has a prefix and the defining element has no namespace node whose name matches that prefix. This error may be raised as a static error if the value of the expression can be determined statically.
It is a dynamic error if the sequence used to construct the content of an element node contains a namespace node or attribute node that is preceded in the sequence by a node that is neither a namespace node nor an attribute node.
It is a dynamic error if the sequence used to construct the content of a document node contains a namespace node or attribute node.
It is a dynamic error if the sequence contains two or more namespace nodes having the same name but different string values (that is, namespace nodes that map the same prefix to different namespace URIs).
It is a dynamic error if the sequence contains a namespace node with no name and the element node being constructed has a null namespace URI (that is, it is an error to define a default namespace when the element is in no namespace).
It is a dynamic error if the conflict resolution algorithm for template rules leaves more than one matching template rule when the declaration of the relevant mode has an on-multiple-match attribute with the value fail.
It is a dynamic error if xsl:apply-templates, xsl:apply-imports or xsl:next-match is used to process an item using a mode whose declaration specifies on-no-match="fail" when there is no template rule in the stylesheet whose match pattern matches that item.
It is a dynamic error if xsl:apply-imports or xsl:next-match is evaluated when the current template rule is absent.
It is a dynamic error if a call on the apply-templates function selects a mode that is not explicitly declared in the containing package, or accepted from a used package, or whose visibility is private.
In general, a circularity in a stylesheet is a dynamic error.
It is a dynamic error if a template that has an explicitly mandatory or implicitly mandatory parameter is invoked without supplying a value for that parameter.
It is a dynamic error if the effective value of the name attribute [of the xsl:element instruction] is not a lexical QName.
In the case of an xsl:element instruction with no namespace attribute, it is a dynamic error if the effective value of the name attribute is a lexical QName whose prefix is not declared in the applicable static namespaces for the xsl:element instruction.
It is a dynamic error if the effective value of the namespace attribute [of the xsl:element instruction] is not in the lexical space of the xs:anyURI datatype or if it is the string http://www.w3.org/2000/xmlns/.
It is a dynamic error if the effective value of the name attribute [of an xsl:attribute instruction] is not a lexical QName.
In the case of an xsl:attribute instruction with no namespace attribute, it is a dynamic error if the effective value of the name attribute is the string xmlns.
In the case of an xsl:attribute instruction with no namespace attribute, it is a dynamic error if the effective value of the name attribute is a lexical QName whose prefix is not declared in the applicable static namespaces for the xsl:attribute instruction.
It is a dynamic error if the effective value of the namespace attribute [of the xsl:attribute instruction] is not in the lexical space of the xs:anyURI datatype or if it is the string http://www.w3.org/2000/xmlns/.
It is a dynamic error if the effective value of the name attribute [of the xsl:processing-instruction instruction] is not both an NCNameNames and a PITargetXML.
It is a dynamic error if the string value of the new namespace node is not valid in the lexical space of the datatype xs:anyURI, or if it is the string http://www.w3.org/2000/xmlns/.
It is a dynamic error if the effective value of the name attribute [of the xsl:namespace instruction] is neither a zero-length string nor an NCNameNames, or if it is xmlns.
It is a dynamic error if the xsl:namespace instruction generates a namespace node whose name is xml and whose string value is not http://www.w3.org/XML/1998/namespace, or a namespace node whose string value is http://www.w3.org/XML/1998/namespace and whose name is not xml.
It is a dynamic error if evaluating the select attribute or the contained sequence constructor of an xsl:namespace instruction results in a zero-length string.
It is a dynamic error if any undiscarded item in the atomized sequence supplied as the value of the value attribute of xsl:number cannot be converted to an integer, or if the resulting integer is less than 0 (zero).
It is a dynamic error if, for any sort key component, the set of sort key values evaluated for all the items in the initial sequence, after any type conversion requested, contains a pair of atomic items for which the result of the XPath lt operator is an error. If the processor is able to detect the error statically, it may optionally raise it as a static error.
It is a dynamic error if the collation attribute of xsl:sort (after resolving against the base URI) is not a URI that is recognized by the implementation as referring to a collation.
It is a dynamic error if the current-group function is used when the current group is absent , or when it is invoked in the course of evaluating a pattern. The error may be reported statically if it can be detected statically.
It is a dynamic error if the current-grouping-key function is used when the current grouping key is absent, or when it is invoked in the course of evaluating a pattern. The error may be reported statically if it can be detected statically.
It is a dynamic error if the collation URI specified to xsl:for-each-group (after resolving against the base URI) is a collation that is not recognized by the implementation. (For notes, [see ERR XTDE1035].)
It is a dynamic error if the effective value of the regex attribute [of the xsl:analyze-string instruction] does not conform to the required syntax for regular expressions, as specified in [Functions and Operators 4.0]. If the regular expression is known statically (for example, if the attribute does not contain any expressions enclosed in curly brackets) then the processor may raise the error as a static error.
It is a dynamic error if the effective value of the flags attribute [of the xsl:analyze-string instruction] has a value other than the values defined in [Functions and Operators 4.0]. If the value of the attribute is known statically (for example, if the attribute does not contain any expressions enclosed in curly brackets) then the processor may raise the error as a static error.
When a URI reference [supplied to the document function] contains a fragment identifier, it is a dynamic error if the media type is not one that is recognized by the processor, or if the fragment identifier does not conform to the rules for fragment identifiers for that media type, or if the fragment identifier selects something other than a sequence of nodes (for example, if it selects a range of characters within a text node).
When a URI reference [supplied to the document function] is a relative reference, it is a dynamic error if no base URI is available to resolve the relative reference. This can arise for example when the URI is contained in a node that has no base URI (for example a parentless text node), or when the second argument to the function is a node that has no base URI, or when the base URI from the static context is undefined.
It is a dynamic error if the value of $key-name is not a valid QName, or if there is no namespace declaration in scope for the prefix of the QName, or if the name obtained by expanding the QName is not the same as the expanded name of any xsl:key declaration in the containing package. If the processor is able to detect the error statically (for example, when the argument is supplied as a string literal), then the processor may optionally raise this as a static error.
It is a dynamic error if the key identified in a call to the function map-for-key is unsuitable because it uses a collation other than the Unicode Codepoint Collation, or because it is defined with composite=yes.
It is a dynamic error to call the key function with two arguments if there is no context node, or if the root of the tree containing the context node is not a document node; or to call the function with three arguments if the root of the tree containing the node supplied in the third argument is not a document node.
If the current function is evaluated within an expression that is evaluated when the context item is absent, a dynamic error occurs.
It is a dynamic error if $node, or the context item if the second argument is omitted, is a node in a tree whose root is not a document node.
It is a dynamic error if $node, or the context item if the second argument is omitted, is a node in a tree whose root is not a document node.
It is a dynamic error if the value supplied as the $property-name argument [to the system-property function] is not a valid QName, or if there is no namespace declaration in scope for the prefix of the QName. If the processor is able to detect the error statically (for example, when the argument is supplied as a string literal), then the processor may optionally raise this as a static error.
It is a dynamic error if the $name argument [passed to the function-available function] evaluates to a string that is not a valid EQName, or if the value is a lexical QName with a prefix for which no namespace declaration is present in the static context. If the processor is able to detect the error statically (for example, when the argument is supplied as a string literal), then the processor may optionally raise this as a static error.
It is a dynamic error if the arguments supplied to a call on an extension function do not satisfy the rules defined for that particular extension function, or if the extension function raises an error, or if the result of the extension function cannot be converted to an XPath value.
When the containing element is processed with XSLT 1.0 behavior, it is a dynamic error to evaluate an extension function call if no implementation of the extension function is available.
It is a dynamic error if the argument [passed to the type-available function] evaluates to a string that is not a valid EQName, or if the value is a lexical QName with a prefix for which no namespace declaration is present in the static context. If the processor is able to detect the error statically (for example, when the argument is supplied as a string literal), then the processor may optionally raise this as a static error.
It is a dynamic error if the argument [passed to the element-available function] evaluates to a string that is not a valid EQName, or if the value is a lexical QName with a prefix for which no namespace declaration is present in the static context. If the processor is able to detect the error statically (for example, when the argument is supplied as a string literal), then the processor may optionally raise this as a static error.
When a processor performs fallback for an extension instruction that is not recognized, if the instruction element has one or more xsl:fallback children, then the content of each of the xsl:fallback children must be evaluated; it is a dynamic error if it has no xsl:fallback children.
It is a dynamic error if the effective value of the format attribute [of an xsl:result-document element] is not a valid EQName, or if it does not match the expanded QName of an output definition in the containing package. If the processor is able to detect the error statically (for example, when the format attribute contains no curly brackets), then the processor may optionally raise this as a static error.
It is a dynamic error to evaluate the xsl:result-document instruction in temporary output state.
It is a dynamic error for a transformation to generate two or more final result trees with the same URI.
It is a dynamic error for a stylesheet to write to an external resource and read from the same resource during a single transformation, if the same absolute URI is used to access the resource in both cases.
A dynamic errormay be raised if the input to the processor includes an item that requires availability of an optional feature that the processor does not provide.
It is a dynamic error if there are two xsl:merge-key elements that occupy corresponding positions among the xsl:merge-key children of two different xsl:merge-source elements and that have differing effective values for any of the attributes lang, order, collation, case-order, or data-type. Values are considered to differ if they have different effective values. In the case of the collation attribute, the values are compared as absolute URIs after resolving against the base URI. The error may be raised statically if it is detected statically.
It is a dynamic error if any input sequence to an xsl:merge instruction contains two items that are not correctly sorted according to the merge key values defined on the xsl:merge-key children of the corresponding xsl:merge-source element, when compared using the collation rules defined by the attributes of the corresponding xsl:merge-key children of the xsl:merge instruction, unless the attribute sort-before-merge is present with the value yes.
It is a dynamic error if an invocation of an abstract component is evaluated.
It is a dynamic error if an xsl:global-context-item declaration specifies use="required", and no global context item is supplied. [XSLT 3.0 Erratum E6, bug 30173].
It is a static error if an xsl:function element with no xsl:param children has a streamability attribute with any value other than unclassified.
It is a dynamic error if the target expression [of an xsl:evaluate instruction] is not a valid expression (that is, if a static error occurs when analyzing the string according to the rules of the XPath specification).
It is a dynamic error if an xsl:evaluate instruction is evaluated when use of xsl:evaluate has been statically or dynamically disabled.
It is a dynamic error if the value of the first argument to the accumulator-before or accumulator-after function is a string that is not a valid EQName, or if there is no namespace declaration in scope for the prefix of the QName, or if the name obtained by expanding the QName is not the same as the expanded name of any xsl:accumulator declaration appearing in the package in which the function call appears. If the processor is able to detect the error statically (for example, when the argument is supplied as a string literal), then the processor may optionally raise this as a static error.
It is a dynamic error to call the accumulator-before or accumulator-after function when there is no context item.
It is a type error to call the accumulator-before or accumulator-after function when the context item is not a node, or when it is an attribute or namespace node.
It is a dynamic error to call the accumulator-before or accumulator-after function when the context item is a node in a tree to which the selected accumulator is not applicable (including the case where it is not applicable because the document is streamed and the accumulator is not declared with streamable="yes"). Implementations may raise this error but are not required to do so, if they are capable of streaming documents without imposing this restriction.
In the absence of the [xsl:]duplicates attribute, a dynamic error occurs if the set of keys in the maps making up the input sequence [of an xsl:map or xsl:record instruction] contains duplicates.
It is an error if there is a cyclic set of dependencies among accumulators such that the (pre- or post-descent) value of an accumulator depends directly or indirectly on itself. A processor may report this as a static error if it can be detected statically. Alternatively a processor may report this as a dynamic error. As a further option, a processor may fail catastrophically when this error occurs.
It is a dynamic error if the current-merge-group function is used when the current merge group is absent. The error may be reported statically if it can be detected statically.
It is a dynamic error if the $source argument of the current-merge-group function (when supplied) does not match the name attribute of any xsl:merge-source element for the current merge operation. The error may be reported statically if it can be detected statically.
It is a dynamic error if the current-merge-key-array or current-merge-key function is used when the current merge key is absent, or when it is invoked in the course of evaluating a pattern. The error may be reported statically if it can be detected statically.
It is a dynamic error if an xsl:try instruction is unable to recover the state of a final result tree because recovery has been disabled by use of the attribute rollback-output="no".
When a transformation is terminated by use of <xsl:message terminate="yes"/>, the effect is the same as when a dynamic error occurs during the transformation. The default error code is XTMM9000; this may be overridden using the error-code attribute of the xsl:message instruction.
When a transformation is terminated by use of xsl:assert, the effect is the same as when a dynamic error occurs during the transformation. The default error code is XTMM9001; this may be overridden using the error-code attribute of the xsl:assert instruction.
This appendix provides a summary of XSLT language features whose effect is explicitly implementation-defined. The conformance rules (see 27 Conformance) require vendors to provide documentation that explains how these choices have been exercised.
The implementation-defined features are grouped into categories for convenience.
This category covers interfaces for initiating a transformation, setting its parameters, initializing the static and dynamic context, and collecting the results. In general terms, it is implementation defined how input is passed to the processor and how it returns its output. This includes the interpretation of URIs used to refer to stylesheet packages and modules, source documents and collections, collations, and result documents.
More specifically:
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. (See 2.3.2 Priming a Stylesheet)
The way in which an XSLT processor is invoked, and the way in which values are supplied for the source document, starting node, stylesheet parameters, and base output URI, are implementation-defined. (See 2.3.2 Priming a Stylesheet)
The way in which a base output URI is established is implementation-defined (See 2.3.6.2 Serializing the Result)
In the absence of an [xsl:]default-collation attribute, the default collation may be set by the calling application in an implementation-defined way. (See 3.7.2 The default-collation Attribute)
It is implementation-defined what forms of URI reference are acceptable in the href attribute of the xsl:include and xsl:import elements, for example, the URI schemes that may be used, the forms of fragment identifier that may be used, and the media types that are supported. The way in which the URI reference is used to locate a representation of a stylesheet module, and the way in which the stylesheet module is constructed from that representation, are also implementation-defined. (See 3.11.1 Locating Stylesheet Modules)
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. The manner in which such user options are provided, if at all, is implementation-defined. (See 5.3.3 Initializing the Dynamic Context)
Streamed processing may be initiated by invoking the transformation with an initial mode declared as streamable, while supplying the initial match selection (in an implementation-defined way) as a streamed document. (See 6.7.76.8.7 Streamable Templates)
The mechanism by which the caller supplies a value for a stylesheet parameter is implementation-defined. (See 9.5 Global Variables and Parameters)
The detail of any external mechanism allowing a processor to enable or disable checking of assertions is implementation-defined. (See 23.2 Assertions)
The way in which the results of the transformation are delivered to an application is implementation-defined. (See 25 Transformation Results)
It is implementation-defined how the URI appearing in the href attribute of xsl:result-document affects the way in which the result tree is delivered to the application. There may be restrictions on the form of this URI. (See 25.1 Creating Secondary Results)
If serialization is supported, then the location to which a final result tree is serialized is implementation-defined, subject to the constraint that relative URI references used to reference one tree from another remain valid. (See 26.2 Serialization parameters)
Some aspects of error handling are implementation-defined:
It is implementation-defined whether type errors are raised statically. (See 2.14 Error Handling)
If the effective version of any element in the stylesheet is not 1.0 or 2.0 but is 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. (See 3.9 Backwards Compatible Processing)
The default values for the warning-on-no-match and warning-on-multiple-match attributes of xsl:mode are implementation-defined. (See 6.7.16.8.1 Declaring Modes)
The form of any warnings output when there is no matching template rule, or when there are multiple matching template rules, is implementation-defined. (See 6.7.16.8.1 Declaring Modes)
The destination and formatting of messages written using the xsl:message instruction are implementation-defined. (See 23.1 Messages)
This appendix acts as an index of functions defined in this specification, to augment the set of functions defined in [Functions and Operators 4.0].
accumulator-afteraccumulator-beforeapply-templatesavailable-system-propertiescharacter-mapcopy-ofcurrentcurrent-groupcurrent-grouping-keycurrent-merge-groupcurrent-merge-keycurrent-merge-key-arraycurrent-output-uridocumentelement-availablefunction-availablekeymap-for-keyregex-groupsnapshotstream-availablesystem-propertytype-availableunparsed-entity-public-idunparsed-entity-uriUse the arrows to browse significant changes since the 3.0 version of this specification.
Sections with significant changes are marked Δ in the table of contents.
Named item types can be declared using the new xsl:item-type element. This is designed to avoid repeating lengthy type definitions (for example function types) every time they are used. [This feature was present in the editor's draft presented to the WG when it started work.]
The xsl:for-each and xsl:apply-templates instructions acquire an attribute separator that can be used to insert content between adjacent items. [This change was in the editor's draft adopted as a baseline when the WG commenced work.]
PR 751 1386
The result type of a mode can be declared using an as attribute. The result type of all template rules in this mode must be consistent with this, as must the values returned by any built-in template rules for the mode.
The xsl:for-each and xsl:apply-templates instructions acquire an attribute separator that can be used to insert content between adjacent items. [This change was in the editor's draft adopted as a baseline when the WG commenced work.]
Numeric values of type xs:decimal are compared as decimals, without first converting to xs:double.
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.]
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.]
It is possible to invoke a named template using an extension instruction, specifically, an element whose name matches the name of the named template.
See 10.1.3 Invoking Named Templates using Extension Instructions
A new attribute xsl:map/@duplicates is available, allowing control over how duplicate keys are handled by the xsl:map instruction.
The semantics of patterns using the intersect and except operators have been changed to reflect the intuitive meaning: for example a node now matches A except B if it matches A and does not match B.
A new attribute xsl:for-each-group/@split-when is available to give applications more complete control over how a sequence is partitioned
See 14 Grouping
Duplicate xsl:include declarations within a stylesheet level are now ignored, preventing spurious errors caused by the presence of duplicate named components.
Named record types are introduced.
The contents of a character map declared using xsl:character-map are now available dynamically via a new character-map function.
New variables err:stack-trace, err:additional, and err:map are available within an xsl:catch clause.
See 8.4 Try/Catch
The input to the serializer can be defined using the select attribute of xsl:result-document as an alternative to using a sequence constructor.
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.
The default value for the indent parameter is now defined to be no for all output methods other than html and xhtml.
The xsl:map instruction allows a select attribute as an alternative to the contained sequence constructor.
The xsl:map-entry instruction, in common with other instructions, now raises error XTSE3185 (rather than XTSE3280) if both a select attribute and a sequence constructor are present.
Composite sort keys are allowed in xsl:sort.
The xsl:mode declaration acquires an attribute copy-namespaces which determines whether or not the built-in template rule copies unused namespace bindings.
The default priority for a template rule using a union pattern has changed. This change may cause incompatible behavior.
The xsl:apply-imports and xsl:next-match instructions automatically pass supplied parameters to the overridden template rule.
The special rule allowing xsl:map to have multiple consumable operands does not apply if duplicate keys are permitted.
PR 159
Parameters on functions declared using xsl:function can now be defined as optional, with a default value supplied.
PR 237
The xsl:if instruction now allows then and else attributes.
See 8.1 Conditional Processing with xsl:if
In xsl:choose, the xsl:when and xsl:otherwise elements can take a select attribute in place of a sequence constructor.
See 8.2 Conditional Processing with xsl:choose
A new xsl:switch instruction is introduced.
PR 326
The higher-order-function feature no longer exists; higher-order functions are now a core part of XSLT, no longer an optional extra.
See 27 Conformance
PR 353
A new attribute, main-module, is added to the xsl:stylesheet element. The attribute is provided for the benefit of development tools such as syntax-directed editors to provide information about all the components (variables, functions, etc) visible within a stylesheet module.
A new element xsl:note is available for documentation and similar purposes: it can appear anywhere in the stylesheet and is ignored by the XSLT processor.
PR 401
Patterns (especially those used in template rules) can now be defined by reference to item types, so any item type can be used as a match pattern. For example match="record(longitude, latitude, *)" matches any map that includes the key values "longitude" and "latitude".
PR 406
The new instruction xsl:array is introduced to allow construction of arrays.
PR 470
The xsl:stylesheet, xsl:transform, or xsl:package element may have a fixed-namespaces attribute making it easier to have the same namespace declarations in force throughout a stylesheet.
PR 489
The xsl:matching-substring and xsl:non-matching-substring elements within xsl:analyze-string may now take a select attribute in place of a contained sequence constructor.
PR 534
A new serialization parameter escape-solidus is provided to control whether the character / is escaped as \/ by the JSON serialization method.
PR 542
A mode (called an enclosing mode) can be defined in which all the relevant template rules are children of the xsl:mode element. This is intended to allow a stylesheet design in which it is easier to determine which rules might apply to a given xsl:apply-templates call.
PR 599
Simplified stylesheets no longer require an xsl:version attribute (which means they might not need a declaration of the XSLT namespace). Unless otherwise specified, a 4.0 simplified stylesheet defaults expand-text to true.
PR 635
The rules concerning the compatibility of schemas imported by different packages have been clarified. It is now explicitly stated that instructions that trigger validation must use the imported schema of the package in which validation is invoked. This differs from the current practice of some XSLT 3.0 processors, which may use (for example) a schema formed from the union of the imported schemas in all packages.
See 3.15 Importing Schema Components
See 25.4 Validation
PR 717
Capturing accumulators have been added; when streaming with a capturing accumulator, the accumulator-after has full access to a snapshot of the matched element node.
PR 718
To allow recursive-descent transformation on a tree of maps and arrays, a new set of built-in templates rules shallow-copy-all is introduced.
PR 751
The xsl:mode declaration acquires an attribute as="sequence-type" which declares the return type of all template rules in that mode.
PR 1181
The [xsl:]xpath-default-namespace attribute can be set to the value ##any, which causes unprefixed element names to match in any namespace or none.
See 5.1.2 Unprefixed Lexical QNames in Expressions and Patterns
PR 1250
The strings used in the formatted number to represent a decimal separator, grouping separator, exponent separator, percent sign, per mille sign, or minus sign, are no longer constrained to be single characters.
PR 1254
The rules concerning the interpretation of xsi:schemaLocation and xsi:noNamespaceSchemaLocation attributes have been tightened up.
See 25.4 Validation
See 25.4 Validation
PR 1306
An as attribute is available on the xsl:sequence instruction.
PR 1361
The term atomic value has been replaced by atomic item.
See 2.1 Terminology
PR 1378
A function call at the outermost level can now be named using any valid EQName (for example fn:doc) provided it binds to one of the permitted functions fn:doc, fn:id, fn:element-with-id, fn:key, or fn:root. If two functions are called, for example doc('a.xml')/id('abc'), it is no longer necessary to put the second call in parentheses.
PR 1442
Default priorities are added for new forms of ElementTest and AttributeTest, for example element(p:*) and element(a|b).
PR 1622
The rules for equality comparison have changed to bring keys into line with maps.
See 20.2.2 fn:key
New in 4.0.
PR 1689
Composite merge keys are now allowed.
See 15 Merging
PR 1703
Ordered maps are introduced.
PR 1819
Different parts of a stylesheet may now use different imported schemas.
See 2.10 Stylesheets and XML Schemas
The standard attribute [xsl:]schema-role is introduced, to allow different parts of a stylesheet to use different schemas.
Different parts of a stylesheet may now use different imported schemas.
See 3.15 Importing Schema Components
A stylesheet can import multiple schemas with different schema role names.
PR 1856
The rules have been adjusted to allow for new capabilities in regular expressions, such as zero-width assertions.
PR 1858
The xsl:record instruction is introduced to make construction of record maps simpler.
Attribute xsl:record/@xsl:duplicates is added to control duplicate keys handling in the xsl:record instruction.
PR 2006
A new function fn:apply-templates is introduced.
PR 2008
The xsl:select instruction is new in 4.0.
PR 2011
The static typing rules have been updated to take account of new constructs in XPath 4.0.
PR 2015
A variable-binding with no as or select attribute no longer attempts to create an implicit document node if the sequence constructor contains an xsl:map, xsl:array, or xsl:select child instruction.
PR 2030
In order to reduce duplication between the XSLT and XQuery specifications, description of the validation process has been moved to the Functions and Operators specification.
See 25.4 Validation