The presentation of this document has been augmented to identify changes from a previous version. Three kinds of changes are highlighted: new, added text, changed text, and deleted text.


W3C

XSL Transformations (XSLT) Version 2.0

W3C Working Draft 2 May 2003

This version:
http://www.w3.org/TR/2003/WD-xslt20-20030502/
Latest version:
http://www.w3.org/TR/xslt20/
Previous versions:
http://www.w3.org/TR/2002/WD-xslt20-20021115/
http://www.w3.org/TR/2002/WD-xslt20-20020816/
http://www.w3.org/TR/2002/WD-xslt20-20020430/
http://www.w3.org/TR/2001/WD-xslt20-20011220/
Editor:
Michael Kay, Software AG <Michael.Kay@softwareag.com>

This document is also available in these non-normative formats: HTML without revision markings and HTML with revision markings.


Abstract

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

XSLT 2.0 is designed to be used in conjunction with XPath 2.0, which is defined in [XPath 2.0]. XSLT shares the same data model as XPath 2.0, which is defined in [Data Model], and it uses the library of functions and operators defined in [Functions and Operators].

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

Status of this Document

This document is a working draft of XSLT 2.0. It is published in order to provide the XSLT user community with a progress report on the evolving language specification. The document is published in two versions: one that highlights changes since the previous published Working Draft, and one without change highlighting.

With this draft, there are no outstanding open issues. All mandatory requirements, and most of the requirements in the "should" and "could" categories, have been satisfied. The Working Group therefore considers it unlikely that future drafts will introduce major changes to the functionality of the language. However, there will still be some tidying up to improve syntactic and semantic consistency, and the Working Group will address any significant concerns that arise from public comments. At this stage, comments on the detail are particularly welcome, whereas comments that question the overall requirements are less likely to be productive.

The amount of change since the November 2002 draft is substantial. A detailed summary of the changes is included at K.2.4 Changes since the November 2002 draft. The most significant changes are:

The specifications for XSLT serialization have been moved to a separate Working Draft, [XSLT and XQuery Serialization], to make it easier for other W3C specifications such as XQuery to reference them.

This remains a draft document and may be updated, replaced, or obsoleted by other documents at any time. It is inappropriate to use W3C Working Drafts as reference material or to cite them as other than "work in progress". While prototype implementations are encouraged, users and vendors are advised that this working draft cannot be regarded as a stable specification.

XSLT 2.0 is a revised version of the XSLT 1.0 Recommendation [XSLT 1.0] published on 16 November 1999. The changes made in this document are intended to meet the requirements for XSLT 2.0 described in [XSLT 2.0 Requirements] and to incorporate fixes for errors that have been detected in XSLT 1.0. A summary of the changes since XSLT 1.0 is included in K Changes from XSLT 1.0.

XSLT 2.0 is designed to be used together with XPath 2.0, which has been developed by the W3C XSL Working Group in collaboration with the XML Query Working Group. The current specification of XPath 2.0 can be found in [XPath 2.0].

Comments on this specification may be sent to public-qt-comments@w3.org; archives of the comments are available. Archives of comments on earlier versions of the specification can be found at http://lists.w3.org/Archives/Public/xsl-editors/. Public discussion of XSL, including XSL Transformations, takes place on the XSL-List mailing list.

The English version of this specification is the only normative version. However, for translations of this document, see http://www.w3.org/Style/XSL/translations.html.

A list of current W3C Recommendations and other technical documents can be found at http://www.w3.org/TR/.

The development of XSLT is undertaken by the XSL Working Group which is now part of the W3C XML Activity.

Patent disclosures relevant to this specification may be found on the XSL Working Group's patent disclosure page at http://www.w3.org/Style/XSL/Disclosures.html.

Table of Contents

1 Introduction
    1.1 What is XSLT?
    1.2 What's new in XSLT 2.0?
2 Concepts
    2.1 Terminology
    2.2 Notation
    2.3 Initiating a Transformation
    2.4 Executing a Transformation
        2.4.1 Push Processing Instructions
        2.4.2 Pull Processing Instructions
        2.4.3 Constructing Sequences
        2.4.4 Constructing Result Trees
    2.5 Maintaining Position: the Focus
    2.6 Parsing and Serialization
    2.7 Extensibility
    2.8 Stylesheets and Schemas
    2.9 Error Handling
3 Stylesheet Structure
    3.1 XSLT Namespace
    3.2 XSLT Media Type
    3.3 Standard Attributes
    3.4 Stylesheet Element
        3.4.1 User-defined Data Elements
    3.5 Simplified Stylesheet Modules
    3.6 Backwards-Compatible Processing
    3.7 Forwards-Compatible Processing
    3.8 Combining Stylesheet Modules
        3.8.1 Stylesheet Inclusion
        3.8.2 Stylesheet Import
    3.9 Embedded Stylesheet Modules
    3.10 Importing Schema Components
4 Data Model
    4.1 Whitespace Stripping
    4.2 Disable Output Escaping
5 Syntactic Constructs
    5.1 Qualified Names
    5.2 Expressions
    5.3 Patterns
    5.4 Unprefixed Names in Expressions and Patterns
    5.5 Attribute Value Templates
    5.6 Sequence Constructors
        5.6.1 Constructing Complex Content
        5.6.2 Constructing Simple Content
        5.6.3 Namespace Fixup
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 Modes
    6.6 Built-in Template Rules
    6.7 Overriding Template Rules
7 Repetition
8 Conditional Processing
    8.1 Conditional Processing with xsl:if
    8.2 Conditional Processing with xsl:choose
9 Variables and Parameters
    9.1 Variables
    9.2 Parameters
    9.3 Values of Variables and Parameters
    9.4 Temporary Trees
    9.5 Global Variables and Parameters
    9.6 Local Variables and Parameters
    9.7 Scope of Variables
    9.8 Circular Definitions
10 Callable Components
    10.1 Named Templates
        10.1.1 Passing Parameters to Templates
    10.2 Named Attribute Sets
    10.3 Stylesheet Functions
        10.3.1 Defining a Stylesheet Function
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 Processing Instructions
    11.6 Creating Namespace Nodes
    11.7 Creating Comments
    11.8 Copying Nodes from a Source Tree to a Result Tree
        11.8.1 Shallow Copy
        11.8.2 Deep Copy
    11.9 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 Collating Sequences
    13.2 The xsl:sort Element
    13.3 Using Unnamed Sort Specifications
    13.4 Using Named Sort Specifications
        13.4.1 Declaring a Named Sort Specification
        13.4.2 Sorting Using a Named Sort Specification
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
15 Regular Expressions
    15.1 Examples of Regular Expression Matching
16 Additional Functions
    16.1 Multiple Source Documents
    16.2 Reading Text Files
    16.3 Keys
        16.3.1 The xsl:key Declaration
        16.3.2 The key Function
    16.4 Number Formatting
        16.4.1 Defining a Decimal Format
        16.4.2 Processing the Picture String
        16.4.3 Analysing the Picture String
        16.4.4 Formatting the Number
    16.5 Formatting Dates and Times
        16.5.1 The date-format declaration
        16.5.2 The Picture String
    16.6 Miscellaneous Additional Functions
        16.6.1 current
        16.6.2 unparsed-entity-uri
        16.6.3 unparsed-entity-public-id
        16.6.4 generate-id
        16.6.5 system-property
17 Messages
18 Extensibility and Fallback
    18.1 Extension Functions
        18.1.1 Testing Availability of Functions
        18.1.2 Calling Extension Functions
        18.1.3 External Objects
    18.2 Extension Instructions
        18.2.1 Designating an Extension Namespace
        18.2.2 Testing Availability of Instructions
        18.2.3 Fallback
19 Result Trees
    19.1 Creating Result Trees
    19.2 Validation
        19.2.1 Validating Constructed Nodes
        19.2.2 Validating Result Trees
20 Serialization
    20.1 Character Maps
    20.2 Disabling Output Escaping
21 Conformance
    21.1 Basic XSLT Processor
    21.2 Schema-Aware XSLT Processor
    21.3 Serialization Feature
    21.4 Backwards Compatibility 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 Schema for XSLT Stylesheets (Non-Normative)
H Acknowledgements (Non-Normative)
I Checklist of Requirements (Non-Normative)
J Summary of Issues (Non-Normative)
    J.1 Open Issues
    J.2 Decided Issues
    J.3 Closed Issues
K Changes from XSLT 1.0 (Non-Normative)
    K.1 Incompatible Changes
        K.1.1 Backwards Compatibility Behavior
        K.1.2 Incompatibility in the Absence of a Schema
        K.1.3 Compatibility in the Presence of a Schema
        K.1.4 XPath 2.0 Backwards Compatibility
    K.2 Changes since XSLT 1.0
        K.2.1 Pervasive changes
        K.2.2 Major Features
        K.2.3 Minor Changes
        K.2.4 Changes since the November 2002 draft


1 Introduction

1.1 What is XSLT?

This specification defines the syntax and semantics of the XSLT 2.0 language. 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 [XML Namespaces 1.0]. 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 Formatting Objects]), or into another presentation-oriented format such as HTML, XHTML, or SVG. However, XSLT is used for a wide range of XML-to-XML transformation tasks, not exclusively for formatting and presentation applications.

A transformation expressed in XSLT describes rules for transforming one or more source trees into one or more result trees. 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, which can be evaluated 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.

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.8.1 Stylesheet Inclusion and 3.8.2 Stylesheet Import .

1.2 What's new in XSLT 2.0?

XSLT 1.0 was published in November 1999, and version 2.0 represents a significant increase in the capability of the language. A detailed list of changes is included in K Changes from XSLT 1.0. XSLT 2.0 has been developed in parallel with XPath 2.0 (see [XPath 2.0]), so the changes to XPath must be considered alongside the changes to XSLT.

2 Concepts

2.1 Terminology

For a full glossary of terms, see B Glossary.

The software responsible for transforming source trees into a result trees 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. A specific product that performs the functions of an XSLT processor is referred to as an implementation .

Note:

The precise meanings of the terms source tree and result tree, as used in this specification, depend on the context. In the context of the stylesheet as a whole, the source trees are the trees provided as the initial input to the transformation, together with any trees supplied as stylesheet parameters and any trees accessed using the document, doc or collection functions; while the result trees are the trees created by an explicit xsl:result-document instruction as well as the implicit result tree created in the absence of an xsl:result-document instruction. In the context of an individual instruction in the stylesheet, the term source tree also includes any temporary tree that the instruction is using for input, and the term result tree includes any temporary tree that the instruction is using for output.

In this specification the words must, must not, should, should not, may, required, and recommended are to be interpreted as described in [RFC2119]. Where the word must 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 21 Conformance. Where the word must relates to a stylesheet, then the processor must enforce this constraint on stylesheets.

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 should be described in the vendor's documentation.

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.

Paragraphs labeled as Notes or described as examples are non-normative.

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

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

  • The term string value is defined in [Data Model]. 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.

2.2 Notation

In this document the specification of each XSLT-defined element type 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 is required if and only if its name is in bold.

  • The string that occurs in the place of an attribute value specifies the allowed values of the attribute. If this is surrounded by curly braces, then the attribute value is treated as an attribute value template, and the string occurring within curly braces 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.

    In all cases where this specification limits the set of values that an attribute may take, 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.

 

The following example illustrates the notation.

<!-- Category: instruction -->
<xsl:example-element
  select = sequence-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 braces 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.

 

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

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

Note:

This working draft includes a non-normative XML Schema for XSLT stylesheet modules: see F Schema for XSLT Stylesheets. However, it has been decided to retain the syntax summaries in their present form as these are thought to be easier to read.

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

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 must be supplied when a transformation is initiated.

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:

  • An identification of the stylesheet module that is to act as the principal stylesheet module for the transformation. The complete stylesheet is assembled by expanding the xsl:import and xsl:include declarations in the principal stylesheet module, as described in 3.8.1 Stylesheet Inclusion and 3.8.2 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.

  • A set of nodes (possibly empty) that forms the initial input sequence. These nodes (which will often be document nodes, but may in principle be any kind of node, from the same or different documents) are available at any time during the transformation as the result of the input function described in [Functions and Operators].

  • A node that acts as the initial context node for the transformation. This node is accessible within the stylesheet as the initial value of the XPath expressions . and self::node(), as described in 2.5 Maintaining Position: the Focus . If no initial context node is supplied, then the context item, context position, and context size will initially be unset, and the evaluation of any expression that references these values will result in a dynamic error. If no initial context node is supplied explicitly, then the stylesheet is invoked with an initial context node in the form of a document node with no children.

    Note:

    It is not necessary for the initial context node to be a member of the initial input sequence, but in a simple transformation of a single document, it is convenient to set both the initial input sequence and the initial context node to the document node of the source document to be transformed.

  • 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 node, according to the rules defined in 6.4 Conflict Resolution for Template Rules. Either a named template, or an initial context node, or both, must be supplied.

  • Optionally, an initial mode. If an initial mode is supplied, then in searching for the template rule that best matches the initial context node, the processor considers only those rules that apply to the initial mode. If no initial mode is supplied, the default mode is used.

  • A base output URI, that is, a URI to be used as the base URI when resolving a relative URI allocated to a result tree. If the transformation generates multiple result trees, then typically each one will be allocated a URI relative to this base URI.

[ERR004] It is a dynamic error if the invocation of the stylesheet specifies a template name that does not match the expanded-QName of a named template defined in the stylesheet.

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 for processing the initial context node in the initial mode, selected according to the rules used by the xsl:apply-templates instruction. If the result of evaluating the initial template is a non-empty sequence, then this sequence is used to construct an implicit result tree, following the rules described in 5.6.1 Constructing Complex Content: the effect is as if the sequence constructor contained in the initial template were contained in an xsl:result-document element with no attributes.

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. [ERR005] It is a dynamic error if the initial template defines a template parameter that specifies required="yes". The processor must signal the error.

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, doc or collection described in [Functions and Operators], or they can be supplied as stylesheet parameters (see 9.5 Global Variables and Parameters), or as the result of an extension function (see 18.1 Extension Functions

2.4 Executing a Transformation

The XSLT instructions used to control a transformation can be divided into two groups: push processing instructions, which use template rules to define the processing associated with different nodes in a source tree, and pull processing instructions, which allow the selection and processing of source tree nodes to be described together. These two groups of instructions are described in the following sections.

2.4.1 Push Processing Instructions

A stylesheet generally contains a set of template rules. A template rule has two parts: a pattern which is matched against nodes in a source tree and a sequence constructor which is evaluated to produce a sequence of items. In most cases these items are nodes, which are then written to a result tree.

A template rule that is selected to process a particular node in the source tree will commonly write one or more nodes to the result tree, and will frequently use the xsl:apply-templates instruction to select other nodes in the source tree (often, but not invariably, the original node's children) for processing. Each of these selected nodes is processed by searching the stylesheet for a matching template rule. Sometimes all the selected nodes will be processed by the same template rule, but in general different nodes will be processed by different template rules. Either way, the chosen template rules are evaluated and the process repeats itself, typically resulting in a recursive traversal of the source tree.

Because the template rule that is written to process one node in the tree has no knowledge of which rules will be chosen to process the nodes that it selects, push processing allows a stylesheet to be applicable to a wide class of documents that have similar source tree structures.

Frequently, the first action of the stylesheet is to find the template rule that matches the document node of a source tree. This initial template may create the document node of a new result tree explicitly by using the xsl:result-document instruction; if it does not do so, the system implicitly creates the document node of a new result tree. The sequence constructor of this template rule then creates the children of the new document node. By the time evaluation of this sequence constructor is complete, these children will typically each act as the parent of further result nodes, so a complete tree is constructed.

In the process of finding a template rule to process a particular node, more than one template rule may have a pattern that matches the node. However, only one template rule will be applied. The method for deciding which template rule to apply is described in 6.4 Conflict Resolution for Template Rules. If there is no template rule that matches the node, a built-in template rule is used (see 6.6 Built-in Template Rules).

 

For example, suppose the source tree contains the structure below:

<doc>
  <val>1</val>
  <val>2</val>
  <val>3</val>
</doc>

If the context node is the doc element, and the xsl:apply-templates instruction is evaluated with the attribute select="*", then the input sequence will contain the three val elements. Suppose the template rule that matches a val element has the following form:

<xsl:template match="val">
<li><xsl:value-of select="."/></li>
</xsl:template>

This template rule will be evaluated once for each val element in the input sequence, and in each case it will return a new li element, which in turn will contain a single text node. The result of the xsl:apply-templates instruction will therefore be a sequence of three li elements. The following XML fragment will be generated:

  <li>1</li>
  <li>2</li>
  <li>3</li>

This fragment will be added to the result tree at the point where the doc element was being processed.

 

Very often, the template rule that matches one element in the source tree will contain an xsl:apply-templates instruction selecting the children of that element as the input sequence for processing. In this situation, each child node will be processed to create a subtree, and these subtrees will be added as children of the element produced by the parent template rule. The structure of the result tree will then correspond directly to the structure of the source tree.

 

For example, suppose that the doc element in the previous example is processed using the template rule below:

<xsl:template match="doc">
<ol><xsl:apply-templates select="*"/></ol>
</xsl:template>

Then the result of processing the doc element will be the following result tree:

<ol>
  <li>1</li>
  <li>2</li>
  <li>3</li>
</ol>
 

2.4.2 Pull Processing Instructions

A single template rule by itself has considerable power. It can create structures of arbitrary complexity; it can pull string values out of arbitrary locations in the source tree; and it can generate structures that are repeated according to the occurrence of nodes in the source tree.

A stylesheet that uses the pull processing technique is written to navigate explicitly around the source tree, accessing data from wherever it appears in order to construct nodes in the result tree. A number of XSLT instructions are provided to assist pull processing: notably xsl:for-each, xsl:choose, xsl:if, and xsl:call-template.

For simple transformations where the structure of the result tree is independent of the structure of the source tree, a stylesheet can often consist of only a single literal result element, containing a sequence constructor which functions as a template for building the complete result tree. Transformations on XML documents that represent data with a regular and predictable structure (for example, data extracted from a relational database) are often of this kind. XSLT allows a simplified syntax for such stylesheets (see 3.5 Simplified Stylesheet Modules).

2.4.3 Constructing Sequences

Whether the stylesheet is written to use push processing or pull processing, nodes in the result tree are always generated using sequence constructors. Each level of the tree is constructed in a two-stage process. First, a sequence constructor is evaluated to produce a sequence of items. Second, this sequence of items is used to form the children (and attributes and namespaces) of a new element or document node.

A sequence constructor is a sequence of instructions, which appear as sibling nodes in the stylesheet, and which are evaluated to create a sequence of items.

A sequence constructor can contain elements (called literal result elements) and text nodes that are copied directly into the result sequence. A sequence constructor can also contain elements from the XSLT namespace that are instructions for creating parts of the result sequence.

The sequence produced by evaluating a sequence constructor is most commonly used to form the child nodes (and attributes and namespaces) of a new element or document node, as described in 2.4.4 Constructing Result Trees. But it is also possible to manipulate the value returned by a sequence constructor directly. This is generally done by binding a variable to the value, as described in 9.1 Variables. It is possible for such a sequence to contain elements, attributes, or other nodes that have no parent.

An instruction is defined as an element that can appear in a sequence constructor and that is either in the XSLT namespace, or in a namespace designated as an extension namespace.

Instructions that select nodes from a source document, or that derive information from these nodes for inclusion in the result document, always access the source tree by means of an expression in the XPath language, described in [XPath 2.0]. A stylesheet written to use XSLT 2.0 will contain expressions whose syntax and semantics are defined by XPath 2.0 (but see also 3.6 Backwards-Compatible Processing and 3.7 Forwards-Compatible Processing).

2.4.4 Constructing Result Trees

The result of evaluating a sequence constructor is an arbitrary sequence of items, which may include both nodes and atomic values. When a sequence constructor appears as the content of an instruction that creates an element or document node, then the sequence of items created by the sequence constructor is used to form the children, attributes and namespaces of the new element or document node. During this process, any sequence of consecutive atomic values is first converted to a text node by casting each atomic value to a string, and inserting a single space between successive strings to form the string value of the text node. Any adjacent text nodes in the sequence are then merged.

Technically, each node appearing in the value returned by a sequence constructor is copied, together with all its children, attributes, and namespaces, when it is attached to a parent element or document node. In practice, it is only necessary to make a physical copy when the original node is accessible independently of its new parent, for example when it is part of a sequence that has been bound to a variable.

The order of the child nodes in the result tree corresponds to their order in the sequence, which itself depends on the stylesheet order of the instructions that created them. In the case of attribute or namespace nodes, the new nodes become attributes or namespaces of the element under construction.

The process of constructing a result tree is described in more detail in 5.6.1 Constructing Complex Content.

2.5 Maintaining Position: the Focus

When a sequence constructor is evaluated, the processor keeps track of which nodes 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:

  • 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), or a node. The context item is initially set to the initial context node 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).

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

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

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, there is no context node: its value is an empty sequence. The context node is returned by the XPath expression self::node(), and it is used as the starting node for all relative path expressions.

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 . this is unaffected by changes to the context item that occur within the XPath expression. The current function is described in 16.6.1 current.

On completion of an instruction which 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 node supplied. [ERR006] When the focus is undefined, evaluation of any expression that references the context item, context position, or context size results in a dynamic error. The processor must signal the error.

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.

Sometimes the focus is based on a single node. A singleton focus based on a node N has the context item (and therefore the context node) set to N, and the context position and context size both set to 1 (one).

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

As with the focus, these variables are not accessible within a stylesheet function unless they have been initialized within that function.

2.6 Parsing and Serialization

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

The stylesheet does not describe how a source tree is constructed. 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 the 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 [DOM2]). 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 XPath 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.

A frequent requirement is to output a 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 a declaration (the xsl:output element, see 20 Serialization) which allows a stylesheet to specify the desired properties of a serialized output file. Implementations that do not serialize result trees are allowed to ignore this declaration.

Because it is a common requirement to perform a transformation on a document while retaining lexical characteristics such as CDATA section boundaries, entity references, and the like, a non-normative appendix to this specification (see G Representation of Lexical XML Constructs) describes a way in which these constructs can be represented within the data model by means of elements in a special namespace. If such a representation is chosen, the tree is transformed in the same way as any other tree. The process of constructing such a tree is something that happens before XSLT transformation starts, and the process of interpreting such a tree and reconstituting the lexical representation is part of the serialization process. Neither of these processes is properly within the scope of XSLT transformation, and therefore, this specification places no requirement on an XSLT processor to support this representation of lexical properties.

2.7 Extensibility

XSLT provides two hooks for extending the language, one hook for extending the set of instruction elements used in sequence constructors and one hook for extending the set of functions used in XPath expressions. These hooks are both based on XML namespaces: see 18 Extensibility and Fallback for further details. Extension instructions and extension functions defined according to these rules may be provided by the implementor of the XSLT processor, and the implementor 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.

2.8 Stylesheets and Schemas

An XSLT stylesheet can make use of information from XML Schemas, as defined in [XML 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 raw 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).

The conformance rules for XSLT 2.0, defined in 21 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 usually work unchanged with a schema-aware XSLT processor; however, the fact that a source document has been processed using a schema processor and has been annotated with type information affects the outcome of certain operations such as sorting.

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

There are places within a stylesheet, and within XPath expressions and patterns in a stylesheet, where the names of schema-defined elements, attributes, and named types appear. For example, it is possible to declare the types expected for the parameters of a function. The element, attribute, and type names that appear in such contexts must either be built-in schema types (for example xs:string or xs:integer), or they must be user-defined types that are made accessible to the XSLT processor by means of an xsl:import-schema declaration: see 3.10 Importing Schema Components.

It is only necessary to import a schema explicitly if its type definitions are mentioned statically 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.

Further, 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 the result tree just as much as for nodes in source documents. It is possible to make assertions about the types of input document by means of tests within the stylesheet. For example:

 
<xsl:template match="document-node(element(my:invoice))" priority="2">
. . .
</xsl:template>

<xsl:template match="document-node()" priority="1">
  <xsl:message terminate="yes">Source document is not an invoice</xsl:message>
</xsl:template>

This example will cause the transformation to fail with an error message if the source document has not been successfully validated and annotated with type my:invoice.

 

A stylesheet can also control the types of nodes that it constructs in a final result tree, or in temporary trees. In the case of temporary trees, this enables the tree to be processed in the same way as a source document that has undergone schema assessment. In the case of a final result tree, it enables the result tree to be passed to further processes (including further XSLT transformations) with its type information intact.

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, and if it does perform such checking, any errors signaled are advisory only: the user must be given the option to use the stylesheet even if static analysis has revealed type errors.

Type annotations can be created in nodes of a result tree, or of a temporary tree, in a number of ways.

  • It is possible to request explicit validation of a complete result tree. Validation is either strict or lax, and is performed according to the rules defined in [XML Schema]. If validation of a result tree fails (strictly speaking, if the outcome of the validity assessment is invalid), then the transformation fails, but if it succeeds, the element and attribute nodes of the tree will be annotated with the names of the schema-defined types to which these nodes conform. These 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 or attributes are copied, either explicitly using the xsl:copy or xsl:copy-of, 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.

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

2.9 Error Handling

An error that is 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 result tree.

There is an exception to this rule when the stylesheet specifies forwards-compatible behavior (see 3.7 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.

An error that is not detected until a source document is being transformed is referred to as a dynamic error. 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 implementation does choose to take recovery action, it must take the recovery action defined 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 is also allowed to take other action, such as logging a warning message.

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 result tree 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 can 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.8 Circular Definitions.

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 as a dynamic error. An implementation may also, optionally, signal a type error 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.

For example, the following construct contains a type error, because 42 is not allowed as an operand of the xsl:apply-templates instruction. 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:apply-templates select="42"/>
</xsl:if>

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

If a transformation has successfully produced a 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. As with other aspects of serialization, the handling of serialization errors is implementation-defined: see 20 Serialization.

3 Stylesheet Structure

A stylesheet consists of one or more stylesheet modules, each one forming all or part of a well-formed XML document.

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 a source document that is to be processed using the stylesheet. 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.9 Embedded Stylesheet Modules).

3.1 XSLT Namespace

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

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.4 Stylesheet Element and 3.5 Simplified Stylesheet Modules).

XSLT processors must use the XML namespaces mechanism [XML Namespaces 1.0] 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 18.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.

An element from the XSLT namespace may have any attribute not from the XSLT namespace, provided that the expanded-QName (see [XPath 2.0]) of the attribute has a non-null namespace URI. The presence of such attributes must not change the behavior of XSLT elements and functions defined in this document or in the XPath specification, though they may be used to modify the behavior of extension functions and extension instructions. Thus, an implementation is always free to ignore such attributes, and must ignore such attributes without giving an error if it does not recognize the namespace URI. Such attributes can provide, for example, unique identifiers, optimization hints, or documentation. The set of namespaces that are recognized for such attributes is implementation-defined.

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.

 

For example, 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.

 

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

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 however, are regarded as single words and are capitalized exactly as in XML Schema. This sometimes leads to composite function names such as current-dateTime.

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 this section, is reserved.

  • The standard function namespace http://www.w3.org/2003/05/xpath-functions is used for functions in the core function library, defined in [Functions and Operators].

  • The standard operator namespace http://www.w3.org/2002/08/xquery-operators is used for functions that underpin XPath operators, defined in [Functions and Operators].

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

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

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

  • The XPath datatypes namespace http://www.w3.org/2003/05/xpath-datatypes is used as defined in [Functions and Operators] . In a stylesheet this namespace may be used to refer to the types xdt:untypedAtomic, xdt:yearMonthDuration, xdt:dayTimeDuration, xdt:anyAtomicType, and to the constructor functions associated with the first three of these types.

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

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

[ERR008] 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 named sort specification, a decimal-format, a date-format, a variable or parameter, a stylesheet function, a named output definition, or a character map.

Implementations may reserve additional namespaces for use by the implementation, provided they follow accepted practice to avoid naming collisions. The set of such namespaces is implementation-defined.

Future versions of this specification may reserve additional namespaces starting with http://www.w3.org/.

3.2 XSLT Media Type

A media type will be registered for XSLT stylesheet modules.

Note:

It is expected that this media type will be application/xslt+xml as forecast in section 8.17 of [RFC3023].

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

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

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

It is recommended that these attributes should also be permitted on extension instructions, but this is at the discretion of the implementor 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, and any descendant elements of the element they appear on, together with attributes of those descendant elements. 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 and [xsl:]xpath-default-namespace the value can be overridden by a different value for the same attribute appearing on a descendant element. The effective value of the attribute for a particular stylesheet element is determined by the innermost containing element on which the attribute appears. Note however that the version attribute on the xsl:output element serves an entirely different purpose.

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.

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 description of the xsl:stylesheet and xsl:transform elements only. This reflects the fact that these attributes are often used on the xsl:stylesheet element, 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:

3.4 Stylesheet Element

<xsl:stylesheet
  id = id
  extension-element-prefixes = tokens
  exclude-result-prefixes = tokens
  version = number
  xpath-default-namespace = uri
  default-validation = "strict" | "lax" | "preserve" | "strip">
  <!-- 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 = "strict" | "lax" | "preserve" | "strip">
  <!-- 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.

[ERR009] An xsl:stylesheet element must have a version attribute, indicating the version of XSLT that the stylesheet requires. [ERR010] The value of the version attribute must be a number (specifically, it must be a DecimalLiteral as defined in [XPath 2.0].) For this version of XSLT, the value should normally be 2.0. A value of 1.0 indicates that the stylesheet was written with the intention that it should be processed using an XSLT 1.0 processor. [ERR011] It is a static error to submit to an XSLT 2.0 processor a stylesheet that specifies version="1.0" in the xsl:stylesheet element of the principal stylesheet module, or in the xsl:version attribute of the outermost element in the case of a simplified stylesheet module. This is a recoverable error. The processor may signal the error, or may recover by processing the stylesheet with backwards-compatible processing behavior enabled (see 3.6 Backwards-Compatible Processing).

When the value of the version attribute is greater than 2.0, forwards-compatible behavior is enabled (see 3.7 Forwards-Compatible Processing).

Note:

XSLT 1.0 allowed the [xsl:]version attribute to take any numeric value, and specified that if the value was not equal to 1.0, the stylesheet would be executed in forwards compatible mode. XSLT 2.0 continues to allow the attribute to take any unsigned decimal value. A software product that includes both an XSLT 1.0 processor and an XSLT 2.0 processor (or that can execute as either) may use the [xsl:]version attribute to decide which processor to invoke; such behavior is outside the scope of this specification. When the stylesheet is executed with an XSLT 2.0 processor, the value 1.0 is taken to indicate that the stylesheet was written with XSLT 1.0 in mind: if this value appears on the outermost element of the principal stylesheet module then an XSLT 2.0 processor must either reject the stylesheet or execute it in backwards compatible mode, as described above. Setting version="2.0" indicates that the stylesheet is to be executed with neither backwards nor forwards compatible behavior enabled. Any other value less than 2.0 enables backwards compatible behavior, while any value greater than 2.0 enables forwards compatible behavior.

When developing a stylesheet that is designed to execute under either XSLT 1.0 or XSLT 2.0, the recommended practice is to create two separate entry modules, one specifying version="1.0", and the other specifying version="2.0"; these entry modules can use xsl:include or xsl:import to incorporate the common code. Subsidiary stylesheet modules should specify version="2.0" if they make use of XSLT 2.0 facilities, and version="1.0" otherwise.

The default-validation attribute defines the default value of the validation attribute of all 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 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. For details of the effect of this attribute, see 19.2 Validation.

[ERR012] An xsl:stylesheet element must have no text node children, other than text nodes consisting entirely of whitespace.

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

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.4.1 User-defined Data Elements)

The xsl:stylesheet element may contain the following types of declaration:

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. The ordering of these elements does not affect the results of the transformation unless there are conflicting declarations (for example, two template rules with the same priority that match the same node). In general, it is an error for a stylesheet to contain such conflicting declarations, but in some cases the processor is allowed to recover from the error by choosing the declaration that appears last in the stylesheet.

3.4.1 User-defined Data Elements

In addition to declarations, the xsl:stylesheet element may contain 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. [ERR013] It is a static error if the xsl:stylesheet element has a child element having a null namespace URI.

An implementation may attach meaning to user-defined data elements that appear in a namespace controlled by the vendor. 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. 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. The set of namespaces that are recognized for such data elements is implementation-defined.

User-defined data elements can provide, for example,

[ERR014] A user-defined data element must not precede an xsl:import element within a stylesheet module.

3.5 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. Such a stylesheet is equivalent to a standard stylesheet module whose xsl:stylesheet element contains a template rule containing the literal result element; the template rule has a match pattern of /.

For example:

<html xsl:version="2.0"
      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.0"
                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>

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.0"
                xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

<xsl:template na