W3C

XSL Transformations (XSLT) Version 2.1

W3C Working Draft 11 May 2010

This version:
http://www.w3.org/TR/2010/WD-xslt-21-20100511/
Latest version:
http://www.w3.org/TR/xslt-21/
Editor:
Michael Kay, Saxonica <http://www.saxonica.com/>

Please refer to the errata for this document, which may include some normative corrections.

See also translations.


Abstract

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

XSLT 2.1 is a revised version of the XSLT 2.0 Recommendation [XSLT 2.0] published on 23 January 2007.

The primary purpose of the changes in this version of the language is to enable transformations to be performed in streaming mode, where neither the source document nor the result document is ever held in memory in its entirety.

XSLT 2.1 is designed to be used in conjunction with XPath 2.1, which is defined in [XPath 2.1]. XSLT shares the same data model as XPath 2.1, which is defined in [Data Model], and it uses the library of functions and operators defined in [Functions and Operators]. XPath 2.1 and the underlying function library introduce a number of enhancements, for example the availability of higher-order functions. Some of the functions that were previously defined in the XSLT 2.0 specification, such as the format-date and format-number functions, are now defined in the standard function library to make them available to other host languages.

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

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, DM for the XDM data model, FO for Functions and Operators.

Status of this Document

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

This is a First Public Working Draft as described in the http://www.w3.org/2005/10/Process-20051014/tr.html process document. It has been developed by the W3C XSL Working Group, which is part of the XML Activity. The Working Group expects to advance this specification to Recommendation Status.

This specification has been developed in conjunction with [XPath 2.1] and other documents that underpin both XSLT and XQuery. Although the development of this family of documents is coordinated, it has not been possible on this occasion to publish them simultaneously, and there may therefore be imperfect technical alignment between them. This will be corrected in later drafts.

There are many open issues in this draft, as well as uncompleted editorial work; known instances are flagged in the form of editorial notes. Where these relate to technical issues, feedback from readers will be especially welcome.

Please report errors in this document using W3C's public Bugzilla system (instructions can be found at http://www.w3.org/XML/2005/04/qt-bugzilla). If access to that system is not feasible, you may send your comments to the W3C XSLT/XPath/XQuery public comments mailing list, public-qt-comments@w3.org. It will be very helpful if you include the string "[XSLT21]" in the subject line of your report, whether made in Bugzilla or in email. Please use multiple Bugzilla entries (or, if necessary, multiple email messages) if you have more than one comment to make. Archives of the comments and responses are available at http://lists.w3.org/Archives/Public/public-qt-comments/.

Publication as a Working Draft does not imply endorsement by the W3C Membership. This is a draft document and may be updated, replaced or obsoleted by other documents at any time. It is inappropriate to cite this document as other than work in progress.

This document was produced by a group operating under the 5 February 2004 W3C Patent Policy. W3C maintains a public list of any patent disclosures made in connection with the deliverables of the XSL Working Group; those pages also include instructions for disclosing a patent. An individual who has actual knowledge of a patent which the individual believes contains Essential Claim(s) must disclose the information in accordance with section 6 of the W3C Patent Policy.

For a list of changes, see J Changes since XSLT 2.0.

Table of Contents

1 Introduction
    1.1 What is XSLT?
    1.2 What's New in XSLT 2.1?
2 Concepts
    2.1 Terminology
    2.2 Notation
    2.3 Initiating a Transformation
    2.4 Executing a Transformation
    2.5 The Evaluation Context
    2.6 Parsing and Serialization
    2.7 Extensibility
    2.8 Stylesheets and XML Schemas
    2.9 Streaming
    2.10 Error Handling
3 Stylesheet Structure
    3.1 XSLT Namespace
    3.2 Reserved Namespaces
    3.3 Extension Attributes
    3.4 XSLT Media Type
    3.5 Standard Attributes
    3.6 Stylesheet Element
        3.6.1 The default-collation attribute
        3.6.2 The default-mode attribute
        3.6.3 User-defined Data Elements
    3.7 Simplified Stylesheet Modules
    3.8 Backwards Compatible Processing
        3.8.1 XSLT 1.0 compatibility mode
        3.8.2 XSLT 2.0 compatibility mode
    3.9 Forwards Compatible Processing
    3.10 Combining Stylesheet Modules
        3.10.1 Locating Stylesheet Modules
        3.10.2 Stylesheet Inclusion
        3.10.3 Stylesheet Import
    3.11 Embedded Stylesheet Modules
    3.12 Conditional Element Inclusion
    3.13 Built-in Types
    3.14 Importing Schema Components
4 Data Model
    4.1 XML Versions
    4.2 Stripping Whitespace from the Stylesheet
    4.3 Stripping Type Annotations from a Source Tree
    4.4 Stripping Whitespace from a Source Tree
    4.5 Attribute Types and DTD Validation
    4.6 Data Model for Streaming
    4.7 Limits
    4.8 Disable Output Escaping
5 Features of the XSLT Language
    5.1 Qualified Names
    5.2 Unprefixed QNames in Expressions and Patterns
    5.3 Expressions
    5.4 The Static and Dynamic Context
        5.4.1 Initializing the Static Context
        5.4.2 Additional Static Context Components used by XSLT
        5.4.3 Initializing the Dynamic Context
            5.4.3.1 Maintaining Position: the Focus
            5.4.3.2 Other components of the XPath Dynamic Context
        5.4.4 Additional Dynamic Context Components used by XSLT
    5.5 Patterns
        5.5.1 Examples of Patterns
        5.5.2 Syntax of Patterns
        5.5.3 The Meaning of a Pattern
        5.5.4 Errors in Patterns
    5.6 Attribute Value Templates
    5.7 Sequence Constructors
        5.7.1 Constructing Complex Content
        5.7.2 Constructing Simple Content
        5.7.3 Namespace Fixup
    5.8 URI References
6 Template Rules
    6.1 Defining Templates
    6.2 Defining Template Rules
    6.3 Applying Template Rules
    6.4 Conflict Resolution for Template Rules
    6.5 Default Priority for Template Rules
    6.6 Modes
        6.6.1 Declaring Modes
        6.6.2 Declaring the initial context item for a mode
        6.6.3 Using Modes
    6.7 Built-in Template Rules
        6.7.1 Built-in Templates: stringify
        6.7.2 Built-in Templates: discard
        6.7.3 Built-in Templates: copy
        6.7.4 Built-in Templates: fail
    6.8 Overriding Template Rules
    6.9 Passing Parameters to Template Rules
7 Repetition
    7.1 The xsl:for-each instruction
    7.2 The xsl:iterate instruction
8 Conditional Processing
    8.1 Conditional Processing with xsl:if
    8.2 Conditional Processing with xsl:choose
    8.3 Try/Catch
        8.3.1 Try/Catch Examples
9 Variables and Parameters
    9.1 Variables
    9.2 Parameters
    9.3 Values of Variables and Parameters
    9.4 Creating implicit document nodes
    9.5 Global Variables and Parameters
    9.6 Local Variables and Parameters
    9.7 Scope of Variables
    9.8 Setting Parameter Values
    9.9 Circular Definitions
10 Callable Components
    10.1 Named Templates
        10.1.1 Passing Parameters to Named Templates
        10.1.2 Tunnel Parameters
    10.2 Named Attribute Sets
    10.3 Stylesheet Functions
    10.4 Dynamic XPath Evaluation
11 Creating Nodes and Sequences
    11.1 Literal Result Elements
        11.1.1 Setting the Type Annotation for Literal Result Elements
        11.1.2 Attribute Nodes for Literal Result Elements
        11.1.3 Namespace Nodes for Literal Result Elements
        11.1.4 Namespace Aliasing
    11.2 Creating Element Nodes Using xsl:element
        11.2.1 Setting the Type Annotation for a Constructed Element Node
    11.3 Creating Attribute Nodes Using xsl:attribute
        11.3.1 Setting the Type Annotation for a Constructed Attribute Node
    11.4 Creating Text Nodes
        11.4.1 Literal Text Nodes
        11.4.2 Creating Text Nodes Using xsl:text
        11.4.3 Generating Text with xsl:value-of
    11.5 Creating Document Nodes
    11.6 Creating Processing Instructions
    11.7 Creating Namespace Nodes
    11.8 Creating Comments
    11.9 Copying Nodes
        11.9.1 Shallow Copy
        11.9.2 Deep Copy
    11.10 Constructing Sequences
12 Numbering
    12.1 Formatting a Supplied Number
    12.2 Numbering based on Position in a Document
    12.3 Number to String Conversion Attributes
13 Sorting
    13.1 The xsl:sort Element
        13.1.1 The Sorting Process
        13.1.2 Comparing Sort Key Values
        13.1.3 Sorting Using Collations
    13.2 Creating a Sorted Sequence
    13.3 Processing a Sequence in Sorted Order
14 Grouping
    14.1 The Current Group
    14.2 The Current Grouping Key
    14.3 The xsl:for-each-group Element
    14.4 Examples of Grouping
    14.5 Non-Transitivity
15 Merging
    15.1 Terminology for merging
    15.2 The xsl:merge instruction
    15.3 Selecting the sequences to be merged
    15.4 Defining the merge keys
    15.5 The xsl:merge-action element
    15.6 Selective processing of merge inputs
    15.7 Merging streamed input documents
    15.8 Examples of xsl:merge
16 Splitting
    16.1 Introduction
    16.2 The xsl:fork instruction
    16.3 Examples of splitting with streamed data
17 Regular Expressions
    17.1 The xsl:analyze-string instruction
    17.2 Captured Substrings
    17.3 Examples of Regular Expression Matching
18 Streaming
    18.1 The xsl:stream instruction
        18.1.1 Examples of xsl:stream
    18.2 Streamable Templates
    18.3 Streamable patterns
    18.4 Streamability Analysis
        18.4.1 Building an Expression Tree
        18.4.2 Expanding the Expression Tree
            18.4.2.1 Expanding the xsl:number instruction
            18.4.2.2 Expanding the xsl:merge instruction
        18.4.3 Analyzing Navigation
            18.4.3.1 Marking contributing child constructs
            18.4.3.2 Analyzing variable references
            18.4.3.3 Tracing the Context of an Expression
        18.4.4 Analyzing choices, repetition, and calls
            18.4.4.1 Analyzing conditional constructs
            18.4.4.2 Analyzing parallel branches
            18.4.4.3 Analyzing looping constructs
            18.4.4.4 Analyzing sorting constructs
            18.4.4.5 Analyzing dynamic invocation
            18.4.4.6 Analyzing calls to functions, templates, and attribute sets
            18.4.4.7 Analyzing the streamability of xsl:iterate
        18.4.5 Streamability Conditions
        18.4.6 Notes on the streamability of paths using the descendant axis
        18.4.7 Examples of streamability analysis
        18.4.8 Notes on the streamability algorithm
    18.5 The copy-of function
    18.6 The snapshot function
    18.7 The outermost function
    18.8 The innermost function
    18.9 The has-children function
19 Additional Functions
    19.1 Multiple Source Documents
        19.1.1 The document function
        19.1.2 The uri-collection function
    19.2 Reading Text Files
        19.2.1 The unparsed-text function
        19.2.2 The unparsed-text-lines function
        19.2.3 The unparsed-text-available function
    19.3 Keys
        19.3.1 The xsl:key Declaration
        19.3.2 The key Function
    19.4 Defining a Decimal Format
    19.5 Miscellaneous Additional Functions
        19.5.1 current
        19.5.2 unparsed-entity-uri
        19.5.3 unparsed-entity-public-id
        19.5.4 system-property
    19.7 Function items and context-dependency
20 Messages
21 Extensibility and Fallback
    21.1 Extension Functions
        21.1.1 Testing Availability of Functions
        21.1.2 Calling Extension Functions
        21.1.3 External Objects
        21.1.4 Testing Availability of Types
    21.2 Extension Instructions
        21.2.1 Designating an Extension Namespace
        21.2.2 Testing Availability of Instructions
        21.2.3 Fallback
22 Final Result Trees
    22.1 Creating Final Result Trees
    22.2 Validation
        22.2.1 Validating Constructed Elements and Attributes
            22.2.1.1 Validation using the [xsl:]validation Attribute
            22.2.1.2 Validation using the [xsl:]type Attribute
            22.2.1.3 The Validation Process
        22.2.2 Validating Document Nodes
23 Serialization
    23.1 Character Maps
    23.2 Disabling Output Escaping
24 Conformance
    24.1 Basic XSLT Processor
    24.2 Schema-Aware XSLT Processor
    24.3 Serialization Feature
    24.4 Compatibility Features
    24.5 Streaming Feature

Appendices

A References
    A.1 Normative References
    A.2 Other References
B Glossary (Non-Normative)
C Element Syntax Summary (Non-Normative)
D Summary of Error Conditions (Non-Normative)
E Checklist of Implementation-Defined Features (Non-Normative)
F List of XSLT-defined functions (Non-Normative)
G Schema for XSLT Stylesheets (Non-Normative)
H Acknowledgements (Non-Normative)
I Summary of Open Issues (Non-Normative)
J Changes since XSLT 2.0 (Non-Normative)
K Incompatibilities with XSLT 2.0 (Non-Normative)


1 Introduction

1.1 What is XSLT?

This specification defines the syntax and semantics of the XSLT 2.1 language.

[Definition: A transformation in the XSLT language is expressed in the form of a stylesheet, whose syntax is well-formed XML [XML 1.0] conforming to the Namespaces in XML Recommendation [Namespaces in XML].]

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

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

A transformation expressed in XSLT describes rules for transforming zero or more source trees into one or more result trees. The structure of these trees is described in [Data Model]. The transformation is achieved by a set of template rules. A template rule associates a pattern, which matches nodes in the source document, with a sequence constructor. In many cases, evaluating the sequence constructor will cause new nodes to be constructed, which can be used to produce part of a result tree. The structure of the result trees can be completely different from the structure of the source trees. In constructing a result tree, nodes from the source trees can be filtered and reordered, and arbitrary structure can be added. This mechanism allows a stylesheet to be applicable to a wide class of documents that have similar source tree structures.

[Definition: A stylesheet may consist of several stylesheet modules, contained in different XML documents. For a given transformation, one of these functions as the principal stylesheet module. The complete stylesheet is assembled by finding the stylesheet modules referenced directly or indirectly from the principal stylesheet module using xsl:include and xsl:import elements: see 3.10.2 Stylesheet Inclusion and 3.10.3 Stylesheet Import.]

1.2 What's New in XSLT 2.1?

The main focus for enhancements in XSLT 2.1 is the requirement to enable streaming of source documents. This is needed when source documents become too large to hold in main memory, and also for applications where it is important to start delivering results before the entire source document is available.

While implementations of XSLT that use streaming have always been theoretically possible, the nature of the language has made it very difficult to achieve this in practice. The approach adopted in this specification is twofold: it identifies a set of restrictions which, if followed by stylesheet authors, will enable implementations to adopt a streaming mode of operation without placing excessive demands on the optimization capabilities of the processor; and it provides new constructs to indicate that streaming is required, or to express transformations in a way that makes it easier for the processor to adopt a streaming execution plan.

Capabilities provided in this category include:

  • A new xsl:stream instruction, which reads and processes a source document in streaming mode;

  • The ability to declare that a mode is a streaming mode, in which case all the template rules using that mode must be streamable;

  • A new xsl:iterate instruction, which iterates over the items in a sequence, allowing parameters for the processing of one item to be set during the processing of the previous item;

  • A new xsl:merge instruction, allowing multiple input streams to be merged into a single output stream;

  • A new xsl:fork instruction, allowing multiple computations to be performed in parallel during a single pass through an input document.

Other significant features in XSLT 2.1 include:

  • An xsl:evaluate instruction allowing evaluation of XPath expressions that are dynamically constructed as strings, or that are read from a source document;

  • Enhancements to the syntax of patterns, in particular enabling the matching of atomic values as well as nodes;

  • An xsl:try instruction to allow recovery from dynamic errors;

  • The element xsl:context-item, used to declare the stylesheet's expectations of the initial context item (notably, its type), given the initial mode.

XSLT 2.1 also delivers enhancements made to the XPath language and to the standard function library, including the following:

  • Variables can now be bound in XPath using the let expression.

  • Functions are now first class values, and can be passed as arguments to other (higher-order) functions, making XSLT a fully-fledged functional programming language.

  • A number of new functions are available, for example trigonometric functions, and the functions parseFO and serializeFO to convert between lexical and tree representations of XML.

The XSL Working Group is designing other new features which it hopes to include in the final XSLT 2.1 Recommendation, but which are not yet advanced enough to include in this Working Draft.

A full list of changes is at J Changes since XSLT 2.0.

2 Concepts

2.1 Terminology

For a full glossary of terms, see B Glossary.

[Definition: The software responsible for transforming source trees into result trees using an XSLT stylesheet is referred to as the processor. This is sometimes expanded to XSLT processor to avoid any confusion with other processors, for example an XML processor.]

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

[Definition: The term result tree is used to refer to any tree constructed by instructions in the stylesheet. A result tree is either a final result tree or a temporary tree.]

[Definition: A final result tree is a result tree that forms part of the final output of a transformation. Once created, the contents of a final result tree are not accessible within the stylesheet itself.] The xsl:result-document instruction always creates a final result tree, and a final result tree may also be created implicitly by the initial template. The conditions under which this happens are described in 2.4 Executing a Transformation. A final result tree may be serialized as described in 23 Serialization.

[Definition: The term source tree means any tree provided as input to the transformation. This includes the document containing the initial context item if any, documents containing nodes supplied as the values of stylesheet parameters, documents obtained from the results of functions such as document, docFO, and collectionFO, documents read using the xsl:stream instruction, and documents returned by extension functions or extension instructions. In the context of a particular XSLT instruction, the term source tree means any tree provided as input to that instruction; this may be a source tree of the transformation as a whole, or it may be a temporary tree produced during the course of the transformation.]

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

The use of the term "tree" in phrases such as source tree, result tree, and temporary tree is not confined to documents that the processor materializes in memory in their entirety. The processor may, and in some cases must, use streaming techniques to limit the amount of memory used to hold source and result documents. When streaming is used, the nodes of the tree may never all be in memory at the same time, but at an abstract level the information is still modeled as a tree of nodes, and the document is therefore still described as a tree.

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

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

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

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

[Definition: In this specification, the term implementation-defined refers to a feature where the implementation is allowed some flexibility, and where the choices made by the implementation must be described in documentation that accompanies any conformance claim.]

[Definition: The term implementation-dependent refers to a feature where the behavior may vary from one implementation to another, and where the vendor is not expected to provide a full specification of the behavior.] (This might apply, for example, to limits on the size of source documents that can be transformed.)

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

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

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

  • [Definition: The term atomization is defined in Section 2.4.2 AtomizationXP21. It is a process that takes as input a sequence of items, and returns a sequence of atomic values, in which the nodes are replaced by their typed values as defined in [Data Model].] For some items (for example, elements with element-only content, and function items), atomization generates a dynamic error.

  • [Definition: The term typed value is defined in Section 5.15 typed-value AccessorDM11. Every node except an element defined in the schema with element-only content has a typed value. For example, the typed value of an attribute of type xs:IDREFS is a sequence of zero or more xs:IDREF values.]

  • [Definition: The term string value is defined in Section 5.13 string-value AccessorDM11. Every node has a string value. For example, the string value of an element is the concatenation of the string values of all its descendant text nodes.]

  • [Definition: The term XPath 1.0 compatibility mode is defined in Section 2.1.1 Static ContextXP21. 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 2.1 and XPath 1.0.]

[Definition: The term core function means a function that is specified in [Functions and Operators] and that is in the standard function namespace.]

2.2 Notation

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

In this document the specification of each XSLT element is preceded by a summary of its syntax in the form of a model for elements of that element type. A full list of all these specifications can be found in C Element Syntax Summary. The meaning of 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.

    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.

  • 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 similar way 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, other than xsl:import, 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 only affects whether it is allowed in the content of elements that allow a sequence constructor or other-declarations.

Example: Syntax Notation

This example illustrates the notation used to describe XSLT elements.

<!-- Category: instruction -->
<xsl:example-element
  select = expression
  debug? = { "yes" | "no" } >
  <!-- 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 a mandatory select attribute, whose value is an XPath expression, and an optional debug attribute, whose value must be either yes or no; the curly brackets indicate that the value can be defined as an attribute value template, allowing a value such as debug="{$debug}", where the variable debug is evaluated to yield "yes" or "no" at run-time.

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] A static error is signaled 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.

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 non-recoverable 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 signal this as a static error.

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

[Definition: Some constructs defined in this specification are described as being deprecated. The use of this term implies that stylesheet authors should not use the construct, and that the construct may be removed in a later version of this specification.] All constructs that are deprecated in this specification are also (as it happens) optional features that implementations are not required to provide.

Note:

This working draft includes a non-normative XML Schema for XSLT stylesheet modules (see G Schema for XSLT 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]. The signatures of these functions are described using the same notation as used in [Functions and Operators]. The names of these functions are all in the standard function namespace.

2.3 Initiating a Transformation

This document does not specify any application programming interfaces or other interfaces for initiating a transformation. This section, however, describes the information that is supplied when a transformation is initiated. Except where otherwise indicated, the information is required.

Implementations may allow a transformation to run as two or more phases, for example parsing, compilation and execution. Such a distinction is outside the scope of this specification, which treats transformation as a single process controlled using a set of stylesheet modules, supplied in the form of XML documents.

The following information is supplied to execute a transformation:

  • The stylesheet module that is to act as the principal stylesheet module for the transformation. The complete stylesheet is assembled by recursively expanding the xsl:import and xsl:include declarations in the principal stylesheet module, as described in 3.10.2 Stylesheet Inclusion and 3.10.3 Stylesheet Import.

  • A set (possibly empty) of values for stylesheet parameters (see 9.5 Global Variables and Parameters). These values are available for use within expressions in the stylesheet.

  • [Definition: An item that acts as the initial context item for the transformation. This item is accessible within the stylesheet as the initial value of the XPath expressions . (dot) and self::node(), as described in 5.4.3.1 Maintaining Position: the Focus ].

    The value that can be supplied as the initial context item is constrained by the xsl:context-item element, if defined for the chosen initial mode.

    If no initial context item is supplied, then the context item, context position, and context size will initially be undefined, and the evaluation of any expression that references these values will result in a dynamic error. (Note that the initial context size and context position will always be 1 (one) when an initial context item is supplied, and will be undefined if no initial context item is supplied).

  • Optionally, the name of a named template which is to be executed as the entry point to the transformation. This template must exist within the stylesheet. If no named template is supplied, then the transformation starts with the template rule that best matches the initial context item, according to the rules defined in 6.4 Conflict Resolution for Template Rules. Either a named template, or an initial context item, or both, must be supplied.

  • Optionally, an initial mode.

    [Definition: The initial mode, if specified, must either be the default mode, or a mode that is explicitly named in the mode attribute of an xsl:template declaration within the stylesheet. If an initial mode is supplied, then in searching for the template rule that best matches the initial context item, the processor considers only those rules that apply to the initial mode. If no initial mode is supplied, then the mode named in the default-mode attribute of the xsl:stylesheet element of the principal stylesheet module is used; or in the absence of such an attribute, the unnamed mode.]

    Note:

    If the initial mode is a streamable mode, then streaming will only be possible if the initial context item is a node that is supplied in a form that allows such processing: for example, as a reference to a stream of parsing events.

    Note:

    The design of the API for invoking a transformation should provide some means for users to designate the unnamed mode as the initial mode in cases where it is not the default mode.

  • A base output URI. [Definition:  The base output URI is a URI to be used as the base URI when resolving a relative URI reference allocated to a final result tree. If the transformation generates more than one final result tree, then typically each one will be allocated a URI relative to this base URI. ] The way in which a base output URI is established is implementation-defined.

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

    Note:

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

[ERR XTDE0040] It is a non-recoverable 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.

[ERR XTDE0045] It is a non-recoverable dynamic error if the invocation of the stylesheet specifies an initial mode (other than the default mode) that does not match the expanded-QName in the mode attribute of any template defined in the stylesheet.

[ERR XTDE0047] It is a non-recoverable dynamic error if the invocation of the stylesheet specifies both an initial mode and an initial template.

[ERR XTDE0050] It is a non-recoverable dynamic error if the stylesheet that is invoked declares a visible stylesheet parameter with required="yes" and no value for this parameter is supplied during the invocation of the stylesheet. A stylesheet parameter is visible if it is not masked by another global variable or parameter with the same name and higher import precedence.

[Definition: The transformation is performed by evaluating an initial template. If a named template is supplied when the transformation is initiated, then this is the initial template; otherwise, the initial template is the template rule selected according to the rules of the xsl:apply-templates instruction for processing the initial context item in the initial mode.]

Parameters passed to the transformation by the client application are matched against stylesheet parameters (see 9.5 Global Variables and Parameters), not against the template parameters declared within the initial template. All template parameters within the initial template to be executed will take their default values.

[ERR XTDE0060] It is a non-recoverable dynamic error if the initial template defines a template parameter that specifies required="yes".

A stylesheet can process further source documents in addition to those supplied when the transformation is invoked. These additional documents can be loaded using the functions document (see 19.1.1 The document function) or docFO or collectionFO (see [Functions and Operators]), or using the xsl:stream instruction; alternatively, they can be supplied as stylesheet parameters (see 9.5 Global Variables and Parameters), or returned as the result of an extension function (see 21.1 Extension Functions).

2.4 Executing a Transformation

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

A transformation as a whole is executed by evaluating the sequence constructor of the initial template as described in 5.7 Sequence Constructors.

The result sequence produced by evaluating the initial template is handled as follows:

  1. If the initial template has an as attribute, then the result sequence of the initial template is checked against the required type in the same way as for any other template.

  2. If the result sequence is non-empty, then it is used to construct an implicit final result tree, following the rules described in 5.7.1 Constructing Complex Content: the effect is as if the initial template T were called by an implicit template of the form:

    <xsl:template name="IMPLICIT">
      <xsl:result-document href="">
        <xsl:call-template name="T"/>
      </xsl:result-document>
    </xsl:template>
    

An implicit result tree is also created when the result sequence is empty, provided that no xsl:result-document instruction has been evaluated during the course of the transformation. In this situation the implicit result tree will consist of a document node with no children.

Note:

This means that there is always at least one result tree. It also means that if the content of the initial template is a single xsl:result-document instruction, as in the example above, then only one result tree is produced, not two. It is useful to make the result document explicit as this is the only way of invoking document-level validation.

If the result of the initial template is non-empty, and an explicit xsl:result-document instruction has been evaluated with the empty attribute href="", then an error will occur [see ERR XTDE1490], since it is not possible to create two final result trees with the same URI.

A sequence constructor is a sequence of sibling nodes in the stylesheet, each of which is either an XSLT instruction, a literal result element, a text node, or an extension instruction.

[Definition: An instruction is either an XSLT instruction or an extension instruction.]

[Definition: An XSLT instruction is an XSLT element whose syntax summary in this specification contains the annotation <!-- category: instruction -->.]

Extension instructions are described in 21.2 Extension Instructions.

The main categories of XSLT instruction are as follows:

Often, a sequence constructor will include an xsl:apply-templates instruction, which selects a sequence of nodes to be processed. Each of the selected nodes is processed by searching the stylesheet for a matching template rule and evaluating the sequence constructor of that template rule. The resulting sequences of items are concatenated, in order, to give the result of the xsl:apply-templates instruction, as described in 6.3 Applying Template Rules; this sequence is often added to a result tree. Since the sequence constructors of the selected template rules may themselves contain xsl:apply-templates instructions, this results in a cycle of selecting nodes, identifying template rules, constructing sequences, and constructing result trees, that recurses through a source tree.

2.5 The Evaluation Context

The results of some expressions and instructions in a stylesheet may depend on information provided contextually. This context information is divided into two categories: the static context, which is known during static analysis of the stylesheet, and the dynamic context, which is not known until the stylesheet is evaluated. Although information in the static context is known at analysis time, it is sometimes used during stylesheet evaluation.

Some context information can be set by means of declarations within the stylesheet itself. For example, the namespace bindings used for any XPath expression are determined by the namespace declarations present in containing elements in the stylesheet. Other information may be supplied externally or implicitly: an example is the current date and time.

The context information used in processing an XSLT stylesheet includes as a subset all the context information required when evaluating XPath expressions. The XPath 2.1 specification defines a static and dynamic context that the host language (in this case, XSLT) may initialize, which affects the results of XPath expressions used in that context. XSLT augments the context with additional information: this additional information is used firstly by XSLT constructs outside the scope of XPath (for example, the xsl:sort element), and secondly, by functions that are defined in the XSLT specification (such as key and current-group) that are available for use in XPath expressions appearing within a stylesheet.

The static context for an expression or other construct in a stylesheet is determined by the place in which it appears lexically. The details vary for different components of the static context, but in general, elements within a stylesheet module affect the static context for their descendant elements within the same stylesheet module.

The dynamic context is maintained as a stack. When an instruction or expression is evaluated, it may add dynamic context information to the stack; when evaluation is complete, the dynamic context reverts to its previous state. An expression that accesses information from the dynamic context always uses the value at the top of the stack.

The most commonly used component of the dynamic context is the context item. This is an implicit variable whose value is the item currently being processed (it may be a node, an atomic value, or a function item). The value of the context item can be referenced within an XPath expression using the expression . (dot).

Full details of the static and dynamic context are provided in 5.4 The Static and Dynamic Context.

2.6 Parsing and Serialization

An XSLT stylesheet describes a process that constructs a set of final result trees from a set of source trees.

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

[Definition: A frequent requirement is to output a final result tree as an XML document (or in other formats such as HTML). This process is referred to as serialization.]

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

2.7 Extensibility

XSLT defines a number of features that allow the language to be extended by implementers, or, if implementers choose to provide the capability, by users. These features have been designed, so far as possible, so that they can be used without sacrificing interoperability. Extensions other than those explicitly defined in this specification are not permitted.

These features are all based on XML namespaces; namespaces are used to ensure that the extensions provided by one implementer do not clash with those of a different implementer.

The most common way of extending the language is by providing additional functions, which can be invoked from XPath expressions. These are known as extension functions, and are described in 21.1 Extension Functions.

It is also permissible to extend the language by providing new instructions. These are referred to as extension instructions, and are described in 21.2 Extension Instructions. A stylesheet that uses extension instructions in a particular namespace must declare that it is doing so by using the [xsl:]extension-element-prefixes attribute.

Extension instructions and extension functions defined according to these rules may be provided by the implementer of the XSLT processor, and the implementer may also provide facilities to allow users to create further extension instructions and extension functions.

This specification defines how extension instructions and extension functions are invoked, but the facilities for creating new extension instructions and extension functions are implementation-defined. For further details, see 21 Extensibility and Fallback.

The XSLT language can also be extended by the use of extension attributes (see 3.3 Extension Attributes), and by means of user-defined data elements (see 3.6.3 User-defined Data Elements).

2.8 Stylesheets and XML Schemas

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

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

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

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

[Definition: The schema components that may be referenced by name in a stylesheet are referred to as the in-scope schema components. This set is the same throughout all the modules of a stylesheet.]

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

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

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

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

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

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

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

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

This example will cause the transformation to fail with an error message when the initial mode is the unnamed mode, unless the document element of the source document is valid against the top-level element declaration my:invoice, and has been annotated as such.

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

2.9 Streaming

[Definition: The term streaming refers to a manner of processing in which documents (such as source and result documents) are not represented by a complete tree of nodes occupying memory proportional to document size, but instead are processed "on the fly" as a sequence of events, similar in concept to the stream of events notified by an XML parser to represent markup in lexical XML.]

[Definition: A streamed document is a source tree that is processed using streaming, that is, without constructing a complete tree of nodes in memory.]

[Definition: A streamed node is a node in a streamed document.]

Many processors implementing earlier versions of this specification have adopted an architecture that allows streaming of the result tree directly to a serializer, without first materializing the complete result tree in memory. Streaming of the source tree, however, has proved to be more difficult without subsetting the language. This has created a situation where documents exceeding the capacity of virtual memory could not be transformed. XSLT 2.1 therefore introduces facilities allowing stylesheets to be written in a way that makes streaming of source documents possible, without excessive reliance on processor-specific optimization techniques.

Streaming achieves two important objectives: it allows large documents to be transformed without requiring correspondingly large amounts of memory; and it allows the processor to start producing output before it has finished receiving its input, thus reducing latency.

This specification does not attempt to legislate precisely which implementation techniques fall under the definition of streaming, and which do not. A number of techniques are available that reduce memory requirements, while still requiring a degree of buffering, or allocation of memory to partial results. A stylesheet that requests streaming of a source document is indicating that the processor should avoid assuming that the entire source document will fit in memory; in return, the stylesheet must be written in a way that makes streaming possible. This specification does not attempt to describe the algorithms that the processor should actually use, or to impose quantitative constraints on the resources that these algorithms should consume.

Nothing in this specification, nor in its predecessors [XSLT 1.0] and [XSLT 2.0], prevents a processor using streaming whenever it sees an opportunity to do so. However, experience has shown that in order to achieve streaming, it is often necessary to write stylesheet code in such a way as to make this possible. Therefore, XSLT 2.1 provides explicit constructs allowing the stylesheet author to request streaming, and defines explicit static constraints on the structure of the code which are designed to make streaming possible.

A processor that claims conformance with the streaming option offers a guarantee that when streaming is requested for a source document, and when the stylesheet conforms to the rules that make the processing guaranteed-streamable, then an algorithm will be adopted in which memory consumption is either completely independent of document size, or increases only very slowly as document size increases, allowing documents to be processed that are orders-of-magnitude larger than the physical memory available. A processor that does not claim conformance with the streaming option must still process a stylesheet and deliver the correct results, but is not required to use streaming algorithms, and may therefore fail with out-of-memory errors when presented with large source documents.

Apart from the fact that there are constructs to request streaming, and rules that must be followed to guarantee that streaming is possible, the language has been designed so there are as few differences as possible between streaming and non-streaming evaluation. The semantics of the language continue to be expressed in terms of the XDM data model, which is substantively unchanged; but readers must take care to observe that when terms like "node" and "axis" are used, the concepts are completely abstract and may have no direct representation in the run-time execution environment.

Streamed processing of a document can be initiated in one of two ways:

  • The initial mode can be declared as a streamable mode. In this case the initial context item will generally be a document node, and it will be supplied by the calling application in a form that allows streaming (that is, in some form other than a tree in memory; for example, as a reference to a push or pull XML parser primed to deliver a stream of events). The type of the initial context item can be constrained using the xsl:context-item element. In this case the template rule that matches the document node (in this mode) must be a streamable template, which means that it (as well as all other template rules using this mode) must satisfy certain statically checkable constraints to ensure that streaming is possible.

  • Streamed processing of any document can be initiated using the xsl:stream instruction. This has an attribute href whose value is the URI of a document to be processed using streaming, and the actual processing to be applied is defined by the instructions written as children of the xsl:stream instruction. These instructions must satisfy the same rules as for a streamable template.

The rules for streamability, which are defined in detail in 18.4 Streamability Analysis, impose two main constraints:

  • The only nodes reachable from the node that is currently being processed are its attributes and namespaces, its ancestors and their attributes and namespaces, and its descendants and their attributes and namespaces. The siblings of the node, and the siblings of its ancestors, are not reachable in the tree, and any attempt to use their values is a static error. However, constructs (for example, simple forms of xsl:number, and simple positional patterns) that require knowledge of the number of preceding elements by name are permitted.

  • When processing a given node in the tree, each descendant node can only be visited once. Essentially this allows two styles of processing: either visit each of the children once, and then process that child with the same restrictions applied; or process all the descendants in a single pass, in which case it is not possible while processing a descendant to make any further downward selection.

The second restriction, that only one visit to the children is allowed, means that XSLT code that was not designed with streaming in mind will often need to be rewritten to make it streamable. In many cases it is possible to do this using a technique sometimes called windowing or burst-mode streaming (note this is not quite the same meaning as windowing in XQuery 1.1.). Many XML documents consist of a large number of elements, each of manageable size, representing transactions or business objects where each such element can be processed independently: in such cases, an effective design pattern is to write a streaming transformation that takes a snapshot of each element in turn, processing the snapshot using the full power of the XSLT language. Each snapshot is a tree built in memory and is therefore fully navigable. For details see the snapshot and copy-of functions.

Streaming applications often fall into one of the following categories:

  • Aggregation applications, where a single aggregation operation (perhaps countFO, sumFO, existsFO, or distinct-valuesFO) is applied to a set of elements selected from the streamed source document by means of a path expression.

  • Record-at-a-time applications, where the source document consists of a long sequence of elements with similar structure ("records"), and each "record" is processed using the same logic, independently of any other "records". This kind of processing is facilitated using the snapshot and copy-of function mentioned earlier.

  • Grouping applications, where the output follows the structure of the input, except that an extra layer of hierarchy is added. For example, the input might be a flat series of banking transactions in date/time order, and the output might contain the same transactions grouped by date.

  • Accumulator applications, which are the same as record-at-a-time applications, except that the processing of one "record" might depend on data encountered earlier in the document. A classical example is processing a sequence of banking transactions in which the input transaction contains a debit or credit amount, and the output adds a running total (the account balance). The xsl:iterate instruction has been introduced to facilitate this style of processing.

  • Isomorphic transformations, in which there is an ordered (often largely one-to-one) relationship between the nodes of the source tree and the nodes of the result tree: for example, transformations that involve only the renaming or selective deletion of nodes, or scalar manipulations of the values held in the leaf nodes. Such transformations are most conveniently expressed using recursive application of template rules. This is possible with a streamed input document only if all the template rules adhere to the constraints required for streamability. To enforce these rules, while still allowing unrestricted processing of other documents within the same transformation, all streaming evaluation must be carried out using a specific mode, which is declared to be a streaming mode by means of an xsl:mode declaration in the stylesheet.

There are important classes of application in which streaming is possible only if multiple streams can be processed in parallel. This specification therefore provides facilities:

  1. allowing two sorted input sequences to be merged into one sorted output sequence (the xsl:merge instruction)

  2. allowing multiple output sequences to be generated during a single pass of an input sequence (the xsl:fork instruction).

These facilities have been designed in such a way that they can readily be implemented using streaming, that is, without materializing the input or output sequences in memory.

Issue 1 (streaming-pessimism):

The design adopted in this specification works on the basis that decisions about streamability should be made statically (at compile time). Sometimes this means taking a pessimistic approach, that is, rejecting a construct as non-streamable based on worst-case assumptions. Two examples of this are (a) disallowing <xsl:with-param name="p" select="@code"/> when calling a streamable template, on the grounds that the called template might perform disallowed navigation from the attribute node; (b) disallowing use of the descendant axis in cases where it might select two elements, one of which is an ancestor of the other. An alternative design approach would allow optimistic assumptions to be made in such cases, creating the risk of dynamic errors: for example it might be a dynamic error in the first case if the called template performs disallowed navigation from the attribute node, and in the second case if the descendant axis actually selects a node that is a descendant of another selected node. The decision to make the analysis pessimistic interacts with the strategy for fallback if streaming is not possible; a non-streaming fallback is feasible if decisions are made statically, but is not realistically possible if the problems are only detected at execution time. The Working Group welcomes discussion of this decision.

2.10 Error Handling

[Definition: An error that can be detected by examining a stylesheet before execution starts (that is, before the source document and values of stylesheet parameters are available) is referred to as a static error.]

Errors classified in this specification as static errors must be signaled by all implementations: that is, the processor must indicate that the error is present. A static error must be signaled even if it occurs in a part of the stylesheet that is never evaluated. Static errors are never recoverable. After signaling a static error, a processor may continue for the purpose of signaling additional errors, but it must eventually terminate abnormally without producing any final result tree.

There is an exception to this rule when the stylesheet specifies forwards compatible behavior (see 3.9 Forwards Compatible Processing).

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

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

[Definition: Some dynamic errors are classed as recoverable errors. When a recoverable error occurs, this specification allows the processor either to signal the error (by reporting the error condition and terminating execution) or to take a defined recovery action and continue processing.] It is implementation-defined whether the error is signaled or the recovery action is taken. If the processor chooses to signal the error rather than taking the recovery action, the error is then treated in the same way as a non-recoverable dynamic error and is therefore eligible to be caught using xsl:try/xsl:catch.

[Definition: If an implementation chooses to recover from a recoverable dynamic error, it must take the optional recovery action defined for that error condition in this specification.]

When the implementation makes the choice between signaling a dynamic error or recovering, it is not restricted in how it makes the choice; for example, it may provide options that can be set by the user. When an implementation chooses to recover from a dynamic error, it may also take other action, such as logging a warning message.

[Definition: A dynamic error that is not recoverable is referred to as a non-recoverable dynamic error. When a non-recoverable dynamic error occurs, the processor must signal the error, and (unless the error is caught using xsl:catch) the transformation fails.]

Note:

The term non-recoverable is retained from earlier XSLT versions, and implies that the processor will not recover from the error on its own initiative. However, the introduction of xsl:try and xsl:catch in XSLT 2.1 means that such errors can now be recovered by means of application logic.

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

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

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

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

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

Example: Errors in Constant Subexpressions

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

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

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

[Definition: Certain errors are classified as type errors. A type error occurs when the value supplied as input to an operation is of the wrong type for that operation, for example when an integer is supplied to an operation that expects a node.] If a type error occurs in an instruction that is actually evaluated, then it must be signaled in the same way as a non-recoverable dynamic error. Alternatively, an implementation may signal a type error during the analysis phase in the same way as a static error, even if it occurs in part of the stylesheet that is never evaluated, provided it can establish that execution of a particular construct would never succeed.

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

Example: A Type Error

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

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

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

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

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

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

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

[Definition: If a transformation has successfully produced a final result tree, it is still possible that errors may occur in serializing the result tree. For example, it may be impossible to serialize the result tree using the encoding selected by the user. Such an error is referred to as a serialization error.] If the processor performs serialization, then it must do so as specified in 23 Serialization, and in particular it must signal any serialization errors that occur.

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

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

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

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

3 Stylesheet Structure

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

Note:

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

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

A stylesheet module is either a standard stylesheet module or a simplified stylesheet module:

Both forms of stylesheet module (standard and simplified) can exist either as an entire XML document, or embedded as part of another XML document, typically but not necessarily a source document that is to be processed using the stylesheet.

[Definition: A standalone stylesheet module is a stylesheet module that comprises the whole of an XML document.]

[Definition: An embedded stylesheet module is a stylesheet module that is embedded within another XML document, typically the source document that is being transformed.] (see 3.11 Embedded Stylesheet Modules).

There are thus four kinds of stylesheet module:

standalone standard stylesheet modules
standalone simplified stylesheet modules
embedded standard stylesheet modules
embedded simplified stylesheet modules

3.1 XSLT Namespace

[Definition: The XSLT namespace has the URI http://www.w3.org/1999/XSL/Transform. It is used to identify elements, attributes, and other names that have a special meaning defined in this specification.]

Note:

The 1999 in the URI indicates the year in which the URI was allocated by the W3C. It does not indicate the version of XSLT being used, which is specified by attributes (see 3.6 Stylesheet Element and 3.7 Simplified Stylesheet Modules).

XSLT processors must use the XML namespaces mechanism [Namespaces in XML] to recognize elements and attributes from this namespace. Elements from the XSLT namespace are recognized only in the stylesheet and not in the source document. The complete list of XSLT-defined elements is specified in C Element Syntax Summary. Implementations must not extend the XSLT namespace with additional elements or attributes. Instead, any extension must be in a separate namespace. Any namespace that is used for additional instruction elements must be identified by means of the extension instruction mechanism specified in 21.2 Extension Instructions.

This specification uses a prefix of xsl: for referring to elements in the XSLT namespace. However, XSLT stylesheets are free to use any prefix, provided that there is a namespace declaration that binds the prefix to the URI of the XSLT namespace.

Note:

Throughout this specification, an element or attribute that is in no namespace, or an expanded-QName whose namespace part is an empty sequence, is referred to as having a null namespace URI.

Note:

The conventions used for the names of XSLT elements, attributes and functions are that names are all lower-case, use hyphens to separate words, and use abbreviations only if they already appear in the syntax of a related language such as XML or HTML. Names of types defined in XML Schema are regarded as single words and are capitalized exactly as in XML Schema. This sometimes leads to composite function names such as current-dateTimeFO.

3.2 Reserved Namespaces

[Definition: The XSLT namespace, together with certain other namespaces recognized by an XSLT processor, are classified as reserved namespaces and must be used only as specified in this and related specifications.] The reserved namespaces are those listed below.

  • The XSLT namespace, described in 3.1 XSLT Namespace, is reserved.

  • [Definition: The standard function namespace http://www.w3.org/2005/xpath-functions is used for functions in the function library defined in [Functions and Operators] and for standard functions defined in this specification.]

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

  • [Definition: The XML namespace, defined in [Namespaces in XML] as http://www.w3.org/XML/1998/namespace, is used for attributes such as xml:lang, xml:space, and xml:id.]

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

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

  • [Definition: The standard error namespace http://www.w3.org/2005/xqt-errors is used for error codes defined in this specification and related specifications. It is also used for the names of certain predefined variables accessible within the scope of an xsl:catch element.]

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

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

Note:

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

[ERR XTSE0080] It is a static error to use a reserved namespace in the name of a named template, a mode, an attribute set, a key, a decimal-format, a variable or parameter, a stylesheet function, a named output definition, or a character map.

3.3 Extension Attributes

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

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

Note:

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

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

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

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

Example: An Extension Attribute for xsl:message

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

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

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

[ERR XTSE0090] It is a static error for an element from the XSLT namespace to have an attribute whose namespace is either null (that is, an attribute with an unprefixed name) or the XSLT namespace, other than attributes defined for the element in this document.

3.4 XSLT Media Type

The media type application/xslt+xml has been registered for XSLT stylesheet modules.

The definition of the media type is at [XSLT Media Type].

This media type should be used for an XML document containing a standard stylesheet module at its top level, and it may also be used for a simplified stylesheet module. It should not be used for an XML document containing an embedded stylesheet module.

3.5 Standard Attributes

[Definition: There are a number of standard attributes that may appear on any XSLT element: specifically version, exclude-result-prefixes, extension-element-prefixes, xpath-default-namespace, default-collation, and use-when.]

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:version, xsl:exclude-result-prefixes, xsl:extension-element-prefixes, xsl:xpath-default-namespace, xsl:default-collation, or xsl:use-when.

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:]version, [xsl:]xpath-default-namespace, and [xsl:]default-collation, the value can be overridden by a different value for the same attribute appearing on a descendant element. The effective value of the attribute for a particular stylesheet element is determined by the innermost ancestor-or-self element on which the attribute appears.

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

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

The effect of the [xsl:]use-when attribute is described in 3.12 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 and xsl:transform elements only. This reflects the fact that these attributes are often used on the xsl:stylesheet element only, in which case they apply to the entire stylesheet module.

Note that the effect of these attributes does not extend to stylesheet modules referenced by xsl:include or xsl:import declarations.

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

[xsl:]version

see 3.8 Backwards Compatible Processing and 3.9 Forwards Compatible Processing

[xsl:]xpath-default-namespace

see 5.2 Unprefixed QNames in Expressions and Patterns

[xsl:]exclude-result-prefixes

see 11.1.3 Namespace Nodes for Literal Result Elements

[xsl:]extension-element-prefixes

see 21.2 Extension Instructions

[xsl:]use-when

see 3.12 Conditional Element Inclusion

[xsl:]default-collation

see 3.6.1 The default-collation attribute

3.6 Stylesheet Element

<xsl:stylesheet
  id? = id
  extension-element-prefixes? = tokens
  exclude-result-prefixes? = tokens
  version = number
  xpath-default-namespace? = uri
  default-validation? = "preserve" | "strip"
  default-collation? = uri-list
  default-mode? = qname | "#unnamed"
  input-type-annotations? = "preserve" | "strip" | "unspecified" >
  <!-- Content: (xsl:import*, other-declarations) -->
</xsl:stylesheet>

<xsl:transform
  id? = id
  extension-element-prefixes? = tokens
  exclude-result-prefixes? = tokens
  version = number
  xpath-default-namespace? = uri
  default-validation? = "preserve" | "strip"
  default-collation? = uri-list
  default-mode? = qname | "#unnamed"
  input-type-annotations? = "preserve" | "strip" | "unspecified" >
  <!-- Content: (xsl:import*, other-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.

An xsl:stylesheet element must have a version attribute, indicating the version of XSLT that the stylesheet module requires.

[ERR XTSE0110] The value of the version attribute must be a number: specifically, it must be a 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 2.1, the value should normally be set to 2.1. If the value is numerically less than 2.1, the stylesheet is processed using the rules for backwards compatible behavior (see 3.8 Backwards Compatible Processing). If the value is numerically greater than 2.1, the stylesheet is processed using the rules for forwards compatible behavior (see 3.9 Forwards Compatible Processing).

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

The default-validation attribute defines the default value of the validation attribute of all xsl:document, xsl:element, xsl:attribute, xsl:copy, xsl:copy-of, and xsl:result-document instructions, and of the xsl:validation attribute of all literal result elements. It also determines the validation applied to the implicit final result tree created in the absence of an xsl:result-document instruction. This default applies within the stylesheet module: it does not extend to included or imported stylesheet modules. If the attribute is omitted, the default is strip. The permitted values are preserve and strip. For details of the effect of this attribute, see 22.2 Validation.

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

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

[Definition: Top-level elements fall into two categories: declarations, and user-defined data elements. Top-level elements whose names are in the XSLT namespace are declarations. Top-level elements in any other namespace are user-defined data elements (see 3.6.3 User-defined Data Elements)].

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

xsl:import
xsl:include
xsl:attribute-set
xsl:character-map
xsl:decimal-format
xsl:function
xsl:import-schema
xsl:key
xsl:mode
xsl:namespace-alias
xsl:output
xsl:param
xsl:preserve-space
xsl:strip-space
xsl:template
xsl:variable

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

If there are xsl:import elements, these must come before any other elements. Apart from this, 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.4 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.

3.6.1 The default-collation attribute

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

The attribute is used to specify the default collation used by all XPath expressions appearing in the attributes of this element, or attributes of descendant elements, unless overridden by another default-collation attribute on an inner element. It also determines the collation used by certain XSLT constructs (such as xsl:key and xsl:for-each-group) within its scope.

The value of the attribute is a whitespace-separated list of collation URIs. If any of these URIs is a relative URI reference, then it is resolved relative to the base URI of the attribute's parent element. If the implementation recognizes one or more of the resulting absolute collation URIs, then it uses the first one that it recognizes as the default collation.

[ERR XTSE0125] It is a static error if the value of an [xsl:]default-collation attribute, after resolving against the base URI, contains no URI that the implementation recognizes as a collation URI.

Note:

The reason the attribute allows a list of collation URIs is that collation URIs will often be meaningful only to one particular XSLT implementation. Stylesheets designed to run with several different implementations can therefore specify several different collation URIs, one for use with each. To avoid the above error condition, it is possible to specify the Unicode Codepoint Collation as the last collation URI in the list.

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

3.6.2 The default-mode attribute

The default-mode attribute defines the default value for the mode attribute of all xsl:template and xsl:apply-templates elements within the stylesheet module. It also determines which mode is referred to when the token #default is used in either of these attributes.

The value must either be a lexical QName, or the token #unnamed which refers to the unnamed mode. It is not necessary for the referenced mode to be explicitly declared in an xsl:mode declaration.

If the default-mode attribute is omitted, then the default mode for the stylesheet module is the unnamed mode. This is equivalent to specifying #unnamed.

Note:

This attribute is provided to support an approach to stylesheet modularity in which all the template rules for one mode are collected together into a single stylesheet module. Using this attribute reduces the risk of forgetting to specify the mode in one or more places where it is needed, and it also makes it easier to reuse an existing stylesheet module that does not use modes in an application where modes are needed to avoid conflicts with existing template rules.

Issue 2 (chameleon-modes):

Would it be useful to be able to specify the default mode for an included module on the xsl:include element, in the style of chameleon includes in XSD? The WG has discussed such a feature; it is recognized that it would be useful, but it is not clear whether it would be useful enough to justify the extra complexity.

3.6.3 User-defined Data Elements

[Definition: In addition to declarations, the xsl:stylesheet element may contain among its children any element not from the XSLT namespace, provided that the expanded-QName of the element has a non-null namespace URI. Such elements are referred to as user-defined data elements.]

[ERR XTSE0130] It is a static error if the xsl:stylesheet element has a child element whose name has a null namespace URI.

An implementation may attach an implementation-defined meaning to user-defined data elements that appear in particular namespaces. The set of namespaces that are recognized for such data elements is implementation-defined. The presence of a user-defined data element must not change the behavior of XSLT elements and functions defined in this document; for example, it is not permitted for a user-defined data element to specify that xsl:apply-templates should use different rules to resolve conflicts. The constraints on what user-defined data elements can and cannot do are exactly the same as the constraints on extension attributes, described in 3.3 Extension Attributes. Thus, an implementation is always free to ignore user-defined data elements, and must ignore such data elements without giving an error if it does not recognize the namespace URI.

User-defined data elements can provide, for example,

A user-defined data element must not precede an xsl:import element within a stylesheet module [see ERR XTSE0200]

3.7 Simplified Stylesheet Modules

A simplified syntax is allowed for a stylesheet module that defines only a single template rule for the document node. The stylesheet module may consist of just a literal result element (see 11.1 Literal Result Elements) together with its contents. The literal result element must have an xsl:version attribute (and it must therefore also declare the XSLT namespace). Such a stylesheet module is equivalent to a standard stylesheet module whose xsl:stylesheet element contains a template rule containing the literal result element, minus its xsl:version attribute; the template rule has a match pattern of /.

Example: A Simplified Stylesheet

For example:

<html xsl:version="2.1"
      xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
      xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <title>Expense Report Summary</title>
  </head>
  <body>
    <p>Total Amount: <xsl:value-of select="expense-report/total"/></p>
  </body>
</html>

has the same meaning as

<xsl:stylesheet version="2.1"
                xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
                xmlns="http://www.w3.org/1999/xhtml">
<xsl:template match="/">
<html>
  <head>
    <title>Expense Report Summary</title>
  </head>
  <body>
    <p>Total Amount: <xsl:value-of select="expense-report/total"/></p>
  </body>
</html>
</xsl:template>
</xsl:stylesheet>

Note that it is not possible, using a simplified stylesheet, to request that the serialized output contains a DOCTYPE declaration. This can only be done by using a standard stylesheet module, and using the xsl:output element.

More formally, a simplified stylesheet module is equivalent to the standard stylesheet module that would be generated by applying the following transformation to the simplified stylesheet module, invoking the transformation by calling the named template expand, with the containing literal result element as the context node:

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

<xsl:template name="expand">
  <xsl:element name="xsl:stylesheet">
    <xsl:attribute name="version" select="@xsl:version"/>
    <xsl:element name="xsl:template">
      <xsl:attribute name="match" select="'/'"/>
      <xsl:copy-of select="."/>
    </xsl:element>
  </xsl:element>
</xsl:template>  

</xsl:stylesheet>

[ERR XTSE0150] A literal result element that is used as the outermost element of a simplified stylesheet module must have an xsl:version attribute. This indicates the version of XSLT that the stylesheet requires. For this version of XSLT, the value will normally be 2.1 ; the value must be a valid instance of the type xs:decimal as defined in [XML Schema Part 2].

The allowed content of a literal result element when used as a simplified stylesheet is the same as when it occurs within a sequence constructor. Thus, a literal result element used as the document element of a simplified stylesheet cannot contain declarations. Simplified stylesheets therefore cannot use template rules, global variables, stylesheet parameters, stylesheet functions, keys, attribute-sets, or output definitions. In turn this means that the only useful way to initiate the transformation is to supply a document node as the initial context item, to be matched by the implicit match="/" template rule using the unnamed mode.

3.8 Backwards Compatible Processing

[Definition: The effective version of an element in the stylesheet is the decimal value of the [xsl:]version attribute (see 3.5 Standard Attributes) on that element or on the innermost ancestor element that has such an attribute, excluding the version attribute on an xsl:output element.]

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

Specifically:

  • If the effective version is equal to 1.0, then the element is processed with XSLT 1.0 behavior as described in 3.8.1 XSLT 1.0 compatibility mode.

  • If the effective version is equal to 2.0, then the element is processed with XSLT 2.0 behavior as described in 3.8.2 XSLT 2.0 compatibility mode.

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

    Note:

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

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

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

[ERR XTDE0160] It is a non-recoverable dynamic error if an element has an effective version of V (with V < 2.1) when the implementation does not support backwards compatible behavior for XSLT version V.

Note:

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

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

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

3.8.1 XSLT 1.0 compatibility mode

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

In this mode, if any attribute contains an XPath expression, then the expression is evaluated with XPath 1.0 compatibility mode set to true. For details of this mode, see Section 2.1.1 Static ContextXP21.

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

Note:

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

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

3.8.2 XSLT 2.0 compatibility mode

[Definition: An element is processed with XSLT 2.0 behavior if its effective version is equal to 2.0.]

In this working draft, no differences are defined for XSLT 2.0 behavior. An XSLT 2.1 processor will therefore produce the same results whether the effective version of an element is set to 2.0 or 2.1.

Note:

An XSLT 2.0 processor, by contrast, will in some cases produce different results in the two cases. For example, if the stylesheet contains an xsl:iterate instruction with an xsl:fallback child, an XSLT 2.1 processor will process the xsl:iterate instruction regardless whether the effective version is 2.0 or 2.1, while an XSLT 2.0 processor will report a static error if the effective version is 2.0, and will take the fallback action if the effective version is 2.1.

3.9 Forwards Compatible Processing

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

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

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

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

The detailed rules follow.

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

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

When an element is processed with forwards compatible behavior:

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

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

  • if the element is in the XSLT namespace and appears as part of a sequence constructor, and XSLT 2.1 does not allow such elements to appear as part of a sequence constructor, then:

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

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

Example: Forwards Compatible Behavior

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

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

Note:

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

Example: Testing the XSLT Version

For example,

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

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

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

3.10 Combining Stylesheet Modules

XSLT provides two mechanisms to construct a stylesheet 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.

3.10.1 Locating Stylesheet Modules

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.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 module may be any of the four kinds of stylesheet module: that is, it may be standalone or embedded, and it may be standard or simplified. If it is a simplified stylesheet module then it is transformed into the equivalent standard stylesheet module by applying the transformation described in 3.7 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 conforming to this specification.

3.10.2 Stylesheet Inclusion

<!-- Category: declaration -->
<xsl:include
  href = uri-reference />

A stylesheet module may include another stylesheet module using an xsl:include declaration.

The xsl:include declaration has a required href attribute whose value is a URI reference identifying the stylesheet module to be included. This attribute is used as described in 3.10.1 Locating Stylesheet Modules.

[ERR XTSE0170] An xsl:include element must be a top-level element.

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

[Definition: The declarations within a stylesheet level have a total ordering known as declaration order. The order of declarations within a stylesheet level is the same as the document order that would result if each stylesheet module were inserted textually in place of the xsl:include element that references it.] In other respects, however, the effect of xsl:include is not equivalent to the effect that would be obtained by textual inclusion.

[ERR XTSE0180] It is a static error if a stylesheet module directly or indirectly includes itself.

Note:

It is not intrinsically an error for a stylesheet to include the same module more than once. However, doing so can cause errors because of duplicate definitions. Such multiple inclusions are less obvious when they are indirect. For example, if stylesheet B includes stylesheet A, stylesheet C includes stylesheet A, and stylesheet D includes both stylesheet B and stylesheet C, then A will be included indirectly by D twice. If all of B, C and D are used as independent stylesheets, then the error can be avoided by separating everything in B other than the inclusion of A into a separate stylesheet B' and changing B to contain just inclusions of B' and A, similarly for C, and then changing D to include A, B', C'.

3.10.3 Stylesheet Import

<!-- Category: declaration -->
<xsl:import
  href = uri-reference />

A stylesheet module may import another stylesheet module using an xsl:import declaration. Importing a stylesheet module is the same as including it (see 3.10.2 Stylesheet Inclusion) except that template rules and other declarations in the importing module take precedence over template rules and declarations in the imported module; this is described in more detail below.

The xsl:import declaration has a required href attribute whose value is a URI reference identifying the stylesheet module to be included. This attribute is used as described in 3.10.1 Locating Stylesheet Modules.

[ERR XTSE0190] An xsl:import element must be a top-level element.

[ERR XTSE0200] The xsl:import element children must precede all other element children of an xsl:stylesheet element, including any xsl:include element children and any user-defined data elements.

Example: Using xsl:import

For example,

<xsl:stylesheet version="2.1"
                xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <xsl:import href="article.xsl"/>
  <xsl:import href="bigfont.xsl"/>
  <xsl:attribute-set name="note-style">
    <xsl:attribute name="font-style">italic</xsl:attribute>
  </xsl:attribute-set>
</xsl:stylesheet>

[Definition: The stylesheet levels making up a stylesheet are treated as forming an import tree. In the import tree, each stylesheet level has one child for each xsl:import declaration that it contains.] The ordering of the children is the declaration order of the xsl:import declarations within their stylesheet level.

[Definition: A declaration D in the stylesheet is defined to have lower import precedence than another declaration E if the stylesheet level containing D would be visited before the stylesheet level containing E in a post-order traversal of the import tree (that is, a traversal of the import tree in which a stylesheet level is visited after its children). Two declarations within the same stylesheet level have the same import precedence.]

For example, suppose

  • stylesheet module A imports stylesheet modules B and C in that order;

  • stylesheet module B imports stylesheet module D;

  • stylesheet module C imports stylesheet module E.

Then the import tree has the following structure:

This browser can't display the SVG file img/fig1.svg. Please upgrade your browser or install the Adobe SVG Viewer.

Here you should see a diagram. If it does not appear correctly in your browser, you need to install an SVG Plugin.

The order of import precedence (lowest first) is D, B, E, C, A.

In general, a declaration with higher import precedence takes precedence over a declaration with lower import precedence. This is defined in detail for each kind of declaration.

[ERR XTSE0210] It is a static error if a stylesheet module directly or indirectly imports itself.

Note:

The case where a stylesheet module with a particular URI is imported several times is not treated specially. The effect is exactly the same as if several stylesheet modules with different URIs but identical content were imported. This might or might not cause an error, depending on the content of the stylesheet module.

3.11 Embedded Stylesheet Modules

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

Two situations where embedded stylesheets may be useful are:

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

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

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

Note:

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

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

Example: The xml-stylesheet Processing Instruction

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

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

Note:

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

Note:

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

Note:

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

3.12 Conditional Element Inclusion

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

Note:

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

A literal result element, or any other element within a stylesheet module that is not in the XSLT namespace, may similarly carry an xsl:use-when attribute.

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

Note:

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

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

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

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

Static Context Components for use-when Expressions
Component Value
XPath 1.0 compatibility mode false
In scope namespaces determined by the in-scope namespaces for the containing element in the stylesheet
Default element/type namespace determined by the xpath-default-namespace attribute if present (see 5.2 Unprefixed QNames in Expressions and Patterns); otherwise the null namespace
Default function namespace The standard function namespace
In scope type definitions The type definitions that would be available in the absence of any xsl:import-schema declaration
In scope element declarations None
In scope attribute declarations None
In scope variables None
In scope functions The core functions defined in [Functions and Operators], together with the functions element-available, function-available, type-available, and system-property defined in this specification, plus the set of extension functions that are present in the static context of every XPath expression (other than a use-when expression) within the content of the element that is the parent of the use-when attribute. Note that stylesheet functions are not included in the context, which means that the function function-available will return false in respect of such functions. The effect of this rule is to ensure that function-available returns true in respect of functions that can be called within the scope of the use-when attribute. It also has the effect that these extensions functions will be recognized within the use-when attribute itself; however, the fact that a function is available in this sense gives no guarantee that a call on the function will succeed.
In scope collations Implementation-defined
Default collation The Unicode Codepoint Collation
Base URI The base URI of the containing element in the stylesheet
Statically known documents None
Statically known collections None
Statically known decimal formats A single unnamed decimal format equivalent to the decimal format that is created by an xsl:decimal-format declaration with no attributes.

 

Dynamic Context Components for use-when Expressions
Component Value
Context item, position, and size Undefined
Dynamic variables None
Current date and time Implementation-defined
Implicit timezone Implementation-defined
Available documents None
Available collections None

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

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

Example: Using Conditional Exclusion to Achieve Portability

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

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

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

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

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

 

Example: Including Variant Stylesheet Modules

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

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

3.13 Built-in Types

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

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

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

Issue 3 (additional-types):

It is likely that the new types from XSD 1.1 will be added to this list when XSD 1.1 becomes a Recommendation.

A schema-aware XSLT processor additionally supports:

Note:

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

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

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

3.14 Importing Schema Components

Note:

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

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

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

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

The same schema components are available in all stylesheet modules; importing components in one stylesheet module makes them available throughout the stylesheet.

The namespace and schema-location attributes are both optional.

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

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

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

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

[ERR XTSE0215] It is a static error if an xsl:import-schema element that contains an xs:schema element has a schema-location attribute, or if it has a namespace attribute that conflicts with the target namespace of the contained schema.

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

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

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

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

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

The schema components included in the in-scope schema components (that is, the components whose names are available for use within the stylesheet) are the top-level element and attribute declarations and type definitions that are available for reference within the synthetic schema document. See [XML Schema Part 1] (section 4.2.3, References to schema components across namespaces).

[ERR XTSE0220] It is a static error if the synthetic schema document does not satisfy the constraints described in [XML Schema Part 1] (section 5.1, Errors in Schema Construction and Structure). This includes, without loss of generality, conflicts such as multiple definitions of the same name.

Note:

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

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

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

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

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

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

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

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

Example: An Inline Schema Document

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

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

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

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

4 Data Model

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

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

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

[Definition: A whitespace text node is a text node whose content consists entirely of whitespace characters (that is, #x09, #x0A, #x0D, or #x20).]

Note:

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

4.1 XML Versions

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

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

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

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

Note:

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

The current version of [XML Schema Part 2] (that is, XSD 1.0) does not reference the XML 1.1 specifications. This means that data types such as xs:NCName and xs:ID are constrained by the XML 1.0 rules, and do not allow the full range of values permitted by XML 1.1. This situation will not be resolved until a new version of [XML Schema Part 2] becomes available; in the meantime, it is recommended that implementers wishing to support XML 1.1 should consult [XML Schema 1.0 and XML 1.1] for guidance. An XSLT 2.1 processor that supports XML 1.1 should implement the rules in later versions of [XML Schema Part 2] as they become available.

4.2 Stripping Whitespace from the Stylesheet

The tree representing the stylesheet is preprocessed as follows:

  1. All comments and processing instructions are removed.

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

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

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

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

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

    xsl:analyze-string
    xsl:apply-imports
    xsl:apply-templates
    xsl:attribute-set
    xsl:call-template
    xsl:character-map
    xsl:choose
    xsl:evaluate
    xsl:merge
    xsl:merge-source
    xsl:next-iteration
    xsl:next-match
    xsl:stylesheet
    xsl:transform

  5. Any whitespace text node whose immediate following-sibling node is an xsl:merge-key, xsl:param, or xsl:sort element is removed from the tree, regardless of any xml:space attributes.

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

[ERR XTSE0260] Within an XSLT element that is required to be empty, any content other than comments or processing instructions, including any whitespace text node preserved using the xml:space="preserve" attribute, is a static error.

Note:

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

Note:

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

4.3 Stripping Type Annotations from a Source Tree

[Definition: The term type annotation is used in this specification to refer to the value returned by the dm:type-name accessor of a node: see Section 5.14 type-name AccessorDM11.]

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

Such stripping of type annotations can be requested by specifying input-type-annotations="strip" on the xsl:stylesheet element. This attribute has three permitted values: strip, preserve, and unspecified. The default value is unspecified. Stripping of type annotations takes place if at least one stylesheet module in the stylesheet specifies input-type-annotations="strip".

[ERR XTSE0265] It is a static error if there is a stylesheet module in the stylesheet that specifies input-type-annotations="strip" and another stylesheet module that specifies input-type-annotations="preserve".

The source trees to which this applies are the same as those affected by xsl:strip-space and xsl:preserve-space: see 4.4 Stripping Whitespace from a Source Tree.

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

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

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

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

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

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

Note:

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

4.4 Stripping Whitespace from a Source Tree

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

For the purposes of this section, the term source tree means the document containing the initial context item if it is a node, and any document returned by the functions document, docFO, or collectionFO. It does not include documents passed as the values of stylesheet parameters or returned from extension functions.

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

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

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

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

Otherwise, the whitespace text node is stripped.

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

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

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

The set of whitespace-preserving element names is specified by xsl:strip-space and xsl:preserve-space declarations. Whether an element name is included in the set of whitespace-preserving names is determined by the best match among all the xsl:strip-space or xsl:preserve-space declarations: it is included if and only if there is no match or the best match is an xsl:preserve-space element. The xsl:strip-space and xsl:preserve-space elements each have an elements attribute whose value is a whitespace-separated list of NameTestsXP21; an element name matches an xsl:strip-space or xsl:preserve-space element if it matches one of the NameTestsXP21. An element matches a NameTestXP21 if and only if the NameTestXP21 would be true for the element as an XPath node test. When more than one xsl:strip-space and xsl:preserve-space element matches, the best matching element is determined by the best matching NameTestXP21. This is determined in the same way as with template rules:

[ERR XTRE0270] It is a recoverable dynamic error if this leaves more than one match, unless all the matched declarations are equivalent (that is, they are all xsl:strip-space or they are all xsl:preserve-space). The optional recovery action is to select, from the matches that are left, the one that occurs last in declaration order.

Issue 4 (multiple-match-on-strip-space):

We have changed the rules for handling ambiguous matches on template rules. Should we make a corresponding change for ambiguous matches on xsl:strip-space, or is this overkill? What is the corresponding change anyway?

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

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

Note:

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

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

4.5 Attribute Types and DTD Validation

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

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

4.6 Data Model for Streaming

The data model for nodes in a document that is being streamed is no different from the standard XDM data model, in that it contains the same objects (nodes) with the same properties and relationships. The facilities for streaming do not change the data model; instead they impose rules that limit the ability of stylesheets to navigate the data model.

A useful way to visualize streaming is to suppose that at any point in time, there is a current position in the streamed input document which may be the start or end of the document, the start or end tag of an element, or a text, comment, or processing instruction node. From this position, the stylesheet has access to the following information:

  • Properties intrinsic to the node, such as its name, its base URI, its type annotation, and its is-id and is-idref properties.

  • The ancestors of the node (but navigation downwards from the ancestors is not permitted).

  • The attributes of the node, and the attributes of its ancestors. For each such attribute, all the properties of the node including its string value and typed value are available, but there are limitations that restrict navigation from the attribute node to other nodes in the document.

  • The in-scope namespace bindings of the node.

  • In the case of attributes, text nodes, comments, and processing instructions, the string value and typed value of the node.

  • Summary data about the preceding siblings of the node, and of each of its ancestor nodes: specifically, for each distinct combination of node kind, node name, and type annotation, a count of the number of preceding siblings that have that combination of properties. This information allows patterns such as match="para[1]" to be used, and it permits some limited use of the xsl:number instruction.

The children and other descendants of a node are not accessible except as a by-product of changing the current position in the document. The same applies to properties of an element or document node that require examination of the node's descendants, that is, the string value and typed value. This is enforced by means of a rule that only one expression requiring downward navigation from a node is permitted.

The detailed rules are defined in 18.4 Streamability Analysis.

4.7 Limits

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

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

The following limits are implementation-defined:

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

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

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

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

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

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

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

4.8 Disable Output Escaping

For backwards compatibility reasons, XSLT 2.1 continues to support the disable-output-escaping feature introduced in XSLT 1.0. This is an optional feature and implementations are not required to support it. A new facility, that of named character maps (see 23.1 Character Maps) was introduced in XSLT 2.0. It provides similar capabilities to disable-output-escaping, but without distorting the data model.

If an implementation supports the disable-output-escaping attribute of xsl:text and xsl:value-of, (see 23.2 Disabling Output Escaping), then the data model for trees constructed by the processor is augmented with a boolean value representing the value of this property. This boolean value, however, can be set only within a final result tree that is being passed to the serializer.

Conceptually, each character in a text node on such a result tree has a boolean property indicating whether the serializer is to disable the normal rules for escaping of special characters (for example, outputting of & as &amp;) in respect of this character or attribute node.

Note:

In practice, the nodes in a final result tree will often be streamed directly from the XSLT processor to the serializer. In such an implementation, disable-output-escaping can be viewed not so much a property stored with nodes in the tree, but rather as additional information passed across the interface between the XSLT processor and the serializer.

5 Features of the XSLT Language

5.1 Qualified Names

The name of a stylesheet-defined object, specifically a named template, a mode, an attribute set, a key, a decimal-format, a variable or parameter, a stylesheet function, a named output definition, or a character map is specified as a QName using the syntax for QNameNames as defined in [Namespaces in XML].

[Definition: A QName is always written in the form (NCName ":")? NCName, that is, a local name optionally preceded by a namespace prefix. When two QNames are compared, however, they are considered equal if the corresponding expanded-QNames are the same, as described below.]

Because an atomic value of type xs:QName is sometimes referred to loosely as a QName, this specification also uses the term lexical QName to emphasize that it is referring to a QNameNames in its lexical form rather than its expanded form. This term is used especially when strings containing lexical QNames are manipulated as run-time values.

[Definition: A lexical QName is a string representing a QName in the form (NCName ":")? NCName, that is, a local name optionally preceded by a namespace prefix.]

[Definition: A string in the form of a lexical QName may occur as the value of an attribute node in a stylesheet module, or within an XPath expression contained in such an attribute node, or as the result of evaluating an XPath expression contained in such an attribute node. The element containing this attribute node is referred to as the defining element of the QName.]

[Definition: An expanded-QName contains a pair of values, namely a local name and an optional namespace URI. It may also contain a namespace prefix. 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.]

If the QName has a prefix, then the prefix is expanded into a URI reference using the namespace declarations in effect on its defining element. The expanded-QName consisting of the local part of the name and the possibly null URI reference is used as the name of the object. The default namespace of the defining element (see Section 6.2 Element NodesDM11) is not used for unprefixed names.

There are three cases where the default namespace of the defining element is used when expanding an unprefixed QName:

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

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

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

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

[ERR XTSE0280] In the case of a prefixed QName used as 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 QName.

[ERR XTDE0290] Where the result of evaluating an XPath expression (or an attribute value template) is required to be a lexical QName, then unless otherwise specified it is a non-recoverable dynamic error if the defining element has no namespace node whose name matches the prefix of the lexical QName. This error may be signaled as a static error if the value of the expression can be determined statically.

5.2 Unprefixed QNames in Expressions and Patterns

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

The value of the attribute is the namespace URI to be used.

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

For any element in the stylesheet, the effective value of this attribute determines the value of the default namespace for element and type names in the static context of any XPath expression contained in an attribute of that element (including XPath expressions in attribute value templates). The effect of this is specified in [XPath 2.1]; in summary, it determines the namespace used for any unprefixed type name in the SequenceType production, and for any element name appearing in a path expression or in the SequenceType production.

The effective value of this attribute similarly applies to any of the following constructs appearing within its scope:

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

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

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

5.3 Expressions

XSLT uses the expression language defined by XPath 2.1 [XPath 2.1]. 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 ExprXP21 defined in [XPath 2.1].]

An XPath expression may occur as the value of certain attributes on XSLT-defined elements, and also within curly brackets in attribute value templates.

Except where forwards compatible behavior is enabled (see 3.9 Forwards Compatible Processing), it is a static error if the value of such an attribute, or the text between curly brackets in an attribute value template, does not match the XPath production ExprXP21, 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 2.1].

The transformation fails with a non-recoverable dynamic error if any XPath expression is evaluated and raises a dynamic error. Error codes are defined in [XPath 2.1].

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 signals a type error during static analysis of an expression. Error codes are defined in [XPath 2.1].

[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: Except where otherwise indicated, the actual value of an expression is converted to the required type using the function conversion rules. These are the rules defined in [XPath 2.1] for converting the supplied argument of a function call to the required type of that argument, as defined in the function signature. The relevant rules are those that apply when XPath 1.0 compatibility mode is set to false.]

This specification also invokes the XPath 2.1 function conversion 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 function conversion 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 reported statically if they can be detected statically, whether or not the construct in question is ever evaluated. Attempting to convert the string 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 reported only if the instructions or expressions that cause them are actually evaluated.

5.4 The Static and Dynamic Context

XPath defines the concept of an expression contextXP21 which contains all the information that can affect the result of evaluating an expression. The expression context has two parts, the static contextXP21, and the dynamic contextXP21. The components that make up the expression context are defined in the XPath specification (see Section 2.1 Expression ContextXP21). This section describes the way in which these components are initialized when an XPath expression is contained within an XSLT stylesheet.

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.4.1 Initializing the Static Context
5.4.2 Additional Static Context Components used by XSLT
5.4.3 Initializing the Dynamic Context
5.4.4 Additional Dynamic Context Components used by XSLT

5.4.1 Initializing the Static Context

The static contextXP21 of an XPath expression appearing in an XSLT stylesheet is initialized as follows. In these rules, the term containing element means the element within the stylesheet that is the parent of the attribute whose value contains the XPath expression in question, and the term enclosing element means the containing element or any of its ancestors.

Issue 5 (recommended-initial-context):

In the rules for defining the initial static context, we sometimes say that the value is implementation-defined, and then give a default. We need to be clearer what we are saying here. Essentially the "default" is a recommendation to implementors about what the value should be when users don't select anything different. Perhaps if we have recommended defaults for some of these values, we should have them for all.

5.4.2 Additional Static Context Components used by XSLT

Some of the components of the XPath static context are used also by XSLT elements. For example, the xsl:sort element makes use of the collations defined in the static context, and attributes such as type and as may reference types defined in the in-scope schema components.

Many top-level declarations in a stylesheet, and attributes on the xsl:stylesheet element, affect the behavior of instructions within the stylesheet. Each of these constructs is described in its appropriate place in this specification.

A number of these constructs are of particular significance because they are used by functions defined in XSLT, which are added to the library of functions available for use in XPath expressions within the stylesheet. These are:

  • The set of named keys, used by the key function

  • The values of system properties, used by the system-property function

  • The set of available instructions, used by the element-available function

5.4.3 Initializing the Dynamic Context

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

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

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

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

5.4.3.1 Maintaining Position: the Focus

[Definition: When a sequence constructor is evaluated, the processor keeps track of which items are being processed by means of a set of implicit variables referred to collectively as the focus.] More specifically, the focus consists of the following three values:

  • [Definition: The context item is the item currently being processed. An item (see [Data Model]) is either an atomic value (such as an integer, date, or string), a node, or a function item. The context item is initially set to the initial context item supplied when the transformation is invoked (see 2.3 Initiating a Transformation). It changes whenever instructions such as xsl:apply-templates and xsl:for-each are used to process a sequence of items; each item in such a sequence becomes the context item while that item is being processed.] The context item is returned by the XPath expression . (dot).

  • [Definition: The context position is the position of the context item within the sequence of items currently being processed. It changes whenever the context item changes. When an instruction such as xsl:apply-templates or xsl:for-each is used to process a sequence of items, the first item in the sequence is processed with a context position of 1, the second item with a context position of 2, and so on.] The context position is returned by the XPath expression position().

  • [Definition: The context size is the number of items in the sequence of items currently being processed. It changes whenever instructions such as xsl:apply-templates and xsl:for-each are used to process a sequence of items; during the processing of each one of those items, the context size is set to the count of the number of items in the sequence (or equivalently, the position of the last item in the sequence).] The context size is returned by the XPath expression last().

[Definition: If the context item is a node (as distinct from an atomic value 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 value or a function item, there is no context node.] The context node is returned by the XPath expression self::node(), and it is used as the starting node for all relative path expressions.

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

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

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

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

When a stylesheet function is called, the focus within the body of the function is initially undefined. The focus is also undefined on initial entry to the stylesheet if no initial context item is supplied.

When the focus is undefined, evaluation of any expression that references the context item, context position, or context size results in a non-recoverable dynamic error [XPDY0002]

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

[Definition: A singleton focus based on an item J has the context item (and therefore the context node, if J is a node) set to J, and the context position and context size both set to 1 (one).]

5.4.3.2 Other components of the XPath Dynamic Context

The previous section explained how the focus for an XPath expression appearing in an XSLT stylesheet is initialized. This section explains how the other components of the dynamic contextXP21 of an XPath expression are initialized.

  • The dynamic variablesXP21 are the current values of the in-scope variable binding elements.

  • The current date and time represents an implementation-dependent point in time during processing of the transformation; it does not change during the course of the transformation.

  • The implicit timezoneXP21 is implementation-defined.

  • The available documentsXP21, and the available collectionsXP21 are determined as part of the process for initiating a transformation (see 2.3 Initiating a Transformation).

    The available documentsXP21 are defined as part of the XPath 2.1 dynamic context to support the docFO function, but this component is also referenced by the similar XSLT document function: see 19.1.1 The document function. This variable defines a mapping between URIs passed to the docFO or document function and the document nodes that are returned.

    Note:

    Defining this as part of the evaluation context is a formal way of specifying that the way in which URIs get turned into document nodes is outside the control of the language specification, and depends entirely on the run-time environment in which the transformation takes place.

    The XSLT-defined document function allows the use of URI references containing fragment identifiers. The interpretation of a fragment identifier depends on the media type of the resource representation. Therefore, the information supplied in available documentsXP21 for XSLT processing must provide not only a mapping from URIs to document nodes as required by XPath, but also a mapping from URIs to media types.

  • The default collectionXP21 is implementation-defined. This allows options such as setting the default collection to be an empty sequence, or to be undefined.

5.4.4 Additional Dynamic Context Components used by XSLT

In addition to the values that make up the focus, an XSLT processor maintains a number of other dynamic context components that reflect aspects of the evaluation context. These components are fully described in the sections of the specification that maintain and use them. They are:

The following non-normative table summarizes the initial state of each of the components in the evaluation context, and the instructions which cause the state of the component to change.

Issue 6 (normative-evaluation-context):

Although this table is described as non-normative, it may be more complete than the same information given normatively elsewhere.

Component Initial Setting Set by Cleared by
focus singleton focus based on the initial context item if supplied xsl:apply-templates, xsl:for-each, xsl:for-each-group, xsl:analyze-string non-contextual function calls
current template rule If a named template is supplied as the entry point to the transformation, then null; otherwise the initial template xsl:apply-templates, xsl:apply-imports, xsl:next-match xsl:for-each, xsl:for-each-group, xsl:analyze-string, xsl:iterate, xsl:stream, xsl:merge, xsl:evaluate, and non-contextual function calls. Also cleared while evaluating global variables or default values of stylesheet parameters, and the sequence constructors contained in xsl:key and xsl:sort.
current mode the initial mode xsl:apply-templates non-contextual function calls, evaluation of global variables and stylesheet parameters, evaluation of the sequence constructor contained in xsl:key or xsl:sort. Clearing the current mode causes the current mode to be set to the default (unnamed) mode.
current group empty sequence xsl:for-each-group non-contextual function calls
current grouping key empty sequence xsl:for-each-group non-contextual function calls
current captured substrings empty sequence xsl:matching-substring xsl:non-matching-substring; non-contextual function calls
output state final output state Set to temporary output state by instructions such as xsl:variable, xsl:attribute, etc., and by calls on stylesheet functions None

[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-func-invoke IN XP21]dynamic function invocations, (that is calls to function items as permitted by XPath 2.1). It does not include calls to all core 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.]

Note:

A consequence of these rules is that whereas the function call current-group() returns the contents of the current group, the dynamic function invocation current-group#0() always returns the empty sequence.

5.5 Patterns

In XSLT 2.1, patterns can match any kind of item: atomic values 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 19.3 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 two basic kinds of pattern: type patterns, and path patterns. Patterns may also be formed by combining other patterns using union, intersection, and difference operators.

A type pattern is written with a leading ~ (tilde) followed by an ItemTypeXP21 and an optional list of predicates: for example, ~xs:anyAtomicValue matches any atomic value, ~xs:integer[. mod 2 = 0] matches any even integer, ~node() matches any node, and ~function()[empty(function-name(.))] matches any function item that refers to an anonymous function. An item matches a type pattern if and only if the item is an instance of the specified type and satisfies all the predicates.

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

5.5.1 Examples of Patterns

Example: Patterns

Here are some examples of patterns:

  • para matches any para element.

  • * matches any element.

  • chapter|appendix matches any chapter element and any appendix element.

  • olist/entry matches any entry element with an olist parent.

  • appendix//para matches any para element 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 that has a parent 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).

  • @* 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'.

  • ~item() matches any item whatsoever.

  • ~node() matches any node. (Note the distinction from the pattern node().)

  • ~element() matches any element. (This is precisely equivalent to the pattern element().)

  • ~xs:date matches any atomic value of type xs:date (or a type derived by restriction from xs:date).

  • ~xs:date[. gt current-date()] matches any date in the future.

  • ~function() matches any function item.

  • ~function(xs:integer) as xs:integer matches any function item whose underlying function takes an integer argument and returns an integer result.

5.5.2 Syntax of Patterns

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

The grammar for patterns uses the notation defined in Section A.1.1 NotationXP21.

The lexical rules for patterns are the same as the lexical rules for XPath expressions, as defined in Section A.2 Lexical structureXP21. 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.

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

Patterns
[1]    Pattern    ::=    PatternTerm ( ('|' | 'union') PatternTerm )*
[2]    PatternTerm    ::=    BasicPattern ( ('intersect' | 'except') BasicPattern )*
[3]    BasicPattern    ::=    TypePattern | PathPattern | QualifiedPattern
[4]    QualifiedPattern    ::=    '(' Pattern ')' PredicateListXP21
[5]    TypePattern    ::=    '~' ItemTypeXP21 PredicateListXP21
[6]    PathPattern    ::=    RelativePathPattern
| '/' RelativePathPattern?
| '//' RelativePathPattern
| RootedPattern
[7]    RootedPattern    ::=    ( VarRefRoot | DocCall | IdCall | ElementWithIdCall | KeyCall )
(('/' | '//') RelativePathPattern)?
[8]    VarRefRoot    ::=    VarRefXP21
[9]    RelativePathPattern    ::=    PatternStep (('/' | '//') PatternStep)*
[10]    PatternStep    ::=    PatternAxis? NodeTestXP21 PredicateListXP21
[11]    PatternAxis    ::=    (('child' | 'attribute' | 'descendant' | 'descendant-or-self') '::') | '@'
[12]    DocCall    ::=    'doc' '(' ArgValue ')'
[13]    IdCall    ::=    'id' '(' ArgValue (',' ArgValue )? ')'
[14]    ElementWithIdCall    ::=    'element-with-id' '(' ArgValue (',' ArgValue )? ')'
[15]    KeyCall    ::=    'key' '(' ArgValue ',' ArgValue (',' ArgValue )? ')'
[16]    ArgValue    ::=    LiteralXP21 | VarRefXP21

The constructs ItemTypeXP21, NodeTestXP21, PredicateListXP21, VarRefXP21, and LiteralXP21 are part of the XPath expression language, and are defined in [XPath 2.1].

In a DocCall, IdCall, ElementWithIdCall, or KeyCall, the construct has the same semantics as a call to the corresponding function in an XPath expression. In particular, the arguments must (after conversion using the function conversion rules if necessary) be of the correct type required by the signature of the function. The function conversion rules are applied with XPath 1.0 compatibility mode set to false. If an argument cannot be converted to the required type, a type error results: if the type error can be detected statically then it may be signalled statically.

5.5.3 The Meaning of a Pattern

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

  1. An item matches the Pattern A | B (or equivalently, A union B) if it matches either A or B or both. (The operators | and union are synonyms.)

  2. An item matches the PatternTerm A intersect B if it matches both A and B.

    Note:

    The operators union, |, intersect, and except are analogous to the XPath operators with the same representation, but there is a difference: in patterns, the definition above gives these operators a meaning when matching atomic values as well as when matching nodes.

    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 b be achieved by writing (/) union (/*)

  3. An item matches the PatternTerm A except B if it matches A and does not match B.

  4. Multiple intersect and except operators are applied from left to right: for example A intersect B except C means (A intersect B) except C: that is, the item must match both A and B, and must not match C.

  5. An item J matches a QualifiedPattern if J matches the parenthesized Pattern and satisfies each of the predicates in the PredicateListXP21. The predicates are evaluated with a singleton focus based on J.

  6. An item J matches a TypePattern if J is an instance of the specified ItemTypeXP21 and satisfies each of the predicates in the PredicateListXP21. The predicates are evaluated with a singleton focus based on J.

  7. An item N matches a PathPattern if 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, where EE is the equivalent expression to the PathPattern, as defined below.

    The concept of an equivalent expression is defined as follows. In general, the equivalent expression to a PathPattern is the XPath expression that takes the same lexical form as the PathPattern as written. However, if the PathPattern is a RelativePathPattern, then the first PatternStep PS of this RelativePathPattern 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 3.2.4 Abbreviated SyntaxXP), and is made as follows:

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

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

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

    4. If PS uses the namespace axis (implicitly, by using namespace-node() as a KindTest), 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.

      Issue 7 (implicit-namespace-axis):

      In XPath 2.1, as currently defined, the path expression A/B/namespace-node() selects nothing, because the default axis for the abbreviated step namespace-node() is child rather than namespace. This has been raised as bug 9298. Perhaps we should allow the namespace axis to be explicit in a pattern.

    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 these adjustments 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 2.1 allows the pattern ~node() to be used (note the tilde).

Example: The Semantics of Path Patterns

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

The path pattern node() 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.

The path 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 path pattern doc('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.

Although the semantics of path patterns are specified formally in terms of expression evaluation, it is possible to understand pattern matching using a different model. A path 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.

5.5.4 Errors in Patterns

Any dynamic error or type error that occurs during the evaluation of a pattern against a particular item is treated as a recoverable error even if the error would not be recoverable under other circumstances. The optional recovery action is to treat the pattern as not matching that node.

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. Making errors in patterns recoverable enables an implementation, if it chooses to do so, to report such errors while stylesheets are under development, while masking them if they occur during production running.

There are several particular cases where a processor must not raise a dynamic error:

  • When evaluating a PathPattern that starts with / or // or with a call on idFO, element-with-idFO, or key, the result of testing this pattern against a node in a tree whose root is not a document node must be a non-match, rather than a dynamic error. This rule applies to each PathPattern within a Pattern.

    Note:

    Without the above rule, any attempt to apply templates to a parentless element node would create the risk of a dynamic error if the stylesheet has a template rule specifying match="/".

  • When matching an atomic value against a PathPattern, the result must always be a non-match, rather than a dynamic error.

  • A processor must not evaluate a predicate within a pattern unless the item matches the part of the pattern that is qualified by the predicate. (Or equivalently, if it does evaluate the predicate, it must not signal an error when the evaluation fails.) For example, evaluation of the pattern ~xs:integer[. gt 5] must not cause an error when testing an item of type xs:date, and the pattern $var[child::*] must not cause an error when testing an atomic value. If there are multiple predicates, they must be evaluated from left to right.

5.6 Attribute Value Templates

[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 ({})].

An attribute value template consists of an alternating sequence of fixed parts and variable parts. A variable part consists of an XPath expression enclosed in curly brackets ({}). 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 }}. If the XPath expression ends with a closing curly bracket, this must be separated from the delimiting closing bracket by whitespace.

Note:

An expression within a variable part may contain an unescaped curly bracket within a StringLiteralXP21 or within a comment.

Currently no XPath expression starts with an opening curly bracket, and the only XPath expression that can end in a closing curly bracket is an inline function literal, which cannot usefully appear in an attribute value template.

[ERR XTSE0350] It is a static error if an unescaped left curly bracket appears in a fixed part of an attribute value template without a matching right curly bracket.

It is a static error if the string contained between matching curly brackets in an attribute value template does not match the XPath production ExprXP21, or if it contains other XPath static errors. The error is signaled 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 an attribute value template.

[Definition: The result of evaluating an attribute value template is referred to as the effective value of the attribute.] 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 obtained by evaluating the enclosed XPath expression and converting the resulting value to a string. This conversion is done using the rules given in 5.7.2 Constructing Simple Content.

Note:

This process can generate dynamic errors, for example if the sequence contains an element with a complex content type (which cannot be atomized).

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

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.

Example: Attribute Value Templates

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"/>

 

Example: Producing a Space-Separated List

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.

Example: Curly Brackets can not be Nested

For example:

<a href="#{id({@ref})/title}">

is not allowed. Instead, use simply:

<a href="#{id(@ref)/title}">

5.7 Sequence Constructors

[Definition: A sequence constructor is a sequence of zero or more sibling nodes in the stylesheet that can be evaluated to return a sequence of nodes, atomic values, 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:

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.

There are several ways the result of a sequence constructor may be used.

5.7.1 Constructing Complex Content

This section describes how the sequence obtained by evaluating a sequence constructor may be used to construct the children of a newly constructed document node, or the children, attributes and namespaces of a newly constructed element node. The sequence of items may be obtained by evaluating the sequence constructor contained in an instruction such as xsl:copy, xsl:element, xsl:document, xsl:result-document, or a literal result element.

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 sequence is processed as follows (applying the rules in the order they are listed):

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

  2. Any atomic value 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.

  3. Any consecutive sequence of strings within the result sequence is converted to a single text node, whose string value contains the content of each of the strings in turn, with a single space (#x20) used as a separator between successive strings.

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

  5. Zero-length text nodes within the result sequence are removed.

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

  7. Invalid items in the result sequence are detected as follows.

    [ERR XTDE0410] It is a non-recoverable dynamic error if the result 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 non-recoverable dynamic error if the result sequence used to construct the content of a document node contains a namespace node or attribute node.

    [ERR XTDE0430] It is a non-recoverable dynamic error if the result 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 non-recoverable dynamic error if the result 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 non-recoverable dynamic error if the result sequence contains a function item.

  8. If the result 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 undefined, it is not significant which of the duplicates is retained.

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

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

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

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

Example: A Sequence Constructor for Complex Content

Consider the following stylesheet fragment:

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

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

 

Example: Space Separators in Element Content

Consider the following stylesheet fragment:

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

This produces the output (when indented):

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

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

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

5.7.2 Constructing Simple Content

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

  1. Zero-length text nodes in the sequence are discarded.

  2. Adjacent text nodes in the sequence are merged into a single text node.

  3. The sequence is atomized (which may cause a dynamic error).

  4. Every value in the atomized sequence is cast to a string.

  5. The strings within the resulting sequence are concatenated, with a (possibly zero-length) separator inserted between successive strings. The default separator is a single space. In the case of xsl:attribute and xsl:value-of, a different separator can be specified using the separator attribute of the instruction; it is permissible for this to be a zero-length string, in which case the strings are concatenated with no separator. In the case of xsl:comment, xsl:processing-instruction, and xsl:namespace, and when expanding an attribute value template, the default separator cannot be changed.

  6. In the case of xsl:processing-instruction, any leading spaces in the resulting string are removed.

  7. The resulting string forms the string value of the new attribute, namespace, comment, processing-instruction, or text node.

Example: Space Separators in Attribute Content

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>
</doc>

This produces the output:

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

The difference between the two cases is that for the e attribute, the sequence constructor generates a sequence of five atomic values, 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.

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 values are handled: separators are never inserted between adjacent text nodes.

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

5.7.3 Namespace Fixup

In a tree supplied to or constructed by an XSLT processor, the constraints relating to namespace nodes that are specified in [Data Model] 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 xml must not be associated with any other namespace URI, and the namespace URI http://www.w3.org/XML/1998/namespace must 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 and Sequences) 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 input sequence, documents loaded using the document, docFO or collectionFO 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, docFO or collectionFO 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 [Data Model], including the constraints imposed by the namespace fixup process. The effect of supplying a pseudo-document that does not meet these constraints is undefined.

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 2.1 supports the creation of result trees that do not satisfy this constraint: the namespace fixup process does not add a namespace node to an element merely because its parent node in the result tree has such a namespace node. However, the process of constructing the children of a new element, which is described in 5.7.1 Constructing Complex Content, does cause the namespaces of a parent element to be inherited by its children unless this is prevented using [xsl:]inherit-namespaces="no" on the instruction that creates the parent element.

Note:

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

5.8 URI References

[Definition: Within this specification, the term URI Reference, unless otherwise stated, refers to a string in the lexical space of the xs:anyURI data type 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, and xsl:result-document.

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

The rules for collation URIs are given in [Functions and Operators].

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.

6 Template Rules

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

6.1 Defining Templates

<!-- Category: declaration -->
<xsl:template
  match? = pattern
  name? = qname
  priority? = number
  mode? = tokens
  as? = sequence-type >
  <!-- Content: (xsl:param*, sequence-constructor) -->
</xsl:template>

[Definition: An xsl:template declaration defines a template, which contains a sequence constructor for creating nodes, atomic values, and/or function items. 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.

If an xsl:template element has a match attribute, then it is a template rule. If it has a name attribute, then it is a named template.

A template may be invoked in a number of ways, depending on whether it is a template rule, a named template, or both. The result of invoking the template is the result of evaluating the sequence constructor contained in the xsl:template element (see 5.7 Sequence Constructors).

If an as attribute 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 function conversion 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 converted to the required type.

6.2 Defining Template Rules

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.

Example: A simple Template Rule

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.4 Conflict Resolution for Template Rules.

6.3 Applying Template Rules

<!-- Category: instruction -->
<xsl:apply-templates
  select? = expression
  mode? = token >
  <!-- 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.4 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.7 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.

Example: Applying Template Rules

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.

Example: Applying Templates to Selected Nodes

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>

 

Example: Applying Templates to Nodes that are not Descendants

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>

 

Example: Matching Nodes by Schema-Defined Types

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.8 Overriding Template Rules.

 

Example: Re-ordering Elements in the Result Tree

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>

 

Example: Processing Recursive Structures

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"

 

Example: Applying Templates to Atomic Values

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="~xs:string[starts-with(., '==')]">
  <h2><xsl:value-of select="replace(., '==', '')"/></h2>
</xsl:template>

<xsl:template match="~xs:string[starts-with(., '::')]">
  <p class="indent"><xsl:value-of select="replace(., '::', '')"/></p>
</xsl:template>

<xsl:template match="~xs:string">
  <p class="body"><xsl:value-of select="."/></p>
</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.

6.4 Conflict Resolution for Template Rules

It is possible for a selected item to match more than one template rule with a given mode M. When this happens, only one template rule is evaluated for the item. The template rule to be used is determined as follows:

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

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

  3. If this leaves more than one matching template rule, then:

    1. If the mode M has an xsl:mode declaration, and the attribute value on-multiple-match="fail" is specified in the mode declaration, a dynamic error is signalled. 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 XTRE0540] It is a non-recoverable 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 in on-multiple-match attribute with the value fail.

    2. 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 signaled, or whether the ambiguity was resolved by taking the last matching rule in declaration order. The choice of error code reflects this legacy. In XSLT 2.1 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 warnings-on-multiple-match="yes".

    Issue 8 (define-warning-codes):

    Should we define warning codes in the same way as we define error codes?

6.5 Default Priority for Template Rules

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

  1. If the top-level pattern consists of multiple alternatives separated by | , then the template rule is treated equivalently to a set of template rules, one for each alternative. However, it is not an error if an item matches more than one of the alternatives.

  2. If the top-level pattern is a PatternTerm containing two or more BasicPatterns separated by intersect or except operators, then the priority of the pattern is that of the first BasicPattern.

  3. If the pattern (in its entirety) is a TypePattern with an empty PredicateListXP21, then:

    1. If the ItemTypeXP21 is item(), the priority is −2 (minus two).

    2. If the ItemTypeXP21 is node(), function(), or xs:anyAtomicType, the priority is −1 (minus one).

    3. If the ItemTypeXP21 is any other atomic type, the priority is the priority associated with its base type plus 1. This means for example that the priority of ~xs:decimal is 0 (zero), and the priority of ~xs:integer is +1 (plus one).

    4. If the ItemTypeXP21 is any other NodeTestXP21, the priority is the same as when that NodeTest appears as a pattern in its own right (see below). For example, the priority of ~element() is −0.5 (minus 0.5), while that of ~element(E) is 0 (zero).

    5. If the ItemTypeXP21 is a TypedFunctionTestXP21, the priority is 0 (zero).

  4. If the pattern (in its entirety) is a TypePattern with a non-empty PredicateListXP21, then the priority is that of the ItemTypeXP21 in the absence of the PredicateListXP21, as given above, plus 0.5. So, for example, the priority of the pattern ~xs:integer[. gt 0] is +1.5.

  5. If the pattern is a PathPattern taking the form /, then the priority is −0.5 (minus 0.5).

  6. If the pattern is a PathPattern taking the form of a QName optionally preceded by a PatternAxis or has the form processing-instruction( StringLiteralXP21 ) or processing-instruction( NCNameNames ) optionally preceded by a PatternAxis, then the priority is 0 (zero).

  7. If the pattern is a PathPattern taking the form of an ElementTestXP21 or AttributeTestXP21, optionally preceded by a PatternAxis, 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, while 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(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(E,T) 0.25 (matches by name and type)
    schema-element(E) 0.25 (matches by substitution group and type)
    attribute(A,T) 0.25 (matches by name and type)
    schema-attribute(A) 0.25 (matches by name and type)
  8. If the pattern is a PathPattern taking the form of a DocumentTestXP21, then if it includes no ElementTestXP21 or SchemaElementTestXP21 the priority is −0.5. If it does include an ElementTestXP21 or SchemaElementTestXP21, then the priority is the same as the priority of that ElementTestXP21 or SchemaElementTestXP21, computed according to the table above.

  9. If the pattern is a PathPattern taking the form of an NCNameNames:* or *:NCNameNames, optionally preceded by a PatternAxis, then the priority is −0.25.

  10. If the pattern is a PathPattern taking the form of any other NodeTestXP21, optionally preceded by a PatternAxis, then the priority is −0.5.

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

In the case of a TypePattern, the default priority reflects the position of the type in the type hierarchy.

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.

6.6 Modes

[Definition:  Modes allow a node in a source tree 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 19.1.1 The document function) or when processing temporary trees.]

Modes are identified by a QName; in addition to any named modes, there is always one unnamed mode available. Whether a mode is named or unnamed, its properties may be defined in an xsl:mode declaration. If a mode name is used (for example in an xsl:template declaration or an xsl:apply-templates instruction) and no declaration of that mode appears in the stylesheet, the mode is implicitly declared with default properties.

6.6.1 Declaring Modes

<!-- Category: declaration -->
<xsl:mode
  name? = qname
  streamable? = "yes" | "no"
  initial? = "yes" | "no"
  on-no-match? = "stringify" | "discard" | "copy" | "fail"
  on-multiple-match? = "use-last" | "fail"
  warning-on-no-match? = "yes" | "no"
  warning-on-multiple-match? = "yes" | "no" >
  <!-- Content: (xsl:context-item?) -->
</xsl:mode>

[Definition: There is always an unnamed mode available. 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 default-mode attribute of the containing xsl:stylesheet element.]

Every mode other than the unnamed mode is identified by a 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 stylesheet 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.]

If a stylesheet does not contain a declaration of the unnamed mode, a declaration is implied equivalent to an xsl:mode element with the single attribute initial="yes". Similarly, if there is a mode that is named in an xsl:template or xsl:apply-templates element, or in the default-mode attribute of an xsl:stylesheet 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 plus the attribute initial="yes".

The contained xsl:context-item element, if present, is used to declare requirements for the initial context item when this mode is used as the initial mode. Therefore, there must be no xsl:context-item child if initial="no" is specified.

[ERR XTSE0542] It is a static error if an xsl:mode declaration specifying initial="no" contains an xsl:context-item element.

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.

Editorial note  
Need to make the formatting of tables more consistent. Also consider whether a tabular style could be more generally used for describing the attributes of particular elements (and consider custom markup for generating the table).
Attribute Values Meaning
name A lexical QName Specifies the name of the mode. If omitted, this xsl:mode declaration provides properties of the unnamed mode
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 18.2 Streamable Templates.
initial yes or no (default yes) Determines whether this mode can be used as the initial mode when the transformation is invoked. If the value yes is specified, or if the attribute is omitted, then the mode is eligible to be used as the initial mode; if the value no is specified then processing in the mode can only be achieved by means of an xsl:apply-templates instruction within the stylesheet that names this mode.
on-no-match One of stringify, discard, copy, or fail (default stringify) Determines selection of the built-in template rules that are used to process a node when an xsl:apply-templates instruction selects a node that does not match any user-written template rule in the stylesheet. For details, see 6.7 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 the node, having the same import precedence and priority. The value fail indicates that it is a non-recoverable dynamic error if more than one template rule matches the node. 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 a node that matches no 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 a node 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.

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

The above rules apply both to the attributes (other than name) of the xsl:mode element itself, and to the attributes of the contained xsl:context-item element if present.

[ERR XTSE0545] It is a static error if a named or unnamed mode contains 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, and the as attribute on the contained xsl:context-item element if present.

If the initial context item supplied to a stylesheet is a streamed document node, then it is not permitted for the values of global variables to be dependent on the context item in a way that requires reading of the input stream. This constraint is enforced by the following static rule:

[ERR XTSE0548] It is a static error if there is both (a) a mode definition in the stylesheet that has the effective attribute values streamable="yes" and initial="yes", and (b) a global variable in the stylesheet whose initializing expression is not motionless with respect to its context item, as defined in 18.4 Streamability Analysis.

6.6.2 Declaring the initial context item for a mode

Given a mode that is used as the initial mode, the xsl:context-item element may be used to constrain the type of the initial context item that is supplied by the calling application.

<xsl:context-item
  as? = ItemType />

If the as attribute is present then its value must be an ItemTypeXP21. When this mode (the mode defined in the containing xsl:mode declaration) is used as the initial mode, then an initial context item must be supplied externally, and its value will be converted to this type using the function conversion rules; this may result in a type errors if the conversion is not possible.

If the as attribute is omitted this is equivalent to specifying as="item()".

Note:

If the ItemType is one that can only be satisfied by a schema-validated input document, for example as="schema-element(invoice)", the processor may interpret this as a request to apply schema validation to the input. Similarly, if the KindTest indicates that an element node is required, the processor may interpret this as a request to supply the document element rather than the document node of a supplied input document.

If there is no xsl:context-item element for an xsl:mode that specifies initial="yes", this is equivalent to specifying <xsl:context-item as="item()"/>

A type errors is signalled if the supplied context item does not match its required type. The error codes is the same as for xsl:param [see ERR XTTE0590].

Example: Declaring the Required Context Item

The following example declares two modes, both of which have initial="yes" meaning that they can be used as entry points to the stylesheet. In the first mode, named invoice, the required context item is a schema-validated invoice element. In the second mode, named po, the required context item is a schema-validated purchase-order element. A third mode, format-address is declared with initial="no" so it cannot be used as an initial entry point; this mode might be used when processing content that is common to invoices and purchase orders.

<xsl:mode name="invoice" initial="yes" on-no-match="copy">
  <xsl:context-item as="schema-element(invoice)">
</xsl:mode>
<xsl:mode name="po" initial="yes" on-no-match="copy">
  <xsl:context-item as="schema-element(purchase-order)">
</xsl:mode>
<xsl:mode name="format-address" initial="no"/>

Issue 9 (declaring-context-item-for-initial-template):

It would also be useful to be able to declare the required type of the context item (or to say that there is none) when starting the transformation with an initial named template

6.6.3 Using Modes

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 default-mode attribute of the containing xsl:stylesheet element, 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 must be one of the following:

  • a QName, which is expanded as described in 5.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 for the stylesheet module

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

[ERR XTSE0550] It is a static error if the list 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.

The xsl:apply-templates element also has an optional mode attribute. The value of this attribute must be one of the following:

If the attribute is omitted, the default mode for the stylesheet module 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 stylesheet function is called, 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.8 Overriding Template Rules).

6.7 Built-in Template Rules

When a node is selected by xsl:apply-templates and there is no user-specified template rule in the stylesheet that can be used to process that node, 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 four 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 four values stringify, copy, discard, or fail, the default being stringify. The effect of these four sets of built-in template rules is explained in the following subsections.

6.7.1 Built-in Templates: stringify

The general effect of choosing on-no-match="stringify" for a mode is to retain the textual content of the source document while losing the markup. 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.

The built-in template rule for text and attribute nodes and atomic values returns a text node containing the string value of the context node. It is effectively:

<xsl:template match="text()|@*|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, namespace nodes, and function items does nothing (it returns the empty sequence).

<xsl:template 
   match="processing-instruction()|comment()|namespace-node()|function()" 
   mode="M"/>
Example: Using a Built-In Template Rule

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>

6.7.2 Built-in Templates: discard

The general effect of choosing on-no-match="discard" for a mode is to omit both the text and the markup from the result document, except in the case of items that are matched by explicit user-written template rules.

The built-in rule for document nodes and element nodes is the same as for on-no-match="stringify": that is, it 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.

The built-in template rule for all other kinds of node, and for atomic values and function items, is empty: that is, when the item is matched, the built-in template rule returns an empty sequence.

6.7.3 Built-in Templates: copy

The general effect of choosing on-no-match="copy" for a mode 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 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="~item()" mode="M">
  <xsl:copy validation="preserve">
    <xsl:apply-templates select="@*" mode="M"/>
    <xsl:apply-templates select="node()" mode="M"/>
  </xsl:copy>
</xsl:template>

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

Example: Modified Identity Transformation

The following stylesheet transforms an input document by deleting all elements named note, together with their attributes and descendants:

<xsl:stylesheet version="2.1"
     xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
                                  
<xsl:mode on-no-match="copy" streamable="yes"/>

<xsl:template match="note">
  <!-- no action -->
</xsl:template>

</xsl:stylesheet>

6.7.4 Built-in Templates: fail

The general effect of choosing on-no-match="fail" for a mode is that every node selected in an xsl:apply-templates instruction must be matched by an explicit user-written template rules.

The built-in template rule is effectively:

<xsl:template match="~item()" mode="M">
  <xsl:message error-code="err:XTDE0555"/>
</xsl:template>

with an implementation-dependent message body.

[ERR XTDE0555] It is a non-recoverable dynamic error if xsl:apply-templates, xsl:apply-imports or xsl:next-match is used to process a node using a mode whose declaration specifies on-no-match="fail" when there is no template rule in the stylesheet whose match pattern matches that node.

6.8 Overriding Template Rules

<!-- 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.4 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 other template rules of lower import precedence and/or priority. Both instructions will invoke the built-in template rule for the context item (see 6.7 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. When an xsl:for-each, xsl:for-each-group, xsl:analyze-string, xsl:iterate, xsl:stream, xsl:merge, or xsl:evaluate instruction is evaluated, or when evaluating a sequence constructor contained in an xsl:sort or xsl:key element, or when a stylesheet function is called (see 10.3 Stylesheet Functions), the current template rule becomes null for the evaluation of that instruction or function.]

The current template rule is not affected by invoking named templates (see 10.1 Named Templates) or named attribute sets (see 10.2 Named Attribute Sets). 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 null.

Note:

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

  • 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.4 Conflict Resolution for Template Rules. That is, it considers all template rules with lower import precedence than the current template rule, plus the template rules that are at the same import precedence that have lower priority than the current template rule, plus the template rules with the same import precedence and priority that occur before the current template rule in declaration order.

    Note:

    As explained in 6.4 Conflict Resolution for Template Rules, a template rule whose match pattern contains multiple alternatives separated by | is treated equivalently to a set of template rules, one for each alternative. This means that where the same item matches more than one alternative, and the alternatives have different priority, it is possible for an xsl:next-match instruction to cause the current template rule to be invoked recursively. This situation does not occur when the alternatives have the same priority.

If no matching template rule is found that satisfies these criteria, the built-in template rule for the context item is used (see 6.7 Built-in Template Rules).

An xsl:apply-imports or xsl:next-match instruction may use xsl:with-param child elements to pass parameters to the chosen template rule (see 9.8 Setting Parameter Values). It also passes on any tunnel parameters as described in 10.1.2 Tunnel Parameters.

[ERR XTDE0560] It is a non-recoverable dynamic error if xsl:apply-imports or xsl:next-match is evaluated when the current template rule is null.

Example: Using xsl:apply-imports

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 or 2.1 processor, but can be used to define fallback behavior when the stylesheet is processed by an XSLT 1.0 processor with forwards compatible behavior.

6.9 Passing Parameters to 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.

[ERR XTDE0700] It is a non-recoverable dynamic error if a template that is invoked using xsl:apply-templates, xsl:apply-imports, or xsl:next-match declares a template parameter with required="yes" and no value for this parameter is supplied by the calling instruction. The same error is reported in the case of a tunnel parameter whether invoked using one of these three instructions or by xsl:call-template, as explained in 10.1.2 Tunnel Parameters.

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

7 Repetition

XSLT offers two constructs for processing each item of a sequence: xsl:for-each and xsl:iterate.

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.

7.1 The xsl:for-each instruction

<!-- Category: instruction -->
<xsl:for-each
  select = expression >
  <!-- Content: (xsl:sort*, sequence-constructor) -->
</xsl:for-each>

The xsl:for-each instruction processes each item in a sequence of items, evaluating the sequence constructor within the xsl:for-each instruction once for each item in that sequence.

The select attribute is required; it contains an expression which is evaluated to produce a sequence, called the input sequence. If there is an xsl:sort element present (see 13 Sorting) the input sequence is sorted to produce a sorted sequence. Otherwise, the sorted sequence is the same as the input sequence.

The xsl:for-each instruction contains a sequence constructor. The sequence constructor is evaluated once for each item in the sorted sequence, with the focus set as follows:

  • The context item is the item being processed.

  • The context position is the position of this item in the sorted sequence.

  • The context size is the size of the sorted sequence (which is the same as the size of the input sequence).

For each item in the input sequence, evaluating the sequence constructor produces a sequence of items (see 5.7 Sequence Constructors). These output sequences are concatenated; if item Q follows item P in the sorted sequence, then the result of evaluating the sequence constructor with Q as the context item is concatenated after the result of evaluating the sequence constructor with P as the context item. The result of the xsl:for-each instruction is the concatenated sequence of items.

Example: Using xsl:for-each

For example, given an XML document with this structure

<customers>
  <customer>
    <name>...</name>
    <order>...</order>
    <order>...</order>
  </customer>
  <customer>
    <name>...</name>
    <order>...</order>
    <order>...</order>
  </customer>
</customers>

the following would create an HTML document containing a table with a row for each customer element

<xsl:template match="/">
  <html>
    <head>
      <title>Customers</title>
    </head>
    <body>
      <table>
        <tbody>
          <xsl:for-each select="customers/customer">
            <tr>
              <th>
                <xsl:apply-templates select="name"/>
              </th>
              <xsl:for-each select="order">
                <td>
                  <xsl:apply-templates/>
                </td>
              </xsl:for-each>
            </tr>
          </xsl:for-each>
        </tbody>
      </table>
    </body>
  </html>
</xsl:template>

7.2 The xsl:iterate instruction

<!-- Category: instruction -->
<xsl:iterate
  select = expression >
  <!-- Content: (xsl:param*, sequence-constructor, xsl:on-completion?) -->
</xsl:iterate>

<!-- Category: instruction -->
<xsl:next-iteration>
  <!-- Content: (xsl:with-param*) -->
</xsl:next-iteration>

<!-- Category: instruction -->
<xsl:break>
  <!-- Content: (sequence-constructor) -->
</xsl:break>

<xsl:on-completion>
  <!-- Content: (sequence-constructor) -->
</xsl:on-completion>

The select attribute is required; it contains an expression which is evaluated to produce a sequence, called the input sequence.

The sequence constructor contained in the xsl:iterate instruction is evaluated once for each item in the input sequence, in order, or until the loop exits by evaluating an xsl:break instruction, whichever is earlier. Within the sequence constructor that forms the body of the xsl:iterate instruction, the context item is set to each item from the value of the select expression in turn; the context position reflects the position of this item in the input sequence, and the context size is the number of items in the input sequence (which may be greater than the number of iterations, if the loop exits prematurely using xsl:break).

Note:

If xsl:iterate is used in conjunction with xsl:stream to achieve streaming, calls on the function lastFO will be disallowed.

The effect of xsl:next-iteration is to cause the iteration to continue by processing the next item in the input sequence, potentially with different values for the iteration parameters. The effect of xsl:break is to cause the iteration to finish, whether or not all the items in the input sequence have been processed. In both cases the affected iteration is the one controlled by the innermost ancestor xsl:iterate element.

The instructions xsl:next-iteration and xsl:break are allowed only as descendants of an xsl:iterate instruction, and only in a tail position within the sequence constructor forming the body of the xsl:iterate instruction.

[Definition: An instruction J is in a tail position within a sequence constructor SC if it satisfies one of the following conditions:]