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.

The baseline for changes is the publication dated 11 May 2010.


W3C

XSL Transformations (XSLT) Version 3.0

W3C Working Draft 10 July 2012

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

See also translations.


Abstract

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

XSLT 3.0 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. Another important aim is to improve the modularity of large stylesheets, allowing stylesheets to be developed from independently-developed components with a high level of software engineering robustness.

XSLT 3.0 is designed to be used in conjunction with XPath 3.0, which is defined in [XPath 3.0]. XSLT shares the same data model as XPath 3.0, which is defined in [Data Model], and it uses the library of functions and operators defined in [Functions and Operators]. XPath 3.0 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-dateFO30 and format-numberFO30 functions, are now defined in the standard function library to make them available to other host languages.

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

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 XP30 for XPath 3.0, DM30 for the XDM data model version 3.0, FO30 for Functions and Operators version 3.0.

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 at http://www.w3.org/TR/.

This is a 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 3.0] 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.

In particular, this document proposes changes to the XDM data model and to XPath language syntax to underpin the introduction of maps, which have been found necessary to support some XSLT streaming use cases and make many other processing tasks easier. These changes have not yet been accepted by other Working Groups with an interest in XPath and the XDM data model.

There are a number open issues in this draft, flagged in the text and summarized at I Summary of Open Issues. Feedback from readers on these issues 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 "[XSLT30]" 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 group; that page also includes 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 and K Changes since the Working Draft of 11 May 2010.

Table of Contents

1 Introduction
    1.1 What is XSLT?
    1.2 What's New in XSLT 3.0?
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 Packages and Modules
    2.8 Extensibility
    2.9 Stylesheets and XML Schemas
    2.10 Streaming
    2.11 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 Packages
        3.6.1 Dependencies between Packages
        3.6.2 Named Components in Packages
            3.6.2.1 Visibility of Components
            3.6.2.2 Visibility of Declarations
            3.6.2.3 Exposing Components
            3.6.2.4 Accepting Components
            3.6.2.5 Overriding Named Components from a Used Package
            3.6.2.6 Binding References to Components
        3.6.3 Overriding Template Rules from a Used Package
        3.6.4 Declarations Local to a Package
        3.6.5 Using an XQuery Library Package
    3.7 Stylesheet Modules
    3.8 Stylesheet Element
        3.8.1 The default-collation attribute
        3.8.2 The default-mode attribute
        3.8.3 User-defined Data Elements
    3.9 Simplified Stylesheet Modules
    3.10 Backwards Compatible Processing
        3.10.1 XSLT 1.0 compatibility mode
        3.10.2 XSLT 2.0 compatibility mode
    3.11 Forwards Compatible Processing
    3.12 Combining Stylesheet Modules
        3.12.1 Locating Stylesheet Modules
        3.12.2 Stylesheet Inclusion
        3.12.3 Stylesheet Import
    3.13 Embedded Stylesheet Modules
    3.14 Conditional Element Inclusion
    3.15 Built-in Types
    3.16 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 Lexical 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: Text-only Copy
        6.7.2 Built-in Templates: Deep Copy
        6.7.3 Built-in Templates: Shallow Copy
        6.7.4 Built-in Templates: Deep Skip
        6.7.5 Built-in Templates: Shallow Skip
        6.7.6 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 Conditional Creation of Literal Result Elements
        11.1.5 Namespace Aliasing
    11.2 Creating Element Nodes Using xsl:element
        11.2.1 The Content of the Constructed Element Node
        11.2.2 The Name of the Constructed Element Node
        11.2.3 Other Properties of the Constructed Element Node
        11.2.4 The Type Annotation of the Constructed Element Node
        11.2.5 Conditional Construction of Element Nodes
    11.3 Creating Attribute Nodes Using xsl:attribute
        11.3.1 Setting the Type Annotation for a Constructed Attribute Node
        11.3.2 Conditional Creation of Attribute Nodes
    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.1.1 Conditional Copying of Elements
        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 xsl:for-each-group Element
    14.2 Accessing Information about the Current Group
        14.2.1 fn:current-group
        14.2.2 fn:current-grouping-key
    14.3 Ordering among Groups
    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 Streamable Merging
    15.5 Defining the merge keys
    15.6 The xsl:merge-action element
    15.7 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 fn:regex-group
    17.3 Examples of Regular Expression Matching
18 Accumulators
    18.1 Declaring an accumulator
    18.2 Informal Model for Accumulators
    18.3 Formal Model for Accumulators
    18.4 Examples of Accumulators
19 Streaming
    19.1 The xsl:stream instruction
        19.1.1 Examples of xsl:stream
    19.2 Streamable Templates
    19.3 Streamability Analysis
        19.3.1 Syntactic Context
        19.3.2 General Rules for Streamability
        19.3.3 Classifying Sequence Constructors
        19.3.4 Classifying Instructions
        19.3.5 Classifying Attribute Sets
        19.3.6 Classifying Attribute Value Templates
        19.3.7 Classifying Expressions
        19.3.8 Incrementally consuming expressions
        19.3.9 Inherited attribute expressions
        19.3.10 Classifying Patterns
    19.4 fn:copy-of
    19.5 fn:snapshot
    19.6 fn:point-copy
    19.7 fn:attributes
    19.8 fn:look-ahead
20 Additional Functions
    20.1 fn:document
    20.2 Keys
        20.2.1 The xsl:key Declaration
        20.2.2 fn:key
    20.3 Defining a Decimal Format
    20.4 Miscellaneous Additional Functions
        20.4.1 fn:current
        20.4.2 fn:unparsed-entity-uri
        20.4.3 fn:unparsed-entity-public-id
        20.4.4 system-property
21 XPath Extensions
    21.1 Maps
        21.1.1 The Type of a Map
        21.1.2 Functions that operate on Maps
            21.1.2.1 map:new
            21.1.2.2 map:collation
            21.1.2.3 map:keys
            21.1.2.4 map:contains
            21.1.2.5 map:get
            21.1.2.6 map:entry
            21.1.2.7 map:remove
            21.1.2.8 fn:deep-equal2
        21.1.3 Map Expressions
        21.1.4 Examples using Maps
    21.2 Processing JSON Data
        21.2.1 fn:parse-json
        21.2.2 fn:serialize-json
        21.2.3 Example: Converting JSON to Custom XML
22 Diagnostics
    22.1 Messages
    22.2 Assertions
23 Extensibility and Fallback
    23.1 Extension Functions
        23.1.1 fn:function-available
        23.1.2 Calling Extension Functions
        23.1.3 External Objects
        23.1.4 fn:type-available
    23.2 Extension Instructions
        23.2.1 Designating an Extension Namespace
        23.2.2 fn:element-available
        23.2.3 Fallback
24 Final Result Trees
    24.1 Creating Final Result Trees
    24.2 Validation
        24.2.1 Validating Constructed Elements and Attributes
            24.2.1.1 Validation using the [xsl:]validation Attribute
            24.2.1.2 Validation using the [xsl:]type Attribute
            24.2.1.3 The Validation Process
        24.2.2 Validating Document Nodes
25 Serialization
    25.1 Character Maps
    25.2 Disabling Output Escaping
26 Conformance
    26.1 Basic XSLT Processor
    26.2 Schema-Aware XSLT Processor
    26.3 Serialization Feature
    26.4 Compatibility Features
    26.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)
    J.1 Changes in this Specification
    J.2 Changes in Other Related specifications
K Changes since the Working Draft of 11 May 2010 (Non-Normative)
L Incompatibilities with XSLT 2.0 (Non-Normative)


1 Introduction

1.1 What is XSLT?

This specification defines the syntax and semantics of the XSLT 3.0 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.

Note:

The use of the term tree in this document does not imply the use of a data structure in memory that holds the entire contents of the document at one time. It implies rather a logical view of the XML input and output in which elements have a hierarchic relationship to each other. When a source document is being processed in a streaming manner, access to the nodes in this tree is constrained, but it is still viewed and described as a tree.

A stylesheet has a modular structure. It may consist of one or more packages developed independently of each other; each package defines the services (functions, templates, etc) that it exposes to its clients. Internally, a package may consist of a number of stylesheet modules.

[Definition: For a given transformation, one stylesheet module 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.12.2 Stylesheet Inclusion and 3.12.3 Stylesheet Import.]

1.2 What's New in XSLT 3.0?

A major focus for enhancements in XSLT 3.0 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.

  • Accumulators, which allow a value to be computed progressively during streamed processing of a document, and accessed as a function of a node in the document, without compromise to the functional nature of the XSLT language.

A second focus for enhancements in XSLT 3.0 is the introduction of a new mechanism for stylesheet modularity, called the package. Unlike the stylesheet modules of XSLT 1.0 and 2.0 (which remain available), a package defines an interface that regulates which functions, variables, templates and other components are visible outside the package, and which can be overridden. There are two main goals for this facility: it is designed to deliver software engineering benefits by improving the reusability and maintainability of code, and it is intended to streamline stylesheet deployment by allowing packages to be compiled independently of each other, and compiled instances of packages to be shared between multiple applications.

Other significant features in XSLT 3.0 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.

  • A new instruction xsl:assert to assist developers in producing correct and robust code.

XSLT 3.0 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 parse-xmlFO30 and serializeFO30 to convert between lexical and tree representations of XML.

This Working Draft includes support for maps (a data structure consisting of key/value pairs, sometimes referred to in other programming languages as dictionaries, hashes, or associative arrays). This feature extends the data model, provides new syntax in XPath, and adds a number of new functions and operators. The XSL Working Group intends that these changes should eventually become part of XPath: however, this has not yet been agreed with all interested parties.

The XSL Working Group is designing other new features which it hopes to include in the final XSLT 3.0 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 25 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, docFO30, and collectionFO30, 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 26 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 3.0] or the XDM specification [Data Model]. Particular attention is drawn to the following:

  • [Definition: The term atomization is defined in Section 2.4.2 Atomization XP30. 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 Accessor DM30. 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 Accessor DM30. Every node has a string value. For example, the string value of an element is the concatenation of the string values of all its descendant text nodes.]

  • [Definition: The term XPath 1.0 compatibility mode is defined in Section 2.1.1 Static Context XP30. 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 3.0 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.

    The types used are as follows:

    Type name Meaning
    string Any string
    expression An XPath expression
    pattern A pattern as described in 5.5 Patterns.
    sequence-type A SequenceTypeXP30 as defined in the XPath specification
    uri; uris A URI, for example a namespace URI or a collation URI; a whitespace-separated list of URIs
    qname A lexical QName as defined in 5.1 Qualified Names
    eqname; eqnames An EQName as defined in 5.1 Qualified Names; a whitespace-separated list of EQNames
    token; tokens A string containing no significant whitespace; a whitespace-separated list of such strings
    nmtoken; nmtokens A string conforming to the XML schema rules for the type xs:NMTOKEN; a whitespace-separated list of such strings.
    char A string comprising a single Unicode character
    integer An integer, that is a string in the lexical space of the schema type xs:integer
    decimal A decimal value, that is a string in the lexical space of the schema type xs:decimal
    ncname An unprefixed name: a string in the value space of the schema type xs:NCName
    prefix An xs:NCName representing a namespace prefix, which must be in scope for the element on which it appears
    id An xs:NCName used as a unique identifier for an element in the containing XML document

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

  • 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] It is a static error if an XSLT-defined element is used in a context where it is not permitted, if a required attribute is omitted, or if the content of the element does not correspond to the content that is allowed for the element.

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.11 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]. A list of these functions appears in F List of XSLT-defined functions. The signatures of these functions are described using the same notation as used in [Functions and Operators]. The names of many of these functions are in the standard function namespace.

2.3 Initiating a Transformation

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

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.12.2 Stylesheet Inclusion and 3.12.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 absent, 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 absent 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 docFO30 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 20.1 fn:document) or docFO30 or collectionFO30 (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 23.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 23.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 3.0 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 25 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 Packages and Modules

In previous versions of the XSLT language, it has been possible to structure a stylesheet as a collection of modules, using the xsl:include and xsl:import declarations to express the dependency of on module on others.

In XSLT 3.0 an additional layer of modularization of stylesheet code is enabled through the introduction of packages. A package is a collection of stylesheet modules with a controlled interface to the packages that use it: for example, it defines which functions and templates defined in the package are visible to callers, which are purely internal, and which are not only public but capable of being overridden by other functions and templates supplied by the using package.

Packages are introduced with several motivations, which broadly divide into two categories:

  1. Software engineering benefits: greater re-use of code, greater robustness through ease of testing, controlled evolution of code in response to new requirements, ability to deliver code that users cannot see or modify.

  2. Efficiency benefits: the ability to avoid compiling libraries repeatedly when they are used in multiple stylesheets, and to avoid holding multiple copies of the same library in memory simultaneously.

Packages are designed to allow separate compilation: that is, a package can be compiled independently of the packages that use it. This specification does not define a process model for compilation, or expand on what it means to compile different packages independently. Nor does it mandate that implementations offer any feature along these lines. It merely defines language features that are designed to make separate compilation of packages possible.

To achieve this, packages (unlike modules):

  • Must not contain unresolved references to functions, templates, or variables declared in other packages;

  • Have strict rules governing the ability to override declarations in a library package with declarations in a package that uses the library;

  • Constrain the visibility of component names and of context declarations such as the declarations of keys and decimal formats;

  • Can declare a mode (a collection of template rules) as final, which disallows the addition of new overriding template rules in a using package;

  • Require explicit disambiguation where naming conflicts arise, for example when a package uses two other packages that both export like-named components;

  • Allow multiple specializations of library components to coexist in the same application.

A package is defined by means of an XML document whose outermost element is an xsl:package element. This is referred to as the package manifest. The xsl:package element has child elements describing properties of the package, as well as an xsl:stylesheet or xsl:transform child element that defines the content of the package, either directly or by reference through one or more xsl:import or xsl:include declarations.

When no packages are explicitly defined, the entire stylesheet is treated as a single package; the effect is as if the principal stylesheet module were wrapped in an xsl:package element with no other information in the package manifest.

2.8 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 23.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 23.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 23 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.8.3 User-defined Data Elements).

2.9 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 SequenceTypeXP30 syntax defined in [XPath 3.0].

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

[Definition: The schema components that may be referenced by name in a 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 3.0, defined in 26 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 substringFO30 function) and other constructs may produce different results depending on the datatype (for example, given the element <product price="10.00" discount="2.00"/>, the expression @price gt @discount will return true if the attributes have type xs:decimal, but will return false if they are untyped).

There is a standard set of type definitions that are always available as in-scope schema components in every stylesheet. These are defined in 3.15 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" typed="lax">
  <xsl:context-item use="required"
                    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.

The setting typed="lax" further ensures that in any match pattern for a template rule in this mode, an element name that corresponds to the name of an element declaration in the schema is taken as referring to elements validated against that declaration: for example, match="employee" will only match a validated employee element. Selecting this option enables the XSLT processor to do more compile-time type-checking against the schema, for example it allows the processor to produce warning or error messages when path expressions contain misspelt element names, or confuse an element with an attribute.

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

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

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

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

2.10 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 3.0 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 3.0 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 guaranteed-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 guaranteed-streamable template.

The rules for streamability, which are defined in detail in 19.3 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 3.0). 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.

The new facility of accumulators allows applications complete control over how much information is retained (and by implication, how much memory is required) in the course of a pass over a streamed document. An accumulator computes a value for every node in a streamed document: or more accurately, two values, one for the first visit to a node (before visiting its descendants), and a second value for the second visit to the node (after visiting the descendants). The computation is structured in such a way that the value for a given node can depend only on the value for the previous node in document order together with the data available when positioned at the current node (for example, the attribute values). Based on the well-established fold operation of functional programming languages, accumulators provide the convenience and economy of mutable variables while remaining within the constraints of a purely declarative processing model.

Streaming applications often fall into one of the following categories:

  • Aggregation applications, where a single aggregation operation (perhaps countFO30, sumFO30, existsFO30, or distinct-valuesFO30) 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 multiple 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.11 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.11 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 3.0 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 Errors XP30) 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 3.0 processor. (An XSLT 1.0 processor will execute this code successfully, returning positive infinity, because it uses double arithmetic rather than decimal arithmetic.)

[Definition: 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 25 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 3.0], [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

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

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.8 Stylesheet Element and 3.9 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 23.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-dateTimeFO30.

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

  • The namespace http://www.w3.org/2005/xpath-functions/map is used for functions defined in this specification relating to the manipulation of maps.

  • [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 3.0]) 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 3.0 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.14 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.10 Backwards Compatible Processing and 3.11 Forwards Compatible Processing

[xsl:]xpath-default-namespace

see 5.2 Unprefixed Lexical QNames in Expressions and Patterns

[xsl:]exclude-result-prefixes

see 11.1.3 Namespace Nodes for Literal Result Elements

[xsl:]extension-element-prefixes

see 23.2 Extension Instructions

[xsl:]use-when

see 3.14 Conditional Element Inclusion

[xsl:]default-collation

see 3.8.1 The default-collation attribute

3.6 Packages

[Definition: A package is represented by an xsl:package element, which will generally be the outermost element of an XML document.] (This specification does not preclude the xsl:package being embedded in another XML document, but it will never have any other XSLT element as an ancestor).

<xsl:package
  xsl:version? = decimal
  name? = uri
  package-version? = string >
  <!-- Content: (xsl:use-package*, (xsl:stylesheet | xsl:transform), xsl:expose*) -->
</xsl:package>

[Definition: The content of the xsl:package element is referred to as the package manifest].

The xsl:version attribute indicates the version of the XSLT language specification to which the package manifest conforms. The value should be 3.0.

Issue 2 (package-xslt-version):

Need to define forwards and backwards compatibility rules for package/@xsl:version

Every package has a name, given in its name attribute, which must be an absolute URI.

Every package has a version identifier, given in its package-version attribute. This is used to distinguish different packages that have the same package name, perhaps successive versions of a package, or perhaps variants of a package for use in different environments. The version identifier can be any string.

The package manifest is in three parts:

  1. It starts with zero-or-more xsl:use-package elements which identify the packages used by this package, including subsidiary elements that constrain the way in which the components contained in those packages are used.

  2. This is followed by an xsl:stylesheet or xsl:transform element (the two names are synonyms) which is an embedded standard stylesheet module. This can contain references to other stylesheet modules using xsl:include and/or xsl:import declarations, and it can contain other declarations such as xsl:function and xsl:template.

    The modules making up a package are this module, plus all modules that are transitively reachable from it using xsl:import and xsl:include declarations. It is permissible for the same module to appear in more than one package, or indeed more than once in the same package; this situation is no different from having two modules with identical content but different URIs.

  3. Finally, the manifest contains zero or more xsl:expose declarations that define the interface offered by this package to the outside world.

A package that does not itself expose any components (in effect, a stylesheet that makes use of library packages but is not itself intended to act as a library package) may be written using a simplified syntax: the xsl:package element is omitted, and the xsl:use-package children are moved to the xsl:stylesheet or xsl:transform element, which is now the outermost element of the stylesheet module. More formally, an xsl:stylesheet or xsl:transform element having one or more xsl:use-package children is equivalent to the package represented by the output of the following transformation, preserving the base URI of the source:

 <xsl:transform version="3.0" 
    xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    xmlns:t="http://www.w3.org/1999/XSL/TransformAlias">
 
    <xsl:namespace-alias stylesheet-prefix="t" result-prefix="xsl"/>
    <xsl:mode on-no-match="shallow-copy"/>
    <xsl:template match="(xsl:stylesheet|xsl:transform)[xsl:use-package]">
      <t:package t:version="{@version}">
        <xsl:copy-of select="xsl:use-package"/>
        <xsl:copy>
          <xsl:copy-of select="@*"/>
          <xsl:copy-of select="* except xsl:use-package"/>
        </xsl:copy>
      </t:package>
    </xsl:template>
 </xsl:transform>   
       

3.6.1 Dependencies between Packages

When components in one package reference components in another, the dependency of the first package on the second must be represented by an xsl:use-package element in the package manifest of the first package.

[Definition: If a package Q contains an xsl:use-package element that references package P, then package Q is said to use package P. In this relationship package Q is referred to as the using package, package P as the used package.]

The phrase directly uses is synonymous with uses as defined above, while directly or indirectly uses refers to the transitive closure of this relationship.

<xsl:use-package
  name? = uri
  package-version? = token >
  <!-- Content: (xsl:accept | xsl:override)* -->
</xsl:use-package>

A package may be used by more than one other package, but the relationship must not be cyclic. It is possible, but by no means inevitable, that using the same package in more than one place within a stylesheet will cause static errors due to the presence of conflicting components according to the above rules. Where a package is successfully used by more than one other package, its components may be overridden in different ways by different using packages.

Issue 3 (cyclic-package-dependencies):

The restriction that prevents cyclic package dependencies is unfortunate, it would be nice if we can find a way of dispensing with it. It's a consequence of the decision that each use of a package effectively creates a new occurrence of all its components.

The name and package-version attributes together identify the used package. The used package must have a name that is an exact match for the name in the name attribute, and it may have a package-version that matches the pattern given in the package-version attribute. Omitting this attribute is equivalent to specifying the value as package-version="#", which matches any version.

The value of the package-version attribute consists of a prefix and a suffix separated by a hash sign (#); if there is no hash sign, the entire string is used as the prefix, and the suffix is empty; if there is more than one hash sign, the first one is taken as the separator and others as part of the suffix; if the hash sign is the last character in the string then a suffix of ".*" is assumed. The pattern matches a package version if the package version can be divided into two substrings such that the first substring matches the prefix literally (using codepoint comparison), and the second substring matches the suffix considered as a regular expression (matched according to the rules of the matchesFO30 function with the $flags argument set to a zero length string). Thus the version pattern 3.1 matches version 3.1 only; the pattern 3.1# matches 3.1, 3.1.2, and 3.17; the pattern 3.1#(\.\d+)? matches 3.1 and 3.1.5; and the pattern 3.1#(\.\d+)* matches 3.1, 3.1.5, and 3.1.5.2.

This specification does not define how the implementation locates a package given its name and version. Nor does it define whether this process locates source code or some other representation of the package contents. Such mechanisms are implementation-defined. Use of the package name as a dereferencable URI is not recommended, because the intent of the packaging feature is to allow a package to be distributed as reusable code and to therefore to exist in many different locations.

The xsl:accept and xsl:override elements are used to modify the visibility or behavior of components acquired from the used package; they are described in 3.6.2.4 Accepting Components below.

Issue 4 (use-package-xquery):

The WG intends to add an option to xsl:use-package to allow an XQuery library module to be used in the same way as a package written in XSLT. This requires defining a mapping of XQuery concepts to XSLT concepts (for example, XQuery external variables equate to XSLT stylesheet parameters). This is likely to be an optional conformance feature.

3.6.2 Named Components in Packages

This section discusses the use of named components in packages: specifically functions, named templates, attribute sets, and global variables and parameters. Some of the provisions in this section also apply to named modes, but there are differences noted in 3.6.3 Overriding Template Rules from a Used Package. The section is largely concerned with details of the rules that affect references from one component to another by name, whether the components are in the same package or in different packages. The rules are designed to meet a number of requirements:

  • A component defined in one package can be overridden by a component in another package, provided the signatures are type-compatible.

  • The author of a package can declare whether the components in the package are public or private (that is, whether or not they can be used from outside the package) and whether they are final, overridable, or abstract (that is whether they can or must be overridden by the using package).

  • Within an application, two packages can make use of a common library and override its components in different ways.

  • Visibility of components can be defined either as part of the declaration of the component, or in the package manifest.

  • An application that wishes to make use of a library package can be selective about which components from the library it acquires, perhaps to avoid name clashes between components acquired from different libraries.

[Definition: The term component is used to refer to any of the following: a stylesheet function, a named template, a mode, a attribute set, a global variable, or a mode.]

[Definition: The symbolic identifier of a component is a composite name used to identify the component uniquely within a package. The symbolic identifier comprises the kind of component (stylesheet function, named template, attribute set, global variable, or mode), the expanded QName of the component (namespace URI plus local name), and in the case of stylesheet functions, the arity.]

[Definition: Two components are said to be homonymous if they have the same symbolic identifier.]

Every component has a declaration in some stylesheet module and therefore within some package. The declaration is an element in an XDM tree representing the stylesheet module. Declarations therefore have identity, based on XDM node identity.

Not all declarations result in components:

  • Some declarations, such as xsl:decimal-format and xsl:strip-space, declare aspects of the processing context which are not considered to be components as defined here.

  • Template rules (xsl:template with a match attribute) are also not considered to be components for the purposes of this section, which is concerned only with components that are bound by name. However, when an xsl:template has both a match attribute and a name attribute, then it establishes both a template rule and a named template, and in its role as a named template it comes within the scope of this discussion.

  • A named declaration, for example a named template, a function, an attribute set, or a global variable, may be overridden within the same package by another like-named declaration having higher import precedence. When a declaration is overridden in this way it can never be referenced or invoked either from within its containing package or from outside that package; it is effectively dead code, and it therefore does not result in the creation of any component, which means that it plays no part in the component binding process.

[Definition: The declaring package of a component is the package that contains the declaration of the component.]

When a component declared in one package is made available in another, the using package will contain a separate component that can be regarded as a modified copy of the original. The new component shares the same symbolic identifier as the original, and it has the same declaration, but it has other properties such as its visibility that may differ from the original.

The properties of a component are as follows:

Note:

When a function F defined in a package P is acquired by two using packages Q and R, we may think of P, Q, and R as all providing access to the "same" function. The detailed semantics, however, demand an understanding that there is one function declaration, but three components. The three components representing the function F within packages P, Q, and R have some properties in common (the same symbolic identifier, the same declaration), but other properties (the visibility and the bindings of symbolic references) that may vary from one of these components to another.

[Definition: The declaration of a component includes constructs that can be interpreted as references to other components by means of their symbolic identifiers. These constructs are generically referred to as symbolic references. Examples of constructs that give rise to symbolic references are the name attribute of xsl:call-template; the [xsl:]use-attribute-sets attribute of xsl:copy, xsl:element, and literal result elements; the mode attribute of xsl:template and xsl:apply-templates; XPath variable references referring to global variables; and XPath function calls referring to stylesheet functions.]

Symbolic references exist as properties of the declaration of a component. The symbolic identifier being referred to can be determined straightforwardly from the syntactic form and context of the reference: for example, the instruction <xsl:value-of select="f:price($o)" xmlns:f="http://f.com/"/> contains a symbolic reference to a function with expanded name {http://f.com/}price and with arity=1. However, because there may be several (homonymous) function components with this symbolic identifier, translating this symbolic reference into a reference to a specific component (a process called "binding") is less straightforward, and is described in the text that follows.

The process of assembling a stylesheet from its constituent packages is primarily a process of binding these symbolic references to actual components. Within any component whose declaration is D, there is a set of bindings; each binding is an association between an symbolic reference in D and a component whose symbolic identifier matches the outward reference. Outward references for which a component C contains a binding are said to be bound in C; those for which C contains no binding are said to be unbound.

For example, suppose that in some package P, function A calls B, which in turn calls C, and that B is private. Now suppose that in some package Q which uses P, C is overridden. The effect of the binding process is that Q will contain three components corresponding to A, B, and C, which we might call A(Q), B(Q), and C(Q). The declarations of A(Q) and B(Q) are in package P, but the declaration of C(Q) is in Q. The internal visibility of B(Q) will be hidden (meaning that it cannot be referenced from within Q), and B(Q) will contain a binding for the component C(Q) that corresponds to the outward reference from B to C. The effect is that when A calls B and B calls C, it is the overriding version of C that is executed. In another package R that uses P without overriding C, there will be three different components A(R), B(R), and C(R). This time the declaration of all three components is in the original package P. Component B(R) will contain a binding to C(R), so in this package, the original version of C is executed. The fact that one package Q overrides C thus has no effect on R, which does not override it.

3.6.2.1 Visibility of Components

[Definition: The visibility of a component is one of: private, public, abstract, final, or hidden.]

The meanings of these visibility values is as follows:

Visibility Meaning
public The component can be referenced from other components in this package or in any using package; it can be overridden by a different component in any using package.
private The component can be referenced from other components in this package; it cannot be referenced or overridden within a using package.
abstract The component can be referenced from other components in this package or in any using package; in a using package it can either remain abstract or be overridden by a different component. (In the top-level package of a stylesheet, it must be overridden by a non-abstract component.)
final The component can be referenced from other components in this package or in any using package; it cannot be overridden by a different component in any using package.
hidden The component cannot be referenced from other components in this package; it cannot be referenced or overridden within a using package.

The visibility (sometimes called the actual visibility) of a component depends on two factors: its potential visibility and its exposed visibility.

[Definition: The potential visibility of a component is established when the component is declared or accepted into a package.]

[Definition: The exposed visibility of a component is established by an xsl:expose element in the package manifest.]

For a component within its declaring package the potential visibility is the value of the visibility attribute on the component's declaration, or private if the attribute is absent.

For a component accepted from another package, the potential visibility depends on the visibility declared in the relevant xsl:accept or xsl:override element that makes the component available within the using package; this in turn has a default that depends on the (actual) visibility of the corresponding component in the used package.

These rules are described more fully in the sections that follow.

3.6.2.2 Visibility of Declarations

The xsl:function, xsl:template, xsl:attribute-set, xsl:variable, xsl:param, and xsl:mode declarations each have an optional visibility attribute that determines the potential visibility of the component corresponding to this declaration in its declaring package. The value is one of private, public, abstract, final (never hidden), with the default being private.

Whatever the value of this attribute, and whatever the exposed visiblity of the component, other declarations within the same package may contain symbolic references to this declaration: informally, the name of the component is always "in scope" within the package containing its declaration. The way in which these symbolic references are bound to an actual component, however, depends on the component's visibility, as defined in 3.6.2.6 Binding References to Components. For example, a symbolic reference will never be bound to a component whose visibility is abstract.

3.6.2.3 Exposing Components

The visibility of a component within a package may be modified by means of an xsl:expose element in the package manifest.

<xsl:expose
  component = "template" | "function" | "attribute-set" | "variable" | "mode"
  names = tokens
  visibility = "public" | "private" | "final" | "abstract" />

The xsl:expose element allows selected components within a package to have an exposed visibility different from their potential visibility .

The components in question are identified using their symbolic identifiers. The component attribute defines the kind of component that is selected (variable embraces xsl:variable and xsl:param). The names attribute selects a subset of those components by name (and in the case of functions, arity); its value is a whitespace-separated sequence of tokens each of which is either a NameTestXP30 or a NamedFunctionRefXP30. (Examples are *, p:*, *:local, p:local, and p:local#2.)

The value may be a NamedFunctionRef only in the case of stylesheet functions, and distinguishes functions with the same name and different arity.

The visibility attribute defines the exposed visibility of the selected components.

If a component is matched by more than one xsl:expose element in the package manifest, then its exposed visibility is determined by the best matching NameTestXP30 or LiteralFunctionItem. The rules are similar to those for template rules:

  • A token in the form of a LiteralFunctionItem (for example, f:price#1) has higher priority than any NameTest.

  • Next, any match that has a lower default priority than the default priority of another match is ignored.

  • If several matches have the same default priority (which can happen if the same value is repeated, or if one of the NameTests takes the form *:local and the other takes the form prefix:*), then the xsl:expose element that appears last in document order within the package manifest is used.

If no xsl:expose element matches a component, then the visibility of the component is its potential visibility.

Otherwise, the visibility of the component depends on its potential visibility and its exposed visibility as defined by the following table. In this table, the value N/P means "not permitted".

Exposed visibility Potential visibility
public private final abstract
public public N/P N/P N/P
private private private private N/P
final final N/P final N/P
abstract N/P N/P N/P abstract

[ERR XTSE3010] It is a static error if the exposed visibility of a component is inconsistent with its potential visibility, as defined in the above table, unless the token that matches the component is a wildcard, in which case it is treated as not matching that component.

[ERR XTSE3020] It is a static error if an xsl:expose element matches no components in the containing package, unless the tokens in the names attribute are all wildcards.

3.6.2.4 Accepting Components

When a package Q uses a package P, by virtue of an xsl:use-package element in the package manifest of Q, then Q will contain a component corresponding to every component in P. The potential visibility of the component within Q depends on the visibility of the component in P, optionally modified by two elements that may appear as children of the xsl:use-package element, namely xsl:accept and xsl:override.

For every component C(P) in package P that is not matched by any xsl:override or xsl:accept element in the package manifest of Q, there will be a corresponding component C(Q) in package Q that has the same symbolic identifier and declaration as C(P). The potential visibility of C(Q) will be the same as the (actual) visibility of C(P), except that where the visibility of C(P) is private, the potential visibility of C(Q) will be hidden. The (actual) visibility of C(Q) depends both on its potential visibility and its exposed visibility, as described in 3.6.2.3 Exposing Components.

A component C(P) in package P whose visibility is hidden will never be matched by an xsl:override or xsl:accept element in the package manifest of Q, and therefore Q will contain a hidden component C(Q) corresponding to C(P).

<xsl:accept
  component = "template" | "function" | "attribute-set" | "variable" | "mode"
  names = tokens
  visibility = "public" | "private" | "final" | "abstract" | "hidden" />

The xsl:accept element has the same syntax as xsl:expose, and very similar semantics. Whereas xsl:expose allows a package to restrict the visibility of its own components to other (using) packages, xsl:accept allows a package to restrict the visibility of components exposed by a package that it uses. This may be necessary if, for example, it uses two different packages whose component names conflict. It may also simply be good practice if the package author knows that only a small subset of the functionality of a used package is required.

The rules for determining whether an xsl:accept element matches a particular component, and for which element to use if there are several matches, are the same as the rules for the xsl:expose element.

[ERR XTSE3030] It is a static error if an xsl:accept element matches no components in the used package, unless the tokens in its names attribute are all wildcards.

In the absence of a matching xsl:override element (see 3.6.2.5 Overriding Named Components from a Used Package), the potential visibility of a component that matches an xsl:accept element depends both on the visibility attribute of the best-matching xsl:accept element and on the (actual) visibility of the corresponding component in the used package, according to the following table. In this table the entry "N/P" means "not permitted".

Visibility in xsl:accept element Visibility in used package
public private final abstract
public public N/P N/P N/P
private private N/P private N/P
final final N/P final N/P
abstract N/P N/P N/P abstract
hidden hidden N/P hidden N/P

[ERR XTSE3040] It is a static error if the visibility assigned to a component by an xsl:accept element is incompatible with the visibility of the corresponding component in the used package, as defined by the above table, unless the token that matches the component name is a wildcard, in which case the xsl:accept element is treated as not matching that component.

[ERR XTSE3050] It is a static error if the xsl:use-package elements in a package manifest cause two or more homonymous components to be accepted with a visibility other than hidden.

Conflicts between the components accepted from used packages and those declared within the package itself are handled as follows:

  1. If the conflict is between two components both declared within the package itself, then it is resolved by the rules relating to import precedence defined for each kind of component.

  2. If the conflict is between two components both accepted from used packages, or between a component declared within the package and an accepted component, then a static error occurs.

Note:

To override a component accepted from a used package, the overriding declaration must appear as a child of the xsl:override element.

Note:

There is no rule that prevents a function (say) being declared in the using package with the same name as a private function in the used package. This does not create a conflict, since all references in the used package are bound to one function and all those in the using package are bound to another.

3.6.2.5 Overriding Named Components from a Used Package

[Definition: A component in a using package may override a component in a used package, provided that the visibility of the component in the used package is either abstract or public. The overriding declaration is written as a child of the xsl:override element, which in turn appears as a child of xsl:use-package.]

Note:

This mechanism is distinct from the mechanism for overriding declarations within the same package by relying on import precedence. It imposes stricter rules: the overriding component is required to be type-compatible with the component that it overrides.

If the used package P contains a component C(P) and the xsl:use-package element contains an xsl:override element which contains a declaration D whose symbolic identifier matches the symbolic identifier of C(P), then the using package Q will contain a component whose declaration is D, whose symbolic identifier is that of D, and whose potential visibility is equal to the value of the visibility attribute of D, or private if this is absent.

If the overridden component C(P) has visibility public then the using package Q will also contain a component C′(Q) whose declaration is the same as the declaration of C(P) and whose visibility is hidden. This component is used as the target of a binding for the symbolic reference xsl:original described below.

Other than its appearance as a child of xsl:override, the overriding declaration is a normal xsl:function, xsl:template, xsl:variable, xsl:param, xsl:attribute-set, or xsl:mode element. In the case of xsl:variable and, xsl:param, the variable that is declared is a global variable.

The potential visibility of the overriding component in the using package is defined by the visibility attribute appearing on the overriding declaration.

The overriding declaration must not be homonymous with any other declaration in the using package, regardless of import precedence, including any other overriding declaration in the package manifest of the using package.

<xsl:override>
  <!-- Content: (xsl:template | xsl:function | xsl:variable | xsl:param | xsl:attribute-set)* -->
</xsl:override>

[ERR XTSE3060] It is a static error if the component referenced by an xsl:override declaration has visibility other than public or abstract

A package is executable if and only if it contains no component whose visibility is abstract. A package that is not executable is not a stylesheet, and therefore cannot be nominated as the stylesheet to be used when initiating a transformation.

Note:

In other words, if a component is declared as abstract, then some package that uses the declaring package of that component directly or indirectly must override that component with one that is not abstract. It is not necessary for the override to happen in the immediately using package.

[ERR XTSE3070] It is a static error if the signature of an overriding component is not compatible with the signature of the component that it is overriding.

[Definition: The signatures of two components are compatible if they present the same interface to the user of the component. The rules depend on the kind of component.]

The compatibility rules for each kind of component are as follows:

  • Two attribute sets are compatible if they have the same name.

  • Two functions are compatible if they have the same name, if the types of the arguments are pairwise identical and if the return types are identical.

  • Two named templates are compatible if they have the same name, if the return types are identical, and if the declared parameters on the overriding template include one parameter matching each parameter on the overridden template by having identical effective values for its name, as, required, and tunnel attributes; in addition the overriding template may define additional parameters provided they specify required="no".

  • Two variables are compatible if they have the same name and their types are identical. A variable may override a parameter or vice-versa, and the value of the required attribute may differ.

Modes are not overridable, so the xsl:mode declaration cannot appear as a child of xsl:override.

Within the declaration of an overriding component (that is, a component whose declaration is a child of xsl:override), where the overridden component has public visibility, it is possible to use the name xsl:original as a symbolic reference to the overridden component:

  • Within an overriding named template, <xsl:call-template name="xsl:original"/> may be used to call the overridden named template.

  • Within an overriding stylesheet function, xsl:original() may be used to call the overridden stylesheet function.

  • Within an overriding global variable or parameter, $xsl:original may be used to reference the overridden global variable or parameter.

  • Within an overriding attribute set, [xsl:]use-attribute-set="xsl:original" may be used to reference the overridden attribute set.

Within the overriding component C(Q), this symbolic reference is bound to the hidden component C′(Q) described earlier, whose declaration is that of the component C(P) in the used package. The static context for the overriding declaration is augmented to include a component of the relevant kind (function, named template, attribute set, or variable) with the name xsl:original.

3.6.2.6 Binding References to Components

[Definition: The process of identifying the component to which a symbolic reference applies (possibly chosen from several homonymous alternatives) is called reference binding.] A reference is called bound if the component to which it applies has been identified and fixed, and is unbound otherwise (that is, if it exists only in the form of a symbolic identifier).

Reference resolution for the components in a package occurs conceptually after a package has been fully defined and before the processing of any other package that uses it.

Note:

If packages are separately compiled, then reference resolution is likely to form part of the compilation process.

When reference resolution is performed for a component C, each symbolic reference R that is present in the declaration of C is processed as follows:

  1. If C already contains a binding for R then this binding is retained.

  2. If C contains no binding for R then the processor attempts to locate a component in the containing package of C whose visibility is not hidden and whose symbolic name matches R. If there is no such component, then a static error is reported as described elsewhere in this specification. There can never be more than one. Call the located component D. If D has visibility private or final, then C acquires a binding that associates the symbolic reference R with the component D. Otherwise, the reference remains unbound.

When a package P is used by another package Q, then Q will accept components corresponding to the components in P, as described in previous sections. Until reference resolution is performed for Q, these components will have the same bindings as their corresponding components from P: a symbolic reference that was bound for a component in P will retain the same binding, and a symbolic reference that was unbound in P will remain unbound in the corresponding component in Q. Subsequently, when reference resolution is performed for package Q, these symbolic references may become bound, perhaps to components whose declaration is in Q or in some other package.

When reference resolution is performed on a package that is intended to be used as a stylesheet (that is, for the top-level package), symbolic references to components whose visibility is public are bound in the same way as references to components whose visibility is private or final. At this stage there must be no symbolic references referring to components whose visibility is abstract (that is, an implementation must be provided for every abstract component).

[ERR XTSE3080] It is a static error if a top-level package intended for execution (as distinct from a library package) contains symbolic references referring to components whose visibility is abstract.

Note:

Unresolved references are allowed at the module level but not at the package level. A stylesheet module can contain references to components that are satisfied only when the module is imported into another module that declares the missing component.

Note:

The process of resolving references (or linking) is critical to an implementation that uses separate compilation. One of the aims of these rules is to ensure that when compiling a package, it is always possible to determine the signature of called functions, templates, and other components. A further aim is to establish unambiguously in what circumstances components can be overridden, so that compilers know when it is possible to perform optimizations such as inlining of function and variable references.

Suppose a public template T calls a private function F. When the package containing these two components is referenced by a using package, the template remains public, while the function becomes hidden. Because the function becomes hidden, it can no longer conflict with any other function of the same name, or be overridden by any other function; at this stage the compiler knows exactly which function T will be calling, and can perform optimizations based on this knowledge.

3.6.3 Overriding Template Rules from a Used Package

The rules in the previous section apply to named components including functions, named templates, global variables, and named attribute sets. The rules for modes, and the template rules appearing within a mode, are slightly different.

The unnamed mode is local to a package: in effect, each package has its own private unnamed mode, and the unnamed mode of one package does not interact with the unnamed mode of any other package.

A named mode may be declared in an xsl:mode declaration as being either public, private, or final. The values of the visibility attribute are interpreted as follows:

Value Meaning
public A using package may use xsl:apply-templates to invoke templates in this mode; it may also declare additional template rules in this mode, which are selected in preference to template rules in the used package. These may appear only as children of the xsl:override element within the xsl:use-package element.
private A using package may neither reference the mode nor provide additional templates in this mode; the name of the mode is not even visible in the using package, so no such attempt is possible. The using package can use the same name for its own modes without risk of conflict.
final A using package may use xsl:apply-templates to invoke templates in this mode, but it must not provide additional template rules in this mode.

As with other named components, an xsl:use-package declaration may contain an xsl:expose element to control the visibility of a mode acquired from the used package. The allowed values of its visibility attribute are public, private, final, and hidden.

The xsl:mode declaration itself must not be overridden. A using package must not contain an xsl:mode declaration whose name matches that of a public or final xsl:mode component accepted from a used package.

The xsl:expose and xsl:accept elements may be used to reduce the visibility of a mode in a using package; the same rules apply in general, though some of the rules are not applicable because, for example, modes cannot be abstract.

It is not possible for a package to combine the template rules from two other packages into a single mode. When xsl:apply-templates is used without specifying a mode, the chosen template rules will always come from the same package; when it is used with a named mode, then they will come from the package where the mode is defined, or any package that uses that package and adds template rules to the mode. If two template rules defined in different packages match the same node, then the rule in the using package wins over any rule in the used package; this decision is made before taking other factors such as import precedence and priority into account.

A static error occurs if two modes with the same name are visible within a package, either because they are both declared within the package, or because one is declared within the package and the other is acquired from a used package, or because both are accepted from different used packages.

The rules for matching template rules by precedence and priority operate as normal, with the addition that template rules declared within an xsl:use-package element have higher precedence than any template rule declared in the used package.

When a template rule specifies match="#all" this is interpreted as meaning all modes declared implicitly or explicitly within the declaring package of the xsl:template element.

Note:

If existing XSLT code has been written to use template rules in the unnamed mode, a convenient way to incorporate this code into a library package is to add a stub module that defines a new named public or final mode, in which there is a single template rule whose content is the single instruction <xsl:apply-templates/>. This in effect redirects xsl:apply-templates instructions using the named mode to the rules defined in the unnamed mode.

3.6.4 Declarations Local to a Package

Declarations of keys, decimal formats, namespace aliases (see 11.1.5 Namespace Aliasing), output definitions, and character maps within a package have local scope within that package — they are all effectively private. The elements that declare these constructs do not have a visibility attribute. The unnamed decimal format and the unnamed output format are also local to a package.

If xsl:strip-space or xsl:preserve-space declarations appear within a library package, they only affect calls to the docFO30 or document functions appearing within that package. Such a declaration within the main package additionally affects stripping of whitespace in the principal source document.

An xsl:decimal-format declaration within a package applies only to calls on format-numberFO30 appearing within that package.

An xsl:namespace-alias declarations within a package applies only to literal result elements within the same package.

An xsl:import-schema declaration within a package adds the names of the imported schema components to the static context for that package only; these names are effectively private, in the sense that they do not become available for use in any other packages. However, the names of schema components must be consistent across the stylesheet as a whole: it is not possible for two different packages within a stylesheet to use a type-name such as "part-number" to refer to different schema-defined simple or complex types.

Type names used in the interface of public components in a package (for example, in the arguments of a function) must be respected by callers of those components, in the sense that the caller must supply values of the correct type. Often this will mean that the using component, if it contains calls on such interfaces, must itself import the necessary schema components. However, the requirement for an explicit schema import applies only where the package contains explicit use of the names of schema components required to call such interfaces.

Note:

For example, suppose a library package contains a function which requires an argument of type mfg:part-number. The caller of this function must supply an argument of the correct type, but does not need to import the schema unless it explicitly uses the schema type name mfg:part-number. If it obtains an instance of this type from outside the package, for example as the result of another function call, then it can supply this instance to the acquired function even though it has not imported a schema that defines this type.

At execution time, the schema available for validating instance documents contains (at least) the union of the schema components imported into all constituent packages of the stylesheet.

3.6.5 Using an XQuery Library Package

This section is a stub: it describes work in progress.

It is intended to provide a variant of xsl:use-package that allows an XQuery library module to be used in exactly the same way as a package written in XSLT.

The syntax for doing this is to be defined.

Such a package will contain functions and global variables/parameters only (no attribute sets or templates). These may be public or private, depending on their XQuery annotations (they cannot be final or abstract). The effect of using functions that are updating, or nondeterministic is implementation-defined.

The same rules for consistency of imported schema components apply as when using an XSLT package.

3.7 Stylesheet Modules

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

Note:

A stylesheet module is represented by an XDM element node (see [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:

  • [Definition: A standard stylesheet module is a tree, or part of a tree, consisting of an xsl:stylesheet or xsl:transform element (see 3.8 Stylesheet Element) together with its descendant nodes and associated attributes and namespaces.]

  • [Definition: A simplified stylesheet module is a tree, or part of a tree, consisting of a literal result element together with its descendant nodes and associated attributes and namespaces. This element is not itself in the XSLT namespace, but it must have an xsl:version attribute, which implies that it must have a namespace node that declares a binding for the XSLT namespace. For further details see 3.9 Simplified Stylesheet Modules. ]

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.13 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.8 Stylesheet Element

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

<xsl:transform
  id? = id
  extension-element-prefixes? = prefixes
  exclude-result-prefixes? = prefixes
  version = decimal
  xpath-default-namespace? = uri
  default-validation? = "preserve" | "strip"
  default-collation? = uris
  default-mode? = eqname | "#unnamed"
  input-type-annotations? = "preserve" | "strip" | "unspecified" >
  <!-- Content: (xsl:use-package*, 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 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 3.0, the value should normally be set to 3.0. If the value is numerically less than 3.0, the stylesheet is processed using the rules for backwards compatible behavior (see 3.10 Backwards Compatible Processing). If the value is numerically greater than 3.0, the stylesheet is processed using the rules for forwards compatible behavior (see 3.11 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 24.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.8.3 User-defined Data Elements)].

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

xsl:use-package
xsl:import
xsl:include
xsl:accumulator
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:use-package elements, these must come before any other elements. If there are xsl:import elements, these must come after any xsl:use-package elements but 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.

For the meaning of the xsl:use-package element, see 3.6 Packages.

3.8.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.8.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 an EQName, 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.

3.8.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.9 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="3.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="3.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>

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="3.0"
                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 3.0 ; 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.10 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 3.0.]

Specifically:

  • If the effective version is equal to 1.0, then the element is processed with XSLT 1.0 behavior as described in 3.10.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.10.2 XSLT 2.0 compatibility mode.

  • If the effective version is any other value less than 3.0, 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 3.0 implementation supports backwards compatible behavior for any XSLT version earlier than XSLT 3.0.

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

Note:

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

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

To write a stylesheet that makes use of features that are new in version N, while also working with a processor that only supports XSLT version M (M < N), it is necessary to understand both the rules for backwards compatible behavior in XSLT version N, and the rules for forwards compatible behavior in XSLT version M. If the xsl:stylesheet element specifies version="2.0" or version="3.0", then an XSLT 1.0 processor will ignore XSLT 2.0 and XSLT 3.0declarations that were not defined in XSLT 1.0, for example xsl:function and xsl:import-schema. If any new XSLT 3.0 instructions are used (for example xsl:evaluate or xsl:stream), or if new XPath 3.0 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.10.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 Context XP30.

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 23.1 Extension Functions.

Note:

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

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

3.10.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 3.0 processor will therefore produce the same results whether the effective version of an element is set to 2.0 or 3.0.

Note:

An XSLT 2.0 processor, by contrast, will in some cases produce different results in the two cases. For example, if the stylesheet contains an xsl:iterate instruction with an xsl:fallback child, an XSLT 3.0 processor will process the xsl:iterate instruction regardless whether the effective version is 2.0 or 3.0, 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 3.0.

3.11 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 3.0, while retaining the ability to execute the stylesheet with an XSLT 3.0 processor using appropriate fallback behavior.

It is always possible to write conditional code to run under different XSLT versions by using the use-when feature described in 3.14 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 3.0 processor are ignored, rather than being treated as errors.

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

The detailed rules follow.

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

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

When an element is processed with forwards compatible behavior:

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

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

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

    1. If the element has one or more xsl:fallback children, then no error is 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 3.0 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 3.0 processor will process the following stylesheet without error, although the stylesheet includes elements from the XSLT namespace that are not defined in this specification:

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

Note:

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

Example: Testing the XSLT Version

For example,

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

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

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

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

Note:

It is appropriate to use this error code when the resource cannot be retrieved, or when the retrieved resource is not well formed XML. If the resource contains XML than can be parsed but that violates the rules for stylesheet modules, then a more specific error code may be more appropriate.

3.12.2 Stylesheet Inclusion

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

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

The xsl:include declaration has a required href attribute whose value is a URI reference identifying the stylesheet module to be included. This attribute is used as described in 3.12.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.12.3 Stylesheet Import

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

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.12.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.12.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="3.0"
                xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <xsl:import href="article.xsl"/>
  <xsl:import href="bigfont.xsl"/>
  <xsl:attribute-set name="note-style">
    <xsl:attribute name="font-style">italic</xsl:attribute>
  </xsl:attribute-set>
</xsl:stylesheet>

[Definition: 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.13 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 Accessor DM30. 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="3.0"
                    xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
                    xmlns:fo="http://www.w3.org/1999/XSL/Format">
    <xsl:import href="doc.xsl"/>
    <xsl:template match="id('foo')">
      <fo:block font-weight="bold"><xsl:apply-templates/></fo:block>
    </xsl:template>
    <xsl:template match="xsl:stylesheet">
      <!-- ignore -->
    </xsl:template>
    </xsl:stylesheet>
  </head>
  <body>
    <para id="foo">
    ...
    </para>
  </body>
</doc>

Note:

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

Note:

The above example uses the pseudo-attribute type="application/xslt+xml" in the xml-stylesheet processing instruction to denote an XSLT stylesheet. This is the officially registered media type for XSLT: see 3.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.14 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 valueXP30 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 Lexical 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 extension 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 absent
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 scopeFO30. 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-dateFO30 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.15 Built-in Types

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

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

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

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

A schema-aware XSLT processor additionally supports:

Note:

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

An implementation may define mechanisms that allow additional schema components to be added to the in-scope schema components for the stylesheet. For example, the mechanisms used to define extension functions (see 23.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.16 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 26 Conformance.

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

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

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

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

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

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 3.0 and XQuery 3.0 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 3.0 can be used with either of these XML versions.

Construction of the XDM tree is outside the scope of this specification, so XSLT 3.0 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 25 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 3.0 and XPath 3.0, 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 3.0 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 datatypes 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 3.0 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:accumulator
    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: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 Accessor DM30.]

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 idFO30 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, docFO30, or collectionFO30. 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 NameTestsXP30; an element name matches an xsl:strip-space or xsl:preserve-space element if it matches one of the NameTestsXP30. An element matches a NameTestXP30 if and only if the NameTestXP30 would be true for the element as an XPath node test.

The effect of xsl:strip-space and xsl:preserve-space is local to the package in which they appear. Declarations within a library package only affect the handling of documents loaded using a call on the document, docFO30, or collectionFO30 functions appearing lexically within the same package. Declarations within the top-level package also affect the processing of the main input document.

[ERR XTSE0270] It is a static error if within any package the same NameTestXP30 appears in both an xsl:strip-space and an xsl:preserve-space declaration if both have the same import precedence. Two NameTests are considered the same if they match the same set of names (which can be determined by comparing them after expanding namespace prefixes to URIs).

Otherwise, when more than one xsl:strip-space and xsl:preserve-space element within the relevant package matches, the best matching element is determined by the best matching NameTestXP30. This is determined in the same way as with The rules are similar to those for template rules:

  • First, any match with lower import precedence than another match is ignored.

  • Next, any match that has a lower default priority than the default priority of another match is ignored.

  • If several matches have the same default priority (which can only happen if one of the NameTests takes the form *:local and the other takes the form prefix:*), then the declaration that appears last in declaration order is used.

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

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 idFO30 and idrefFO30 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.

There is an assumption that information about unparsed entities is available at all times during the processing of a document. This has two implications: firstly, the processor may need to read ahead at the start of the document to determine this information so that it is available while processing the document root node; and secondly, the information then needs to be retained for the duration of the processing.

Expressions such as (/) instanceof document-node(element(invoice)) also require look-ahead as far as the start-tag of the first element.

A streaming processor is required to read only as much of the source document as is needed to generate correct stylesheet output. It is not required to read the full source document merely in order to satisfy the requirement imposed by the XML Recommendation that an XML Processor must report violations of well-formedness in the input.

More detailed rules are defined in 19.3 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 datatypes 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 3.0 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 25.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 25.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 a qualified name: that is, it consists of a local name and an optional namespace URI.

In most cases where such names are written in a stylesheet, the syntax for expressing the name is given by the production EQNameXP30 in the XPath specification. In practice, this means that three forms are permitted:

  • A simple NCName appearing on its own (without any prefix). This represents the local name of the object. The interpretation of unprefixed names is described below.

  • A lexical QName written in the form NCName ":" NCName where the first part is a namespace prefix and the second part is the local name. The namespace part of the object's name is then derived from the prefix by examining the in-scope namespace bindings of the element node in the stylesheet where the name appears.

  • A URIQualifiedNameXP30 in the form "Q{" URI? "}" NCName where the two parts of the name, that is the namespace part and the local part, both appear explicitly. If the URI part is omitted (for example Q{}local), the resulting expanded QName is a QName whose namespace part is absent.

Note:

There are a few places where the third form, a URIQualifiedName, is not permitted. These include the name attribute of xsl:element and xsl:attribute (which have a separate namespace attribute for the purpose), and constructs defined by other specifications. For example, names appearing within an embedded xs:schema element must follow the XSD rules.

[Definition: An expanded QName is a value in the value space of the xs:QName datatype as defined in the XDM data model (see [Data Model]): that is, a triple containing namespace prefix (optional), namespace URI (optional), and local name. Two expanded QNames are equal if the namespace URIs are the same (or both absent) and the local names are the same. The prefix plays no part in the comparison, but is used only if the expanded QName needs to be converted back to a string.]

[Definition: An EQName is a string representing a expanded QName where the string, after removing leading and trailing whitespace, is in the form defined by the EQNameXP30 production in the XPath specification.]

Note:

At the time of publication, the most recent public working draft of XPath 3.0 uses the syntax "uri":local for an EQName. However, the next public working draft is expected to use the syntax Q{uri}local.

[Definition: A lexical QName is a string representing a expanded QName where the string, after removing leading and trailing whitespace, is within the lexical space of the xs:QName datatype as defined in XML Schema (see [XML Schema Part 2]): that is, a local name optionally preceded by a namespace prefix and a colon.]

Note that every lexical QName is an EQName, but the converse is not true.

The following rules are used when interpreting a lexical QName:

  1. [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 lexical QName.]

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

    [ERR XTSE0280] In the case of a prefixed lexical QName used as the value (or as part of the value) of an attribute in the stylesheet, or appearing within an XPath expression in the stylesheet, it is a static error if the defining element has no namespace node whose name matches the prefix of the lexical QName.

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

  3. If the lexical QName has no prefix, then:

    1. 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 Lexical QNames in Expressions and Patterns.

    2. If the name is in one of the following categories, then the default namespace of the defining element is used:

      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

    3. In all other cases, a lexical QName with no prefix represents an expanded QName in no namespace (that is, an xs:QName value in which both the prefix and the namespace URI are absent).

5.2 Unprefixed Lexical 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 3.0]; 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 Nodes DM30) 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 3.0 [XPath 3.0]. Expressions are used in XSLT for a variety of purposes including:

  • selecting nodes for processing;

  • specifying conditions for different ways of processing a node;

  • generating text to be inserted in a result tree.

[Definition: Within this specification, the term XPath expression, or simply expression, means a string that matches the production ExprXP30 defined in [XPath 3.0].]

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.11 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 ExprXP30, 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 3.0].

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

The transformation fails with a type error if an XPath expression raises a type error, or if the result of evaluating the XPath expression is evaluated and raises a type error, or if the XPath processor signals a type error during static analysis of an expression. Error codes are defined in [XPath 3.0].

[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 3.0] 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 3.0 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 contextXP30 which contains all the information that can affect the result of evaluating an expression. The expression context has two parts, the static contextXP30, and the dynamic contextXP30. The components that make up the expression context are defined in the XPath specification (see Section 2.1 Expression Context XP30). 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 contextXP30 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.

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 deterministicFO30, meaning that if they are called twice during the same execution scopeFO30, with the same arguments, then they return the same results (see Section 1.6 Terminology FO30). In XSLT, the execution of a stylesheet defines the execution scope. This means, for example, that if the function current-dateTimeFO30 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 Context XP30 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 docFO30 and collectionFO30 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.14 Conditional Element Inclusion.

[Definition: A component of the context that has no value is said to be absent.] This is a distinguishable state, and is not the same as having the empty sequence as its value.

5.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 20.4.1 fn:current.

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

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

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

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 contextXP30 of an XPath expression are initialized.

  • The dynamic variablesXP30 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 timezoneXP30 is implementation-defined.

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

    The available documentsXP30 are defined as part of the XPath 3.0 dynamic context to support the docFO30 function, but this component is also referenced by the similar XSLT document function: see 20.1 fn:document. This variable defines a mapping between URIs passed to the docFO30 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 documentsXP30 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 collectionXP30 is implementation-defined. This allows options such as setting the default collection to be an empty sequence, or to be absent.

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 5 (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 absent xsl:for-each-group, xsl:merge non-contextual function calls
current grouping key absent xsl:for-each-group, xsl:merge 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 dynamic function invocationsXP30, (that is calls to function items as permitted by XPath 3.0). 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 contextual function call such as current-group() cannot be used in a dynamic function invocation: it is not possible to form a function item such as current-group#0.

5.5 Patterns

In XSLT 3.0, 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 20.2 Keys).

[Definition: A pattern specifies a set of conditions on an item. An item that satisfies the conditions matches the pattern; an item that does not satisfy the conditions does not match the pattern.]

There are 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 ItemTypeXP30 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.

Note:

The specification uses the phrases an item matches a pattern and a pattern matches an item interchangeably. They are equivalent: an item matches a pattern if and only if the pattern matches the item.

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

The lexical rules for patterns are the same as the lexical rules for XPath expressions, as defined in Section A.2 Lexical structure XP30. 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.10 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 ')' PredicateListXP30
[5]    TypePattern    ::=    '~' ItemTypeXP30 PredicateListXP30
[6]    PathPattern    ::=    RelativePathPattern
| '/' RelativePathPattern?
| '//' RelativePathPattern
| RootedPattern
[7]    RootedPattern    ::=    ( VarRefRoot | DocCall | IdCall | ElementWithIdCall | KeyCall )
(('/' | '//') RelativePathPattern)?
[8]    VarRefRoot    ::=    VarRefXP30
[9]    RelativePathPattern    ::=    PatternStep (('/' | '//') PatternStep)*
[10]    PatternStep    ::=    PatternAxis? NodeTestXP30 PredicateListXP30
[11]    PatternAxis    ::=    (('child' | 'attribute' | 'namespace' | '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    ::=    LiteralXP30 | VarRefXP30

The constructs ItemTypeXP30, NodeTestXP30, PredicateListXP30, VarRefXP30, and LiteralXP30 are part of the XPath expression language, and are defined in [XPath 3.0].

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

Note:

As with XPath expressions, the pattern / union /* can be parsed in two different ways, and the chosen interpretation is to treat union as an element name rather than as an operator. The other interpretation can be achieved by writing (/) union (/*)

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

First the pattern is converted to an expression, called the equivalent expression. The equivalent expression to a Pattern is the XPath expression that takes the same lexical form as the Pattern as written, with two adjustments:

  1. Any occurrence of ~ ItemType in a TypePattern is replaced by .[. instance of ItemType]. For example, the equivalent expression for the pattern ~xs:integer[. gt 5] is .[. instance of xs:integer][. gt 5]

  2. If the Pattern 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.3.5 Abbreviated Syntax XP30), 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.

    The axes child-or-top, attribute-or-top, and namespace-or-top are introduced only for definitional purposes. They cannot be used explicitly in a user-written pattern or expression.

    Note:

    The purpose of this adjustment is to ensure that a pattern such as person matches any element named person, even if it has no parent; and similarly, that the pattern @width matches any attribute named width, even a parentless attribute. The rule also ensures that a pattern using a NodeTest of the form document-node(...) matches a document node. The pattern node() will match any element, text node, comment, or processing instruction, whether or not it has a parent. For backwards compatibility reasons, the pattern node(), when used without an explicit axis, does not match document nodes, attribute nodes, or namespace nodes. The rules are also phrased to ensure that positional patterns of the form para[1] continue to count nodes relative to their parent, if they have one. To match any node at all, XSLT 3.0 allows the pattern ~node() to be used (note the tilde).

The meaning of the pattern is then defined in terms of the semantics of the equivalent expression, denoted below as EE.

Specifically, an item N matches a pattern P if either of the following applies, where EE is the equivalent expression to P:

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

  2. N is not a node, and the result of evaluating the expression exists(EE) with a singleton focus based on N is the boolean value true.

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 idFO30, element-with-idFO30, 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 StringLiteralXP30 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 ExprXP30, 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 implementation-dependent, 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, docFO30 or collectionFO30 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, docFO30 or collectionFO30 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 implementation-dependent.

In an Infoset (see [XML Information Set]) created from a document conforming to [Namespaces in XML], it will always be true that if a parent element has an in-scope namespace with a non-empty namespace prefix, then its child elements will also have an in-scope namespace with the same namespace prefix, though possibly with a different namespace URI. This constraint is removed in [Namespaces in XML 1.1]. XSLT 3.0 supports the creation of result trees that do not satisfy this constraint: the namespace fixup process does not add a namespace node to an element merely because its parent node in the result tree has such a namespace node. However, the process of constructing the children of a new element, which is described in 5.7.1 Constructing Complex Content, does cause the namespaces of a parent element to be inherited by its children unless this is prevented using [xsl:]inherit-namespaces="no" on the instruction that creates the parent element.

Note:

This has implications on serialization, defined in [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 datatype as defined in [XML Schema Part 2].] Note that this is a wider definition than that in [RFC3986]: in particular, it is designed to accommodate Internationalized Resource Identifiers (IRIs) as described in [RFC3987], and thus allows the use of non-ASCII characters without escaping.

URI References are used in XSLT with three main roles:

  • As namespace URIs

  • As collation URIs

  • As identifiers for resources such as stylesheet modules; these resources are typically accessible using a protocol such as HTTP. Examples of such identifiers are the URIs used in the href attributes of xsl:import, xsl:include, 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? = eqname
  priority? = decimal
  mode? = tokens
  as? = sequence-type
  visibility? = "public" | "private" | "final" | "abstract" >
  <!-- Content: (xsl:context-item?, xsl:param*, sequence-constructor) -->
</xsl:template>

[Definition: An xsl:template declaration defines a template, which contains a sequence constructor ; this sequence constructor is evaluated to determine the result of the template. A template can serve either as a template rule, invoked by matching items against a pattern, or as a named template, invoked explicitly by name. It is also possible for the same template to serve in both capacities.]

[ERR XTSE0500] An xsl:template element must have either a match attribute or a name attribute, or both. An xsl:template element that has no match attribute must have no mode attribute and no priority attribute. An xsl:template element that has no name attribute must have no visibility attribute.

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

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

If an xsl:context-item element is present as the first child element, it defines whether the template requires a context item to be supplied, and if so, what the type of the context item must be. If this template is the initial template, then this has the effect of placing constraints on the initial context item for the transformation as a whole.

The use attribute of xsl:context-item takes the value required, optional, or prohibited. If the value required is specified, then there must be a context item. (This will automatically be the case if the template is invoked using xsl:apply-templates, xsl:apply-imports, or xsl:next-match, but not if it is invoked using xsl:call-template). If the value optional is specified, or if the attribute is omitted, or if the xsl:context-item element is omitted, then there may or may not be a context item when the template is invoked. If the containing xsl:template element has no name attribute then the only permitted value is required. If the value prohibited is specified, then there will be no context item available to the body template (if the calling template has a context item, it will not be made available to the called template).

The as attribute of the xsl:context-item defines the required type of the context item supplied to the template if one is supplied. The default value is as="item()". If a context item is supplied (which will automatically be the case if the template is invoked using xsl:apply-templates, xsl:apply-imports, or xsl:next-match) then if will be converted to the required type by applying the function conversion rules; a type error ([see ERR XTTE0590]) occurs if conversion to the required type is not possible. The processor may signal a type error statically if the required context item type is incompatible with the match pattern, that is, if no item that satisfies the match pattern can also satisfy the required context item type.

The xsl:context-item element plays no part in deciding whether and when the template rule is invoked in response to an xsl:apply-templates instruction.

[ERR XTTE3090] It is a type error if the xsl:context-item child of xsl:template specifies that a context item is required and none is supplied by the caller, that is, if the context item is absent at the point where xsl:call-template is evaluated.

If an as attribute of the xsl:template element is present, the as attribute defines the required type of the result. The result of evaluating the sequence constructor is then converted to the required type using the 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.

If the visibility attribute is present with the value abstract then (a) the sequence constructor defining the template body must be empty: that is, the only permitted children are xsl:context-item and xsl:param, and (b) there must be no match attribute.

If the parent of the xsl:template element is an xsl:override element, then there must be a name attribute and no match attribute, and the package that is the target of the containing xsl:use-package element must contain among its components a named template whose symbolic identifier is the same as this named template, and which has a compatible signature.

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 signaled. 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 an on-multiple-match attribute with the value fail.

      Issue 6 (error-XTRE0540):

      This error is no longer recoverable; should the error code change?

    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 3.0 this situation is not an error unless the attribute value on-multiple-match="fail" is specified in the mode declaration. It is also possible to request warnings when this condition arises, by means of the attribute warnings-on-multiple-match="yes".

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 PredicateListXP30, then:

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

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

    3. If the ItemTypeXP30 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 ItemTypeXP30 is a union type, the priority is the minimum priority of the atomic types in the transitive membership of the union, minus 0.5. This means for example that the priority of a type formed as the union of xs:date and xs:dateTime has a lower priority than xs:dateTime but a higher priority than xs:anyAtomicType, while a type formed as the union of xs:ID and xs:IDREF has a lower priority than xs:IDREF but a higher priority than xs:NCName.

    5. If the ItemTypeXP30 is any other NodeTestXP30, 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).

    6. If the ItemTypeXP30 is an AnyFunctionTestXP30 the priority is -1, while for any other TypedFunctionTestXP30, the priority is 0 (zero).

    7. If the ItemTypeXP30 is a MapType of the form map(*), then the priority is +0.5, while for a MapType of the form map(K, V) the priority is the same as that of the pattern ~K.

  4. If the pattern (in its entirety) is a TypePattern with a non-empty PredicateListXP30, then the priority is that of the ItemTypeXP30 in the absence of the PredicateListXP30, 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 an EQName optionally preceded by a PatternAxis or has the form processing-instruction( StringLiteralXP30 ) 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 ElementTestXP30 or AttributeTestXP30, 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 DocumentTestXP30, then if it includes no ElementTestXP30 or SchemaElementTestXP30 the priority is −0.5. If it does include an ElementTestXP30 or SchemaElementTestXP30, then the priority is the same as the priority of that ElementTestXP30 or SchemaElementTestXP30, 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 NodeTestXP30, 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 20.1 fn:document) or when processing temporary trees.]

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

6.6.1 Declaring Modes

<!-- Category: declaration -->
<xsl:mode
  name? = eqname
  streamable? = "yes" | "no"
  initial? = "yes" | "no"
  on-no-match? = "deep-copy" | "shallow-copy" | "deep-skip" | "shallow-skip" | "text-only-copy" | "fail"
  on-multiple-match? = "use-last" | "fail"
  warning-on-no-match? = "yes" | "no"
  warning-on-multiple-match? = "yes" | "no"
  typed? = "yes" | "no" | "strict" | "lax" | "unspecified"
  visibility? = "public" | "private" | "final" >
  <!-- 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 an expanded QName.

A stylesheet may contain multiple xsl:mode declarations and may include or import stylesheet modules that also contain xsl:mode declarations. The name of an xsl:mode declaration is the value of its name attribute, if any.

[Definition: All the xsl:mode declarations in a 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.

Attribute Values Meaning
name A EQName 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 19.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 deep-copy, shallow-copy, deep-skip, shallow-skip, text-only-copy or fail (default text-only-copy) Determines selection of the built-in template rules that are used to process 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.
typed One of yes, no, strict, lax, or unspecified. The default is unspecified. Informs the processor whether the nodes to be processed by template rules in this mode are to be typed or untyped. If the value yes is specified, then all nodes processed in this mode must be typed (a dynamic error occurs if xsl:apply-templates in this mode selects an element or attribute whose type annotation is xs:untyped or xs:untypedAtomic). If the value no is specified, then all nodes processed in this mode must be untyped (a dynamic error occurs if xsl:apply-templates in this mode selects an element or attribute whose type annotation is anything other than xs:untyped or xs:untypedAtomic). The value strict is equivalent to yes, with the additional provision that within the match pattern of every template rule in this mode, any NameTest used without a PatternAxis in the first PatternStep of a RelativePathPattern is interpreted as a SchemaElementTest: for example, match="product" is interpreted as match="schema-element(product)", while match="product/code" is interpreted as match="schema-element(product)/code". The value lax is equivalent to strict, except that the interpretation of a NameTest as a SchemaElementTest occurs only if it matches the name of a global element declaration in the in-scope schema declarations. The value unspecified is equivalent to omitting the attribute, and places no constraints on whether the nodes to be processed in this mode are typed or untyped.

[ERR XTTE3100] It is a type error if an xsl:apply-templates instruction in a particular mode selects an element or attribute whose type is xs:untyped or xs:untypedAtomic when the typed attribute of that mode specifies the value yes, strict, or lax.

[ERR XTTE3110] It is a type error if an xsl:apply-templates instruction in a particular mode selects an element or attribute whose type is anything other than xs:untyped or xs:untypedAtomic when the typed attribute of that mode specifies the value no.

[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 19.3 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? = sequence-type
  use? = "required" | "optional" | "prohibited" />

If the as attribute is present then its value must be an ItemTypeXP30. 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 error if the conversion is not possible.

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

When the xsl:context-item element appears as a child of xsl:mode, the only permitted value for the use attribute is required, indicating that an initial context item must be supplied by the calling application when this mode is selected as the initial mode.

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 error is signaled if the supplied context item does not match its required type. The error code 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="deep-copy">
  <xsl:context-item as="schema-element(invoice)"/>
</xsl:mode>
<xsl:mode name="po" initial="yes" on-no-match="deep-copy">
  <xsl:context-item as="schema-element(purchase-order)"/>
</xsl:mode>
<xsl:mode name="format-address" initial="no"/>

Note:

The xsl:context-item element can also appear as a child of xsl:template to define the type of the context item passed to a named template. If the named template is also the initial template, then this constrains the initial context item for the transformation as a whole.

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:

  • an EQName, 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 or xsl:template declaration 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 six 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 six values deep-copy, shallow-copy, deep-skip, shallow-skip, text-only-copy, or fail, the default being text-only-copy. The effect of these six sets of built-in template rules is explained in the following subsections.

6.7.1 Built-in Templates: Text-only Copy

The effect of choosing on-no-match="text-only-copy" for a mode is that the textual content of the source document is retained while losing the markup, except where explicit template rules dictate otherwise. When an element is encountered for which there is no explicit template rule, the processing continues with the children of that element. Text nodes are copied to the output.

The built-in rule for document nodes and element nodes is equivalent to calling xsl:apply-templates with no select attribute, and with the mode attribute set to #current. If the built-in rule was invoked with parameters, those parameters are passed on in the implicit xsl:apply-templates instruction.

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: Deep Copy

The effect of choosing on-no-match="deep-copy" for a mode is that an unmatched element in the source tree is copied unchanged to the output, together with its entire subtree. The subtree is copied unconditionally, without attempting to match nodes in the subtree against template rules.

When this default action is selected for a mode M, all items are processed using a template rule that is equivalent to the following:

<xsl:template match="~item()" mode="M">
  <xsl:copy-of select="." validation="preserve"/>
</xsl:template>

6.7.3 Built-in Templates: Shallow Copy

The effect of choosing on-no-match="shallow-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="3.0"
     xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
                                  
<xsl:mode on-no-match="shallow-copy" streamable="yes"/>

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

</xsl:stylesheet>

6.7.4 Built-in Templates: Deep Skip

The effect of choosing on-no-match="deep-skip" for a mode is that an unmatched element in the source tree is skipped in its entirety; neither the element nor any of its descendants is copied to the result tree or processed any further.

When this default action is selected for a mode M, all items are processed using a template rule that is equivalent to the following:

<xsl:template match="~item()" mode="M"/>

6.7.5 Built-in Templates: Shallow Skip

The effect of choosing on-no-match="shallow-skip" for a mode is to drop both the textual content and the markup from the result document, except where there is an explicit user-written template rules that dictates otherwise.

The built-in rule for document nodes and element nodes is the same as for on-no-match="text-only-copy": 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.6 Built-in Templates: Fail

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

The built-in template rule is effectively:

<xsl:template match="~item()" mode="M">
  <xsl:message terminate="yes" 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 3.0 processor, but can be used to define fallback behavior when the stylesheet is processed by an XSLT 1.0 processor with forwards compatible behavior.

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
  select? = expression >
  <!-- Content: (sequence-constructor) -->
</xsl:break>

<xsl:on-completion
  select? = expression >
  <!-- 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 lastFO30 will be disallowed.

The xsl:break and xsl:on-completion elements may have either a select attribute or a non-empty contained sequence constructor but not both. The effect of the element in both cases is obtained by evaluating the select expression if present or the contained sequence constructor otherwise; if neither is present, the value is an empty sequence.

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

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

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

[ERR XTSE3120] It is a static error if an xsl:break or xsl:next-iteration element appears other than in a tail position within the sequence constructor forming the body of an xsl:iterate instruction.

[ERR XTSE3130] It is a static error if the name attribute of an xsl:with-param child of an xsl:next-iteration element does not match the name attribute of an xsl:param child of the innermost containing xsl:iterate instruction.

Parameter names in xsl:with-param must be unique: [see ERR XTSE0670].

The result of the xsl:iterate instruction is the concatenation of the sequences that result from the repeated evaluation of the contained sequence constructor, followed by the sequence that results from evaluating the xsl:break or xsl:on-completion element if any.

Any xsl:param element that appears as a child of xsl:iterate declares a parameter whose value may vary from one iteration to the next. The initial value of the parameter is the value obtained according to the rules given in 9.3 Values of Variables and Parameters. The dynamic context for evaluating the initial value of an xsl:param element is the same as the dynamic context for evaluating the select expression of the xsl:iterate instruction (the context item is thus not the first item in the input sequence).

On the first iteration a parameter always takes its initial value (which may depend on variables or other aspects of the dynamic context). Subsequently:

  • If an xsl:next-iteration instruction is evaluated, then parameter values for processing the next item in the input sequence can be set in the xsl:with-param children of that instruction; in the absence of an xsl:with-param element that names a particular parameter, that parameter will retain its value from the previous iteration.

  • If an xsl:break instruction is evaluated, no further items in the input sequence are processed.

  • If neither an xsl:next-iteration nor an xsl:break instruction is evaluated, then the next item in the input sequence is processed using parameter values that are unchanged from the previous iteration.

The xsl:next-iteration instruction contributes nothing to the result sequence (technically, it returns an empty sequence). The instruction supplies parameter values for the next iteration, which are evaluated according to the rules given in 9.8 Setting Parameter Values; if there are no further items in the input sequence then it supplies parameter values for use while evaluating the body of the xsl:on-completion element if any.

The xsl:break instruction indicates that the iteration should terminate without processing any remaining items from the input sequence. The select expression or contained sequence constructor is evaluated using the same context item, position, and size as the xsl:break instruction itself, and the result is appended to the result of the xsl:iterate instruction as a whole.

If neither an xsl:next-iteration nor an xsl:break instruction is evaluated, the next item in the input sequence is processed with parameter values unchanged from the previous iteration; if there are no further items in the input sequence, the iteration terminates.

The optional xsl:on-completion element (which is not technically an instruction and is not technically part of the sequence constructor) is evaluated when the input sequence is exhausted. It is not evaluated if the evaluation is terminated using xsl:break. During evaluation of this sequence constructor the context item, position, and size are absent (that is, any reference to these values is an error). However, the values of the parameters to xsl:iterate are available, and take the values supplied by the xsl:next-iteration instruction evaluated while processing the last item in the sequence.

If the input sequence is empty, then the result of the xsl:iterate instruction is the result of evaluating the sequence constructor forming the body of the xsl:on-completion element, using the initial values of the xsl:param elements. If there is no xsl:on-completion element, the result is an empty sequence.

Note:

Conceptually, xsl:iterate behaves like a tail-recursive function. The xsl:next-iteration instruction then represents the recursive call, supplying the tail of the input sequence as an implicit parameter. There are two main reasons for providing the xsl:iterate instruction. One is that many XSLT users find writing recursive functions to be a difficult skill, and this construct promises to be easier to learn. The other is that recursive function calls are difficult for an optimizer to analyze. Because xsl:iterate is more constrained than a general-purpose head-tail recursive function, it should be more amenable to optimization. In particular, when the instruction is used in conjunction with xsl:stream, it is designed to make it easy for the implementation to use streaming techniques, processing the nodes in an input document sequentially as they are read, without building the entire document tree in memory.

The examples below use xsl:iterate in conjunction with the xsl:stream instruction. This is not the only way of using xsl:iterate, but it illustrates the way in which the two features can be combined to achieve streaming of a large input document.

Example: Using xsl:iterate to compute cumulative totals

Suppose that the input XML document has this structure

<transactions>
  <transaction date="2008-09-01" value="12.00"/>
  <transaction date="2008-09-01" value="8.00"/>
  <transaction date="2008-09-02" value="-2.00"/>
  <transaction date="2008-09-02" value="5.00"/>
</transactions>

and that the requirement is to transform this to:

<account>
  <balance date="2008-09-01" value="12.00"/>
  <balance date="2008-09-01" value="20.00"/>
  <balance date="2008-09-02" value="18.00"/>
  <balance date="2008-09-02" value="23.00"/>
</account>

This can be achieved using the following code, which is designed to process the transaction file using streaming:

<account>
  <xsl:stream href="transactions.xml">
    <xsl:iterate select="transactions/transaction">
      <xsl:param name="balance" select="0.00" as="xs:decimal"/>
      <xsl:variable name="newBalance" 
                    select="$balance + xs:decimal(@value)"/>
      <balance date="{@date}" value="{$newBalance}"/>
      <xsl:next-iteration>
        <xsl:with-param name="balance" select="$newBalance"/>
      </xsl:next-iteration>
    </xsl:iterate>
  </xsl:stream>
</account>

The following example modifies this by only outputting the information for the first day's transactions:

<account>
  <xsl:stream href="'transactions.xml">
    <xsl:iterate select="transactions/transaction">
      <xsl:param name="balance" select="0.00" as="xs:decimal"/>
      <xsl:param name="prevDate" select="()" as="xs:date?"/>
      <xsl:variable name="newBalance" 
                    select="$balance + xs:decimal(@value)"/>
      <xsl:variable name="thisDate" 
                    select="xs:date(@date)"/>
      <xsl:choose>
        <xsl:when test="empty($prevDate) or $thisDate eq $prevDate">
          <balance date="{$thisDate}" 
                   value="{format-number($newBalance, '0.00')}"/>
          <xsl:next-iteration>
            <xsl:with-param name="balance" select="$newBalance"/>
            <xsl:with-param name="prevDate" select="$thisDate"/>
          </xsl:next-iteration>
        </xsl:when>
        <xsl:otherwise>
          <xsl:break/>
        </xsl:otherwise>
      </xsl:choose>
    </xsl:iterate>
  </xsl:stream>
</account>

The following code outputs the balance only at the end of each day, together with the final balance:

<account>
  <xsl:stream href="transactions.xml">
    <xsl:iterate select="transactions/transaction">
      <xsl:param name="balance" select="0.00" as="xs:decimal"/>
      <xsl:param name="prevDate" select="()" as="xs:date?"/>
      <xsl:variable name="newBalance" 
                    select="$balance + xs:decimal(@value)"/>
      <xsl:variable name="thisDate" select="xs:date(@date)"/>
      <xsl:if test="exists($prevDate) and $thisDate ne $prevDate">
        <balance date="{$prevDate}" 
                 value="{format-number($balance, '0.00')}"/>
      </xsl:if>
      <xsl:next-iteration>
        <xsl:with-param name="balance" select="$newBalance"/>
        <xsl:with-param name="prevDate" select="$thisDate"/>
      </xsl:next-iteration>
      <xsl:on-completion>
        <balance date="{$prevDate}" 
                 value="{format-number($balance, '0.00')}"/>
      </xsl:on-completion>
    </xsl:iterate>
  </xsl:stream>
</account>

If the sequence of transactions is empty, this code outputs a single element: <balance date="" value="0.00"/>.

 

Example: Collecting multiple values in a single pass

Problem: Given a sequence of employee elements, find the employees having the highest and lowest salary, while processing each employee only once.

Solution:

<xsl:stream href="employees.xml">
  <xsl:iterate select="employees/employee">
    <xsl:param name="highest" as="element(employee)*"/>
    <xsl:param name="lowest" as="element(employee)*"/>
    <xsl:variable name="is-new-highest" as="xs:boolean"
                  select="empty($highest[@salary ge current()/@salary])"/>
    <xsl:variable name="is-equal-highest" as="xs:boolean" 
                  select="exists($highest[@salary eq current()/@salary])"/> 
    <xsl:variable name="is-new-lowest" as="xs:boolean" 
                  select="empty($lowest[@salary le current()/@salary])"/>
    <xsl:variable name="is-equal-lowest" as="xs:boolean" 
                  select="exists($lowest[@salary eq current()/@salary])"/> 
    <xsl:variable name="new-highest-set" as="element(employee)*"
                  select="if ($is-new-highest) then .
                          else if ($is-equal-highest) then ($highest, .)
                          else $highest"/>
    <xsl:variable name="new-lowest-set" as="element(employee)*"
                  select="if ($is-new-lowest) then .
                          else if ($is-equal-lowest) then ($lowest, .)
                          else $lowest"/>
    <xsl:next-iteration>
      <xsl:with-param name="highest" select="$new-highest-set"/>
      <xsl:with-param name="lowest" select="$new-lowest-set"/>
    </xsl:next-iteration>
    <xsl:on-completion>
      <highest-paid-employees>
        <xsl:value-of select="$highest/name"/>
      </highest-paid-employees>
      <lowest-paid-employees>
        <xsl:value-of select="$lowest/name"/>
      </lowest-paid-employees>  
    </xsl:on-completion>
   </xsl:iterate>
 </xsl:stream>

If the input sequence is empty, this code outputs an empty highest-paid-employees element and an empty lowest-paid-employees element.

 

Example: Processing the last item in a sequence specially

When streaming, some limited look-ahead is needed to determine whether the item being processed is the last in a sequence. The lastFO30 function cannot be used in guaranteed-streamable code. The xsl:iterate instruction provides a solution to this problem.

Problem: render the last paragraph in a section in some special way, for example by using bold face. (The actual rendition is achieved by processing the paragraph with mode last-para.)

The solution uses xsl:iterate to maintain a one-element lookahead by explicit coding:

<xsl:template match="section" mode="streaming">
   <xsl:iterate select="para">
     <xsl:param name="prev" select="()" as="element(para)?"/>
     <xsl:if test="$prev">
       <xsl:apply-templates select="$prev"/>
     </xsl:if>
     <xsl:next-iteration>
       <xsl:with-param name="prev" select="."/>
     </xsl:next-iteration>
     <xsl:on-completion>
       <xsl:apply-templates select="$prev" mode="last-para"/>      
     </xsl:on-completion>
   </xsl:iterate>
 </xsl:template>

8 Conditional Processing

There are two instructions in XSLT that support conditional processing: xsl:if and xsl:choose. The xsl:if instruction provides simple if-then conditionality; the xsl:choose instruction supports selection of one choice when there are several possibilities.

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

8.1 Conditional Processing with xsl:if

<!-- Category: instruction -->
<xsl:if
  test = expression >
  <!-- Content: sequence-constructor -->
</xsl:if>

The xsl:if element has a mandatory test attribute, which specifies an expression. The content is a sequence constructor.

The result of the xsl:if instruction depends on the effective boolean valueXP30 of the expression in the test attribute. The rules for determining the effective boolean value of an expression are given in [XPath 3.0]: they are the same as the rules used for XPath conditional expressions.

If the effective boolean value of the expression is true, then the sequence constructor is evaluated (see 5.7 Sequence Constructors), and the resulting node sequence is returned as the result of the xsl:if instruction; otherwise, the sequence constructor is not evaluated, and the empty sequence is returned.

Example: Using xsl:if

In the following example, the names in a group of names are formatted as a comma separated list:

<xsl:template match="namelist/name">
  <xsl:apply-templates/>
  <xsl:if test="not(position()=last())">, </xsl:if>
</xsl:template>

The following colors every other table row yellow:

<xsl:template match="item">
  <tr>
    <xsl:if test="position() mod 2 = 0">
       <xsl:attribute name="bgcolor">yellow</xsl:attribute>
    </xsl:if>
    <xsl:apply-templates/>
  </tr>
</xsl:template>

8.2 Conditional Processing with xsl:choose

<!-- Category: instruction -->
<xsl:choose>
  <!-- Content: (xsl:when+, xsl:otherwise?) -->
</xsl:choose>

<xsl:when
  test = expression >
  <!-- Content: sequence-constructor -->
</xsl:when>

<xsl:otherwise>
  <!-- Content: sequence-constructor -->
</xsl:otherwise>

The xsl:choose element selects one among a number of possible alternatives. It consists of a sequence of one or more xsl:when elements followed by an optional xsl:otherwise element. Each xsl:when element has a single attribute, test, which specifies an expression. The content of the xsl:when and xsl:otherwise elements is a sequence constructor.

When an xsl:choose element is processed, each of the xsl:when elements is tested in turn (that is, in the order that the elements appear in the stylesheet), until one of the xsl:when elements is satisfied. If none of the xsl:when elements is satisfied, then the xsl:otherwise element is considered, as described below.

An xsl:when element is satisfied if the effective boolean valueXP30 of the expression in its test attribute is true. The rules for determining the effective boolean value of an expression are given in [XPath 3.0]: they are the same as the rules used for XPath conditional expressions.

The content of the first, and only the first, xsl:when element that is satisfied is evaluated, and the resulting sequence is returned as the result of the xsl:choose instruction. If no xsl:when element is satisfied, the content of the xsl:otherwise element is evaluated, and the resulting sequence is returned as the result of the xsl:choose instruction. If no xsl:when element is satisfied, and no xsl:otherwise element is present, the result of the xsl:choose instruction is an empty sequence.

Only the sequence constructor of the selected xsl:when or xsl:otherwise instruction is evaluated. The test expressions for xsl:when instructions after the selected one are not evaluated.

Example: Using xsl:choose

The following example enumerates items in an ordered list using arabic numerals, letters, or roman numerals depending on the depth to which the ordered lists are nested.

<xsl:template match="orderedlist/listitem">
  <fo:list-item indent-start='2pi'>
    <fo:list-item-label>
      <xsl:variable name="level"
                    select="count(ancestor::orderedlist) mod 3"/>
      <xsl:choose>
        <xsl:when test='$level=1'>
          <xsl:number format="i"/>
        </xsl:when>
        <xsl:when test='$level=2'>
          <xsl:number format="a"/>
        </xsl:when>
        <xsl:otherwise>
          <xsl:number format="1"/>
        </xsl:otherwise>
      </xsl:choose>
      <xsl:text>. </xsl:text>
    </fo:list-item-label>
    <fo:list-item-body>
      <xsl:apply-templates/>
    </fo:list-item-body>
  </fo:list-item>
</xsl:template>

8.3 Try/Catch

The xsl:try instruction can be used to trap dynamic errors occurring within the expression it wraps; the recovery action if such errors occur is defined using a child xsl:catch element.

<!-- Category: instruction -->
<xsl:try
  select? = expression >
  <!-- Content: (sequence-constructor, xsl:catch, (xsl:catch | xsl:fallback)*) -->
</xsl:try>

Note:

Because a sequence constructor may contain an xsl:fallback element, the effect of this content model is that an xsl:fallback instruction may appear as a child of xsl:try in any position.

<xsl:catch
  errors? = tokens
  select? = expression >
  <!-- Content: sequence-constructor -->
</xsl:catch>

An xsl:try instruction evaluates either the expression contained in its select attribute, or its contained sequence constructor, and returns the result of that evaluation if it succeeds without error. If a dynamic error occurs during the evaluation, the processor evaluates the first xsl:catch child element applicable to the error, and returns that result instead.

If the xsl:try element has a select attribute, then it must have no children other than xsl:catch and xsl:fallback. That is, the select attribute and the contained sequence constructor are mutually exclusive. If neither is present, the result of the xsl:try is an empty sequence (no dynamic error can occur in this case).

[ERR XTSE3140] It is a static error if the select attribute of the xsl:try element is present and the element has children other than xsl:catch and xsl:fallback elements.

Any xsl:fallback children of the xsl:try element are ignored by an XSLT 3.0 processor, but can be used to define the recovery action taken by an XSLT 1.0 or XSLT 2.0 processor operating with forwards compatible behavior.

The xsl:catch element has an optional errors attribute, which lists the error conditions that the xsl:catch element is designed to intercept. The default value is errors="*", which catches all errors. The value is a whitespace-separated list of NameTestsXP30; an xsl:catch element catches an error condition if this list includes a NameTest that matches the error code associated with that error condition.

Note:

Error codes are QNames. Those defined in this specification and in related specifications are all in the standard error namespace, and may therefore be caught using an xsl:catch element such as <xsl:catch errors="err:FODC0001 err:FODC0005"> where the namespace prefix err is bound to this namespace. Errors defined by implementors, and errors raised by an explicit call of the errorFO30 function or by use of the xsl:message or xsl:assert instruction, may use error codes in other namespaces.

If more than one xsl:catch element matches an error, the error is processed using the first one that matches, in document order. If no xsl:catch matches the error, then the error is not caught (that is, evaluation of the xsl:try element fails with the dynamic error).

An xsl:catch element may have either a select attribute, or a contained sequence constructor.

[ERR XTSE3150] It is a static error if the select attribute of the xsl:catch element is present unless the element has empty content.

The result of evaluating the xsl:catch element is the result of evaluating the XPath expression in its select attribute or the result of evaluating the contained sequence constructor; if neither is present, the result is an empty sequence. This result is delivered as the result of the xsl:try instruction.

If a dynamic error occurs during the evaluation of xsl:catch, it causes the containing xsl:try to fail with this error. The error is not caught by other sibling xsl:catch elements within the same xsl:try instruction, but it may be caught by an xsl:try instruction at an outer level, or by an xsl:try instruction nested within the xsl:catch.

Within the select expression, or within the sequence constructor contained by the xsl:catch element, a number of variables are implicitly declared, giving information about the error that occurred. These are lexically scoped to the xsl:catch element. These variables are all in the standard error namespace, and they are initialized as described in the following table:

Variable Type Value
err:code xs:QName The error code
err:description xs:string? A description of the error condition; an empty sequence if no description is available (for example, if the errorFO30 function was called with one argument).
err:value item()* Value associated with the error. For an error raised by calling the errorFO30 function, this is the value of the third argument (if supplied). For an error raised by evaluating xsl:message with terminate="yes", or a failing xsl:assert, this is the document node at the root of the tree containing the XML message body.
err:module xs:string? The URI (or system ID) of the stylesheet module containing the instruction where the error occurred; an empty sequence if the information is not available.
err:line-number xs:integer? The line number within the stylesheet module of the instruction where the error occurred; an empty sequence if the information is not available. The value may be approximate.
err:column-number xs:integer? The column number within the stylesheet module of the instruction where the error occurred; an empty sequence if the information is not available. The value may be approximate.

Variables declared within the sequence constructor of the xsl:try element (and not within an xsl:catch) are not visible within the xsl:catch element.

Note:

Within an xsl:catch it is possible to re-throw the error using the function call error($err:code, $err:description, $err:value).

The following additional rules apply to the catching of errors:

  1. All dynamic errors occurring during the evaluation of the xsl:try sequence constructor or select expression are caught (provided they match one of the xsl:catch elements).

    • This includes errors occurring in functions or templates invoked in the course of this evaluation, unless already caught by a nested xsl:try.

    • It also includes errors caused by calling the errorFO30 function or the xsl:message instruction with terminate="yes" or the xsl:assert instruction.

    • It does not include errors that occur while evaluating references to variables whose declaration and initialization is outside the xsl:try.

  2. The existence of an xsl:try instruction does not affect the right of the processor to recover, or not recover, from errors classified as recoverable dynamic errors. An xsl:catch element will be activated only if the processor chooses to signal the error rather than taking the defined recovery action.

  3. The existence of an xsl:try instruction does not affect the obligation of the processor to signal certain errors as static errors, or its right to choose whether to signal some errors (such as type errors) statically or dynamically. Static errors are never caught.

  4. Some fatal errors arising in the processing environment, such as running out of memory, may cause termination of the transformation despite the presence of an xsl:try instruction. This is implementation-dependent.

  5. If the sequence constructor or select expression of the xsl:try causes execution of xsl:result-document, xsl:message, or xsl:assert instructions and fails with a dynamic error that is caught, it is implementation-dependent whether these instructions have any externally visible effect. The processor is not required to do a "rollback" of any changes made by these instructions. The same applies to any side effects caused by extension functions or extension instructions.

  6. If the xsl:try element appears in a context where it is required to deliver a value of a specified type (for example, if it appears as the body of a stylesheet function), then any error that occurs because it delivers a value of the wrong type, or an error that occurs during conversion to the required type (for example, during atomization), is treated as occurring within the scope of the xsl:try instruction.

  7. When an instruction J computes a value that will inevitably cause some outer-level instruction O to fail with a dynamic error, then the failure may be treated as occurring in J, in which case it will be caught by an xsl:try instruction whose scope includes J but does not include O. For example, creating an element may fail because the element is not allowed by the content model of a containing element; although the specification describes this as a failure associated with the construction of the containing element, a processor is allowed to detect the error as soon as it becomes inevitable.

    Note:

    The effect of this rule is that when stylesheet output is streamed to a schema validator or to a serializer, errors detected by the validation or serialization process may be treated if they occurred in the instruction that generated the offending output; however, stylesheet authors cannot rely on this. In fact, where serialization is applied to a final result tree, there is no guarantee that it will be possible to catch the error at all, since serialization is outside the scope of the transformation process proper.

  8. The fact that the application tries to catch errors does not prevent the processor from organizing the evaluation in such a way as to prevent errors occurring. For example exists(//a[10 div . gt 5]) may still do an "early exit", rather than examining every item in the sequence just to see if it triggers a divide-by-zero error.

  9. A failure occurring while evaluating the match pattern of a template rule, if not treated as a recoverable error, is treated as occurring during the evaluation of the calling xsl:apply-templates instruction (or xsl:apply-imports or xsl:next-match if appropriate).

  10. Except as specified above, the optimizer must not rearrange the evaluation (at compile time or at run time) so that expressions written to be subject to the try/catch are evaluated outside its scope, or expressions written to be external to the try/catch are evaluated within its scope. This does not prevent expressions being rearranged, but any expression that is so rearranged must carry its try/catch context with it.

Note:

If an error occurs while evaluating an instruction within xsl:try, then no instruction within the xsl:try has any effect on the result returned by the xsl:try instruction. This means that if a processor is streaming the output to a serializer, it needs to adopt a strategy such as buffering the output in memory so that nothing is written until successful completion of the xsl:try instruction, or checkpointing the output so it can be rolled back when an error occurs.

Issue 7 (try-catch-output-buffering):

The rules appear inconsistent: if the processor is obliged to buffer "immediate" output from the xsl:try element before sending it the serializer, should not the same requirement apply also to xsl:result-document (rule 5)? And if output has to be buffered, is rule 7 appropriate, allowing serialization errors to be detected "on the fly"?

8.3.1 Try/Catch Examples

Example: Catching a divide-by-zero error

The following example divides an employee's salary by the number of years they have served, catching the divide-by-zero error if the latter is zero.

<xsl:try select="salary div length-of-service">
  <xsl:catch errors="err:FAOR0001" select="()"/>
</xsl:try>

 

Example: Catching an error during result-tree validation

The following example generates a result tree and performs schema validation, outputting a warning message and serializing the invalid tree if validation fails.

<xsl:result-document href="out.xml">
  <xsl:variable name="result">
    <xsl:call-template name="construct-output"/>
  </xsl:variable>
  <xsl:try>
    <xsl:copy-of select="$result" validation="strict"/>
    <xsl:catch>
      <xsl:message>Warning: validation of result document failed:
          Error code: <xsl:value-of select="$err:code"/>
          Reason: <xsl:value-of select="$err:description"/>
      </xsl:message>
      <xsl:sequence select="$result"/>
    </xsl:catch>
  </xsl:try>
</xsl:result-document>

The reason that the result tree is constructed in a variable in this example is so that the unvalidated tree is available to be used within the xsl:catch element. An alternative approach would be to repeat the logic for constructing the tree:

<xsl:try>
  <xsl:result-document href="out.xml" validation="strict">  
    <xsl:call-template name="construct-output"/>
  </xsl:result-document>
  <xsl:catch>
    <xsl:message>Warning: validation of result document failed:
          Error code: <xsl:value-of select="$err:code"/>
          Reason: <xsl:value-of select="$err:description"/>
    </xsl:message>
    <xsl:call-template name="construct-output"/>
  </xsl:catch>
  </xsl:try>

9 Variables and Parameters

[Definition: The two elements xsl:variable and xsl:param are referred to as variable-binding elements ].

[Definition: The xsl:variable element declares a variable, which may be a global variable or a local variable.]

[Definition: The xsl:param element declares a parameter, which may be a stylesheet parameter, a template parameter, a function parameter, or an xsl:iterate parameter. A parameter is a variable with the additional property that its value can be set by the caller.]

[Definition: A variable is a binding between a name and a value. The value of a variable is any sequence (of nodes, atomic values, and/or function items), as defined in [Data Model].]

9.1 Variables

<!-- Category: declaration -->
<!-- Category: instruction -->
<xsl:variable
  name = eqname
  select? = expression
  as? = sequence-type
  visibility? = "public" | "private" | "final" | "abstract" >
  <!-- Content: sequence-constructor -->
</xsl:variable>

The xsl:variable element has a required name attribute, which specifies the name of the variable. The value of the name attribute is an EQName, which is expanded as described in 5.1 Qualified Names.

The xsl:variable element has an optional as attribute, which specifies the required type of the variable. The value of the as attribute is a SequenceTypeXP30, as defined in [XPath 3.0].

[Definition: The value of the variable is computed using the expression given in the select attribute or the contained sequence constructor, as described in 9.3 Values of Variables and Parameters. This value is referred to as the supplied value of the variable.] If the xsl:variable element has a select attribute, then the sequence constructor must be empty.

If the as attribute is specified, then the supplied value of the variable is converted to the required type, using the function conversion rules.

[ERR XTTE0570] It is a type error if the supplied value of a variable cannot be converted to the required type.

If the as attribute is omitted, the supplied value of the variable is used directly, and no conversion takes place.

The visibility attribute must not be specified for a local variable: that is, it is allowed only when the parent element is xsl:stylesheet, xsl:transform, or xsl:override.

If the visibility attribute is present with the value abstract then the select attribute must be absent and the contained sequence constructor must be empty. In this situation there is no supplied value, and therefore the constraint that the supplied value is consistent with the required type does not apply.

9.2 Parameters

<!-- Category: declaration -->
<xsl:param
  name = eqname
  select? = expression
  as? = sequence-type
  required? = "yes" | "no"
  tunnel? = "yes" | "no"
  visibility? = "public" | "private" | "final" | "abstract" >
  <!-- Content: sequence-constructor -->
</xsl:param>

The xsl:param element may be used:

The xsl:param element has a required name attribute, which specifies the name of the parameter. The value of the name attribute is an EQName, which is expanded as described in 5.1 Qualified Names.

[ERR XTSE0580] It is a static error if the values of the name attribute of two sibling xsl:param elements represent the same expanded QName.

Note:

For rules concerning stylesheet parameters, see 9.5 Global Variables and Parameters. Local variables may shadow template parameters and function parameters: see 9.7 Scope of Variables.

The supplied value of the parameter is the value supplied by the caller. If no value was supplied by the caller, and if the parameter is not mandatory, then the supplied value is computed using the expression given in the select attribute or the contained sequence constructor, as described in 9.3 Values of Variables and Parameters. If the xsl:param element has a select attribute, then the sequence constructor must be empty.

Note:

This specification does not dictate whether and when the default value of a parameter is evaluated. For example, if the default is specified as <xsl:param name="p"><foo/></xsl:param>, then it is not specified whether a distinct foo element node will be created on each invocation of the template, or whether the same foo element node will be used for each invocation. However, it is permissible for the default value to depend on the values of other parameters, or on the evaluation context, in which case the default must effectively be evaluated on each invocation.

The xsl:param element has an optional as attribute, which specifies the required type of the parameter. The value of the as attribute is a SequenceTypeXP30, as defined in [XPath 3.0].

If the as attribute is specified, then the supplied value of the parameter is converted to the required type, using the function conversion rules.

[ERR XTTE0590] It is a type error if the conversion of the supplied value of a parameter to its required type fails.

If the as attribute is omitted, the supplied value of the parameter is used directly, and no conversion takes place.

The optional required attribute may be used to indicate that a parameter is mandatory. This attribute may be specified for stylesheet parameters and for template parameters; it must not be specified for function parameters, which are always mandatory, or for parameters to xsl:iterate, which are always initialized to a default value. A parameter is mandatory if it is a function parameter or if the required attribute is present and has the value yes. Otherwise, the parameter is optional. If the parameter is mandatory, then the xsl:param element must be empty and must not have a select attribute.

[ERR XTTE0600] If a default value is given explicitly, that is, if there is either a select attribute or a non-empty sequence constructor, then it is a type error if the default value cannot be converted to the required type, using the function conversion rules.

If an optional parameter has no select attribute and has an empty sequence constructor, and if there is no as attribute, then the default value of the parameter is a zero length string.

[ERR XTDE0610] If an optional parameter has no select attribute and has an empty sequence constructor, and if there is an as attribute, then the default value of the parameter is an empty sequence. If the empty sequence is not a valid instance of the required type defined in the as attribute, then the parameter is treated as a required parameter, which means that it is a non-recoverable dynamic error if the caller supplies no value for the parameter.

The visibility attribute must not be specified for a local parameter: that is, it is allowed only when the parent element is xsl:stylesheet, xsl:transform, or xsl:override.

If the visibility attribute is present with the value abstract then the select attribute must be absent and the contained sequence constructor must be empty. In this situation there is no supplied value, and therefore the constraint that the supplied value is consistent with the required type does not apply.

Note:

The effect of these rules is that specifying <xsl:param name="p" as="xs:date" select="2"/> is an error, but if the default value of the parameter is never used, then the processor has discretion whether or not to report the error. By contrast, <xsl:param name="p" as="xs:date"/> is treated as if required="yes" had been specified: the empty sequence is not a valid instance of xs:date, so in effect there is no default value and the parameter is therefore treated as being mandatory.

The optional tunnel attribute may be used to indicate that a parameter is a tunnel parameter. The default is no; the value yes may be specified only for template parameters. Tunnel parameters are described in 10.1.2 Tunnel Parameters

9.3 Values of Variables and Parameters

A variable-binding element may specify the supplied value of a variable or the default value of a parameter in four different ways.

  • If the variable-binding element has a select attribute, then the value of the attribute must be an expression and the supplied value of the variable is the value that results from evaluating the expression. In this case, the content of the variable-binding element must be empty.

  • If the variable-binding element has empty content and has neither a select attribute nor an as attribute, then the supplied value of the variable is a zero-length string. Thus

    <xsl:variable name="x"/>
    

    is equivalent to

    <xsl:variable name="x" select="''"/>
    
  • If a variable-binding element has no select attribute and has non-empty content (that is, the variable-binding element has one or more child nodes), and has no as attribute, then the content of the variable-binding element specifies the supplied value. The content of the variable-binding element is a sequence constructor; a new document is constructed with a document node having as its children the sequence of nodes that results from evaluating the sequence constructor and then applying the rules given in 5.7.1 Constructing Complex Content. The value of the variable is then a singleton sequence containing this document node. For further information, see 9.4 Creating implicit document nodes.

  • If a variable-binding element has an as attribute but no select attribute, then the supplied value is the sequence that results from evaluating the (possibly empty) sequence constructor contained within the variable-binding element (see 5.7 Sequence Constructors).

These combinations are summarized in the table below.

select attribute as attribute content Effect
present absent empty Value is obtained by evaluating the select attribute
present present empty Value is obtained by evaluating the select attribute, adjusted to the type required by the as attribute
present absent present Static error
present present present Static error
absent absent empty Value is a zero-length string
absent present empty Value is an empty sequence, provided the as attribute permits an empty sequence
absent absent present Value is a document node whose content is obtained by evaluating the sequence constructor
absent present present Value is obtained by evaluating the sequence constructor, adjusted to the type required by the as attribute

[ERR XTSE0620] It is a static error if a variable-binding element has a select attribute and has non-empty content.

Example: Values of Variables

The value of the following variable is the sequence of integers (1, 2, 3):

<xsl:variable name="i" as="xs:integer*" select="1 to 3"/>

The value of the following variable is an integer, assuming that the attribute @size exists, and is annotated either as an integer, or as xs:untypedAtomic:

<xsl:variable name="i" as="xs:integer" select="@size"/>

The value of the following variable is a zero-length string:

<xsl:variable name="z"/>

The value of the following variable is a document node containing an empty element as a child:

<xsl:variable name="doc"><c/></xsl:variable>

The value of the following variable is a sequence of integers (2, 4, 6):

<xsl:variable name="seq" as="xs:integer*">
  <xsl:for-each select="1 to 3">
    <xsl:sequence select=".*2"/>
  </xsl:for-each>
</xsl:variable>

The value of the following variable is a sequence of parentless attribute nodes:

<xsl:variable name="attset" as="attribute()+">
  <xsl:attribute name="x">2</xsl:attribute>
  <xsl:attribute name="y">3</xsl:attribute>
  <xsl:attribute name="z">4</xsl:attribute>    
</xsl:variable>

The value of the following variable is an empty sequence:

<xsl:variable name="empty" as="empty-sequence()"/>

The actual value of the variable depends on the supplied value, as described above, and the required type, which is determined by the value of the as attribute.

Example: Pitfalls with Numeric Predicates

When a variable is used to select nodes by position, be careful not to do:

<xsl:variable name="n">2</xsl:variable>
...
<xsl:value-of select="td[$n]"/>

This will output the values of all the td elements, space-separated (or with XSLT 1.0 behavior, the value of the first td element), because the variable n will be bound to a node, not a number. Instead, do one of the following:

<xsl:variable name="n" select="2"/>
...
<xsl:value-of select="td[$n]"/>

or

<xsl:variable name="n">2</xsl:variable>
...
<xsl:value-of select="td[position()=$n]"/>

or

<xsl:variable name="n" as="xs:integer">2</xsl:variable>
...
<xsl:value-of select="td[$n]"/>

9.4 Creating implicit document nodes

A document node is created implicitly when evaluating an xsl:variable, xsl:param, or xsl:with-param element that has non-empty content and that has no as attribute. The value of the variable is a single node, the document node of a temporary tree. The content of the document node is formed from the result of evaluating the sequence constructor contained within the variable-binding element, as described in 5.7.1 Constructing Complex Content.

Note:

The construct:

<xsl:variable name="tree">
  <a/>
</xsl:variable>

can be regarded as a shorthand for:

<xsl:variable name="tree" as="document-node()">
  <xsl:document validation="preserve">
    <a/>
  </xsl:document>  
</xsl:variable>

The base URI of the document node is taken from the base URI of the variable binding element in the stylesheet. (See Section 5.2 base-uri Accessor DM30 in [Data Model])

No document-level validation takes place (which means, for example, that there is no checking that ID values are unique). However, type annotations on nodes within the new tree are copied unchanged.

Note:

The base URI of other nodes in the tree is determined by the rules for constructing complex content. The effect of these rules is that the base URI of a node in the temporary tree is determined as if all the nodes in the temporary tree came from a single entity whose URI was the base URI of the variable-binding element. Thus, the base URI of the document node will be equal to the base URI of the variable-binding element, while an xml:base attribute within the temporary tree will change the base URI for its parent element and that element's descendants, just as it would within a document constructed by parsing.

The document-uri and unparsed-entities properties of the new document node are set to empty.

A temporary tree is available for processing in exactly the same way as any source document. For example, its nodes are accessible using path expressions, and they can be processed using instructions such as xsl:apply-templates and xsl:for-each. Also, the key and idFO30 functions can be used to find nodes within a temporary tree, by supplying the document node at the root of the tree as an argument to the function or by making it the context node.

Example: Two-Phase Transformation

For example, the following stylesheet uses a temporary tree as the intermediate result of a two-phase transformation, using different modes for the two phases (see 6.6 Modes). Typically, the template rules in module phase1.xsl will be declared with mode="phase1", while those in module phase2.xsl will be declared with mode="phase2":

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

<xsl:import href="phase1.xsl"/>
<xsl:import href="phase2.xsl"/>

<xsl:variable name="intermediate">
  <xsl:apply-templates select="/" mode="phase1"/>
</xsl:variable>

<xsl:template match="/">
  <xsl:apply-templates select="$intermediate" mode="phase2"/>
</xsl:template>

</xsl:stylesheet>

Note:

The algorithm for matching nodes against template rules is exactly the same regardless which tree the nodes come from. If different template rules are to be used when processing different trees, then unless nodes from different trees can be distinguished by means of patterns, it is a good idea to use modes to ensure that each tree is processed using the appropriate set of template rules.

9.5 Global Variables and Parameters

Both xsl:variable and xsl:param are allowed as declaration elements: that is, they may appear as children of the xsl:stylesheet element.

[Definition: A top-level variable-binding element declares a global variable that is visible everywhere (except where it is shadowed by another binding).]

[Definition: A top-level xsl:param element declares a stylesheet parameter. A stylesheet parameter is a global variable with the additional property that its value can be supplied by the caller when a transformation is initiated.] As described in 9.2 Parameters, a stylesheet parameter may be declared as being mandatory, or may have a default value specified for use when no value is supplied by the caller. The mechanism by which the caller supplies a value for a stylesheet parameter is implementation-defined. An XSLT processor must provide such a mechanism.

It is an error if no value is supplied for a mandatory stylesheet parameter [see ERR XTDE0050].

If a stylesheet contains more than one binding for a global variable of a particular name, then the binding with the highest import precedence is used.

[ERR XTSE0630] It is a static error if a stylesheet contains more than one binding of a global variable with the same name and same import precedence, unless it also contains another binding with the same name and higher import precedence.

For a global variable or the default value of a stylesheet parameter, the expression or sequence constructor specifying the variable value is evaluated with a singleton focus based on the root node of the tree containing the initial context item. An XPath error will be reported if the evaluation of a global variable or parameter references the context item, context position, or context size when no initial context item is supplied. The values of other components of the dynamic context are the initial values as defined in 5.4.3 Initializing the Dynamic Context and 5.4.4 Additional Dynamic Context Components used by XSLT.

Example: A Stylesheet Parameter

The following example declares a global parameter para-font-size, which is referenced in an attribute value template.

<xsl:param name="para-font-size" as="xs:string">12pt</xsl:param>

<xsl:template match="para">
 <fo:block font-size="{$para-font-size}">
   <xsl:apply-templates/>
 </fo:block>
</xsl:template>

The implementation must provide a mechanism allowing the user to supply a value for the parameter para-font-size when invoking the stylesheet; the value 12pt acts as a default.

9.6 Local Variables and Parameters

[Definition: As well as being allowed as a declaration, the xsl:variable element is also allowed in sequence constructors. Such a variable is known as a local variable.]

An xsl:param element may also be used to create a variable binding with local scope:

The result of evaluating a local xsl:variable or xsl:param element (that is, the contribution it makes to the result of the sequence constructor it is part of) is an empty sequence.

9.7 Scope of Variables

For any variable-binding element, there is a region (more specifically, a set of element nodes) of the stylesheet within which the binding is visible. The set of variable bindings in scope for an XPath expression consists of those bindings that are visible at the point in the stylesheet where the expression occurs.

A global variable binding element is visible everywhere in the stylesheet (including other stylesheet modules) except within the xsl:variable or xsl:param element itself and any region where it is shadowed by another variable binding.

A local variable binding element is visible for all following siblings and their descendants, with the following exceptions:

  1. It is not visible in any region where it is shadowed by another variable binding.

  2. It is not visible within the subtree rooted at an xsl:fallback instruction that is a sibling of the variable binding element.

  3. It is not visible within the subtree rooted at an xsl:catch instruction that is a sibling of the variable binding element.

The binding is not visible for the xsl:variable or xsl:param element itself.

[Definition: A binding shadows another binding if the binding occurs at a point where the other binding is visible, and the bindings have the same name. ] It is not an error if a binding established by a local xsl:variable or xsl:param shadows a global binding. In this case, the global binding will not be visible in the region of the stylesheet where it is shadowed by the other binding.

Example: Local Variable Shadowing a Global Variable

The following is allowed:

<xsl:param name="x" select="1"/>
<xsl:template name="foo">
  <xsl:variable name="x" select="2"/>
</xsl:template>

It is also not an error if a binding established by a local xsl:variable element shadows a binding established by another local xsl:variable or xsl:param.

Example: Misuse of Variable Shadowing

The following is not an error, but the effect is probably not what was intended. The template outputs <x value="1"/>, because the declaration of the inner variable named $x has no effect on the value of the outer variable named $x.

<xsl:variable name="x" select="1"/>
<xsl:template name="foo">
  <xsl:for-each select="1 to 5">
    <xsl:variable name="x" select="$x+1"/>
  </xsl:for-each>
  <x value="{$x}"/>
</xsl:template>

Note:

Once a variable has been given a value, the value cannot subsequently be changed. XSLT does not provide an equivalent to the assignment operator available in many procedural programming languages.

This is because an assignment operator would make it harder to create an implementation that processes a document other than in a batch-like way, starting at the beginning and continuing through to the end.

As well as global variables and local variables, an XPath expression may also declare range variables for use locally within an expression. For details, see [XPath 3.0].

Where a reference to a variable occurs in an XPath expression, it is resolved first by reference to range variables that are in scope, then by reference to local variables and parameters, and finally by reference to global variables and parameters. A range variable may shadow a local variable or a global variable. XPath also allows a range variable to shadow another range variable.

9.8 Setting Parameter Values

<xsl:with-param
  name = eqname
  select? = expression
  as? = sequence-type
  tunnel? = "yes" | "no" >
  <!-- Content: sequence-constructor -->
</xsl:with-param>

Parameters are passed to templates using the xsl:with-param element. The required name attribute specifies the name of the template parameter (the variable the value of whose binding is to be replaced). The value of the name attribute is an EQName, which is expanded as described in 5.1 Qualified Names.

The xsl:with-param element is also used when passing parameters to an iteration of the xsl:iterate instruction, or to a dynamic invocation of an XPath expression using xsl:evaluate. In consequence, xsl:with-param may appear within xsl:apply-templates, xsl:apply-imports, xsl:call-template, xsl:evaluate, xsl:next-iteration, and xsl:next-match. (Arguments to stylesheet functions, however, are supplied as part of an XPath function call: see 10.3 Stylesheet Functions.)

[ERR XTSE0670] It is a static error if two or more sibling xsl:with-param elements have name attributes that represent the same expanded QName.

The value of the parameter is specified in the same way as for xsl:variable and xsl:param (see 9.3 Values of Variables and Parameters), taking account of the values of the select and as attributes and the content of the xsl:with-param element, if any.

Note:

It is possible to have an as attribute on the xsl:with-param element that differs from the as attribute on the corresponding xsl:param element.

In this situation, the supplied value of the parameter will first be processed according to the rules of the as attribute on the xsl:with-param element, and the resulting value will then be further processed according to the rules of the as attribute on the xsl:param element.

For example, suppose the supplied value is a node with type annotation xs:untypedAtomic, and the xsl:with-param element specifies as="xs:integer", while the xsl:param element specifies as="xs:double". Then the node will first be atomized and the resulting untyped atomic value will be cast to xs:integer. If this succeeds, the xs:integer will then be promoted to an xs:double.

The focus used for computing the value specified by the xsl:with-param element is the same as that used for its parent instruction.

The optional tunnel attribute may be used to indicate that a parameter is a tunnel parameter. The default is no. Tunnel parameters are described in 10.1.2 Tunnel Parameters. They are used only when passing parameters to templates: for an xsl:with-param element that is a child of xsl:evaluate or xsl:next-iteration the tunnel attribute must either be omitted or take the value no.

In other cases it is a non-recoverable dynamic error if the template that is invoked declares a template parameter with required="yes" and no value for this parameter is supplied by the calling instruction. [see ERR XTDE0700]

9.9 Circular Definitions

[Definition: A circularity is said to exist if a construct such as a global variable, an attribute set, or a key, is defined in terms of itself. For example, if the expression or sequence constructor specifying the value of a global variable X references a global variable Y, then the value for Y must be computed before the value of X. A circularity exists if it is impossible to do this for all global variable definitions.]

Example: Circular Variable Definitions

The following two declarations create a circularity:

<xsl:variable name="x" select="$y+1"/>
<xsl:variable name="y" select="$x+1"/>

 

Example: Circularity involving Variables and Functions

The definition of a global variable can be circular even if no other variable is involved. For example the following two declarations (see 10.3 Stylesheet Functions for an explanation of the xsl:function element) also create a circularity:

<xsl:variable name="x" select="my:f()"/>

<xsl:function name="my:f">
  <xsl:sequence select="$x"/>
</xsl:function>

 

Example: Circularity involving Variables and Templates

The definition of a variable is also circular if the evaluation of the variable invokes an xsl:apply-templates instruction and the variable is referenced in the pattern used in the match attribute of any template rule in the stylesheet. For example the following definition is circular:

<xsl:variable name="x">
  <xsl:apply-templates select="//param[1]"/>
</xsl:variable>

<xsl:template match="param[$x]">1</xsl:template>

 

Example: Circularity involving Variables and Keys

Similarly, a variable definition is circular if it causes a call on the key function, and the definition of that key refers to that variable in its match or use attributes. So the following definition is circular:

<xsl:variable name="x" select="my:f(10)"/>

<xsl:function name="my:f">
  <xsl:param name="arg1"/>
  <xsl:sequence select="key('k', $arg1)"/>
</xsl:function>

<xsl:key name="k" match="item[@code=$x]" use="@desc"/>

[ERR XTDE0640] In general, a circularity in a stylesheet is a non-recoverable dynamic error. However, as with all other dynamic errors, an implementation will signal the error only if it actually executes the instructions and expressions that participate in the circularity. Because different implementations may optimize the execution of a stylesheet in different ways, it is implementation-dependent whether a particular circularity will actually be signaled.

For example, in the following declarations, the function declares a local variable $b, but it returns a result that does not require the variable to be evaluated. It is implementation-dependent whether the value is actually evaluated, and it is therefore implementation-dependent whether the circularity is signaled as an error:

<xsl:variable name="x" select="my:f(1)"/>

<xsl:function name="my:f">
  <xsl:param name="a"/>
  <xsl:variable name="b" select="$x"/>  
  <xsl:sequence select="$a + 2"/>
</xsl:function>

Circularities usually involve global variables or parameters, but they can also exist between key definitions (see 20.2 Keys), between named attribute sets (see 10.2 Named Attribute Sets), or between any combination of these constructs. For example, a circularity exists if a key definition invokes a function that references an attribute set that calls the key function, supplying the name of the original key definition as an argument.

Circularity is not the same as recursion. Stylesheet functions (see 10.3 Stylesheet Functions) and named templates (see 10.1 Named Templates) may call other functions and named templates without restriction. With careless coding, recursion may be non-terminating. Implementations are required to signal circularity as a dynamic error, but they are not required to detect non-terminating recursion.

10 Callable Components

This section describes three constructs that can be used to provide subroutine-like functionality that can be invoked from anywhere in the stylesheet: named templates (see 10.1 Named Templates), named attribute sets (see 10.2 Named Attribute Sets), and stylesheet functions (see 10.3 Stylesheet Functions).

10.1 Named Templates

<!-- Category: instruction -->
<xsl:call-template
  name = eqname >
  <!-- Content: xsl:with-param* -->
</xsl:call-template>

[Definition: Templates can be invoked by name. An xsl:template element with a name attribute defines a named template.] The value of the name attribute is an EQName, which is expanded as described in 5.1 Qualified Names. If an xsl:template element has a name attribute, it may, but need not, also have a match attribute. An xsl:call-template instruction invokes a template by name; it has a required name attribute that identifies the template to be invoked. Unlike xsl:apply-templates, the xsl:call-template instruction does not change the focus.

The match, mode and priority attributes on an xsl:template element have no effect when the template is invoked by an xsl:call-template instruction. Similarly, the name and visibility attributes on an xsl:template element have no effect when the template is invoked by an xsl:apply-templates instruction.

[ERR XTSE0650] It is a static error if a stylesheet contains an xsl:call-template instruction whose name attribute does not match the name attribute of any named template visible in the containing package (this includes any template defined in this package, as well as templates accepted from used packages whose visibility in this package is not hidden). For more details of the process of binding the called template, see 3.6.2.6 Binding References to Components.

[ERR XTSE0660] It is a static error if a package contains more than one template with the same name and the same import precedence, unless it also contains a template with the same name and higher import precedence.

The target template for an xsl:call-template instruction is established using the binding rules described in 3.6.2.6 Binding References to Components. This will always be a template whose name attribute matches the name attribute of the xsl:call-template instruction. It may be a template defined in the same package that has higher import precedence than any other template with this name, or it may be a template accepted from a used package, or (if the template is not defined as private or final) it may be an overriding template in a package that uses the containing package. The result of evaluating an xsl:call-template instruction is the sequence produced by evaluating the sequence constructor contained in its target template (see 5.7 Sequence Constructors).

10.1.1 Passing Parameters to Named Templates

Parameters are passed to named templates using the xsl:with-param element as a child of the xsl:call-template instruction.

[ERR XTSE0680] In the case of xsl:call-template, it is a static error to pass a non-tunnel parameter named x to a template that does not have a non-tunnel template parameter named x, unless the xsl:call-template instruction is processed with XSLT 1.0 behavior. This is not an error in the case of xsl:apply-templates, xsl:apply-imports, and xsl:next-match; in these cases the parameter is simply ignored.

The optional tunnel attribute may be used to indicate that a parameter is a tunnel parameter. The default is no. Tunnel parameters are described in 10.1.2 Tunnel Parameters

[ERR XTSE0690] It is a static error if a template that is invoked using xsl:call-template declares a template parameter specifying required="yes" and not specifying tunnel="yes", if no value for this parameter is supplied by the calling xsl:call-template instruction.

Example: Calling a Named Template with a Parameter

This example defines a named template for a numbered-block with a parameter to control the format of the number.

<xsl:template name="numbered-block">
  <xsl:param name="format">1. </xsl:param>
  <fo:block>
    <xsl:number format="{$format}"/>
    <xsl:apply-templates/>
  </fo:block>
</xsl:template>

<xsl:template match="ol//ol/li">
  <xsl:call-template name="numbered-block">
    <xsl:with-param name="format">a. </xsl:with-param>
  </xsl:call-template>
</xsl:template>

10.1.2 Tunnel Parameters

[Definition: A parameter passed to a template may be defined as a tunnel parameter. Tunnel parameters have the property that they are automatically passed on by the called template to any further templates that it calls, and so on recursively.] Tunnel parameters thus allow values to be set that are accessible during an entire phase of stylesheet processing, without the need for each template that is used during that phase to be aware of the parameter.

Note:

Tunnel parameters are conceptually similar to dynamically scoped variables in some functional programming languages.

A tunnel parameter is created by using an xsl:with-param element that specifies tunnel="yes". A template that requires access to the value of a tunnel parameter must declare it using an xsl:param element that also specifies tunnel="yes".

On any template call using an xsl:apply-templates, xsl:call-template, xsl:apply-imports or xsl:next-match instruction, a set of tunnel parameters is passed from the calling template to the called template. This set consists of any parameters explicitly created using <xsl:with-param tunnel="yes">, overlaid on a base set of tunnel parameters. If the xsl:apply-templates, xsl:call-template, xsl:apply-imports or xsl:next-match instruction has an xsl:template declaration as an ancestor element in the stylesheet, then the base set consists of the tunnel parameters that were passed to that template; otherwise (for example, if the instruction is within a global variable declaration, an attribute set declaration, or a stylesheet function), the base set is empty. If a parameter created using <xsl:with-param tunnel="yes"> has the same expanded QName as a parameter in the base set, then the parameter created using xsl:with-param overrides the parameter in the base set; otherwise, the parameter created using xsl:with-param is added to the base set.

When a template accesses the value of a tunnel parameter by declaring it with xsl:param tunnel="yes", this does not remove the parameter from the base set of tunnel parameters that is passed on to any templates called by this template.

Two sibling xsl:with-param elements must have distinct parameter names, even if one is a tunnel parameter and the other is not. Equally, two sibling xsl:param elements representing template parameters must have distinct parameter names, even if one is a tunnel parameter and the other is not. However, the tunnel parameters that are implicitly passed in a template call may have names that duplicate the names of non-tunnel parameters that are explicitly passed on the same call.

Tunnel parameters are not passed in calls to stylesheet functions.

All other options of xsl:with-param and xsl:param are available with tunnel parameters just as with non-tunnel parameters. For example, parameters may be declared as mandatory or optional, a default value may be specified, and a required type may be specified. If any conversion is required from the supplied value of a tunnel parameter to the required type specified in xsl:param, then the converted value is used within the receiving template, but the value that is passed on in any further template calls is the original supplied value before conversion. Equally, any default value is local to the template: specifying a default value for a tunnel parameter does not change the set of tunnel parameters that is passed on in further template calls.

The set of tunnel parameters that is passed to the initial template is empty.

Tunnel parameters are passed unchanged through a built-in template rule (see 6.7 Built-in Template Rules).

If a tunnel parameter is declared in an xsl:param element with the attribute tunnel="yes", then a non-recoverable dynamic error occurs [see ERR XTDE0700] if the set of tunnel parameters passed to the template does not include a parameter with a matching expanded QName.

Example: Using Tunnel Parameters

Suppose that the equations in a scientific paper are to be sequentially numbered, but that the format of the number depends on the context in which the equations appear. It is possible to reflect this using a rule of the form:

<xsl:template match="equation">
  <xsl:param name="equation-format" select="'(1)'" tunnel="yes"/>
  <xsl:number level="any" format="{$equation-format}"/>
</xsl:template>

At any level of processing above this level, it is possible to determine how the equations will be numbered, for example:

<xsl:template match="appendix">
  ...
  <xsl:apply-templates>
    <xsl:with-param name="equation-format" select="'[i]'" tunnel="yes"/>
  </xsl:apply-templates>
  ...
</xsl:template>

The parameter value is passed transparently through all the intermediate layers of template rules until it reaches the rule with match="equation". The effect is similar to using a global variable, except that the parameter can take different values during different phases of the transformation.

10.2 Named Attribute Sets

<!-- Category: declaration -->
<xsl:attribute-set
  name = eqname
  use-attribute-sets? = eqnames
  visibility? = "public" | "private" | "final" | "abstract" >
  <!-- Content: xsl:attribute* -->
</xsl:attribute-set>

[Definition: The xsl:attribute-set element defines a named attribute set: that is, a collection of attribute definitions that can be used repeatedly on different constructed elements.]

The required name attribute specifies the name of the attribute set. The value of the name attribute is an EQName, which is expanded as described in 5.1 Qualified Names. The content of the xsl:attribute-set element consists of zero or more xsl:attribute instructions that are evaluated to produce the attributes in the set.

If the visibility attribute is present with the value abstract then there must be no xsl:attribute children.

The result of evaluating an attribute set is a sequence of attribute nodes. Evaluating the same attribute set more than once can produce different results, because although an attribute set does not have parameters, it may contain expressions or instructions whose value depends on the evaluation context.

Attribute sets are used by specifying a use-attribute-sets attribute on the xsl:element or xsl:copy instruction, or by specifying an xsl:use-attribute-sets attribute on a literal result element. An attribute set may be defined in terms of other attribute sets by using the use-attribute-sets attribute on the xsl:attribute-set element itself. The value of the [xsl:]use-attribute-sets attribute is in each case a whitespace-separated list of names of attribute sets. Each name is specified as an EQName, which is expanded as described in 5.1 Qualified Names.

Specifying a use-attribute-sets attribute is broadly equivalent to adding xsl:attribute instructions for each of the attributes in each of the named attribute sets to the beginning of the content of the instruction with the [xsl:]use-attribute-sets attribute, in the same order in which the names of the attribute sets are specified in the use-attribute-sets attribute.

More formally, an xsl:use-attribute-sets attribute is expanded using the following recursive algorithm, or any algorithm that produces the same results:

  • The value of the attribute is tokenized as a list of QNames.

  • Each QName in the list is processed, in order, as follows:

    • The QName must match the name attribute of one or more xsl:attribute-set declarations in the stylesheet.

    • Each xsl:attribute-set declaration whose name matches is processed as follows. Where two such declarations have different import precedence, the one with lower import precedence is processed first. Where two declarations have the same import precedence, they are processed in declaration order.

The xsl:attribute instructions are evaluated using the same focus as is used for evaluating the element that is the parent of the [xsl:]use-attribute-sets attribute forming the initial input to the algorithm. However, the static context for the evaluation depends on the position of the xsl:attribute instruction in the stylesheet: thus, only local variables declared within an xsl:attribute instruction, and global variables, are visible.

The set of attribute nodes produced by expanding xsl:use-attribute-sets may include several attributes with the same name. When the attributes are added to an element node, only the last of the duplicates will take effect.

The way in which each instruction uses the results of expanding the [xsl:]use-attribute-sets attribute is described in the specification for the relevant instruction: see 11.1 Literal Result Elements, 11.2 Creating Element Nodes Using xsl:element , and 11.9 Copying Nodes.

[ERR XTSE0710] It is a static error if the value of the use-attribute-sets attribute of an xsl:copy, xsl:element, or xsl:attribute-set element, or the xsl:use-attribute-sets attribute of a literal result element, is not a whitespace-separated sequence of EQNames, or if it contains a QName that does not match the name attribute of any xsl:attribute-set declaration in the stylesheet.

[ERR XTSE0720] It is a static error if an xsl:attribute-set element directly or indirectly references itself via the names contained in the use-attribute-sets attribute.

Each attribute node produced by expanding an attribute set has a type annotation determined by the rules for the xsl:attribute instruction that created the attribute node: see 11.3.1 Setting the Type Annotation for a Constructed Attribute Node. These type annotations may be preserved, stripped, or replaced as determined by the rules for the instruction that creates the element in which the attributes are used.

Attribute sets are used as follows:

  • The xsl:copy and xsl:element instructions have an use-attribute-sets attribute. The sequence of attribute nodes produced by evaluating this attribute is prepended to the sequence produced by evaluating the sequence constructor contained within the instruction.

  • Literal result elements allow an xsl:use-attribute-sets attribute, which is evaluated in the same way as the use-attribute-sets attribute of xsl:element and xsl:copy. The sequence of attribute nodes produced by evaluating this attribute is prepended to the sequence of attribute nodes produced by evaluating the attributes of the literal result element, which in turn is prepended to the sequence produced by evaluating the sequence constructor contained with the literal result element.

Example: Using Attribute Sets

The following example creates a named attribute set title-style and uses it in a template rule.

<xsl:template match="chapter/heading">
  <fo:block font-stretch="condensed" xsl:use-attribute-sets="title-style">
    <xsl:apply-templates/>
  </fo:block>
</xsl:template>

<xsl:attribute-set name="title-style">
  <xsl:attribute name="font-size">12pt</xsl:attribute>
  <xsl:attribute name="font-weight">bold</xsl:attribute>
</xsl:attribute-set>

 

Example: Overriding Attributes in an Attribute Set

The following example creates a named attribute set base-style and uses it in a template rule with multiple specifications of the attributes:

font-family

is specified only in the attribute set

font-size

is specified in the attribute set, is specified on the literal result element, and in an xsl:attribute instruction

font-style

is specified in the attribute set, and on the literal result element

font-weight

is specified in the attribute set, and in an xsl:attribute instruction

Stylesheet fragment:

<xsl:attribute-set name="base-style">
  <xsl:attribute name="font-family">Univers</xsl:attribute>
  <xsl:attribute name="font-size">10pt</xsl:attribute>
  <xsl:attribute name="font-style">normal</xsl:attribute>
  <xsl:attribute name="font-weight">normal</xsl:attribute>
</xsl:attribute-set>

<xsl:template match="o">
  <fo:block xsl:use-attribute-sets="base-style"
            font-size="12pt"
            font-style="italic">
    <xsl:attribute name="font-size">14pt</xsl:attribute>
    <xsl:attribute name="font-weight">bold</xsl:attribute>
    <xsl:apply-templates/>
  </fo:block>
</xsl:template>

Result:

<fo:block font-family="Univers"
          font-size="14pt"
          font-style="italic"
          font-weight="bold">
...
</fo:block>

10.3 Stylesheet Functions

[Definition: An xsl:function declaration declares the name, parameters, and implementation of a stylesheet function that can be called from any XPath expression within the stylesheet.]

<!-- Category: declaration -->
<xsl:function
  name = eqname
  as? = sequence-type
  visibility? = "public" | "private" | "final" | "abstract"
  override? = "yes" | "no" >
  <!-- Content: (xsl:param*, sequence-constructor) -->
</xsl:function>

The xsl:function declaration defines a stylesheet function that can be called from any XPath expression used in the stylesheet (including an XPath expression used within a predicate in a pattern). The name attribute specifies the name of the function. The value of the name attribute is an EQName, which is expanded as described in 5.1 Qualified Names.

An xsl:function declaration can only appear as a top-level element in a stylesheet module.

[ERR XTSE0740] It is a static error if a stylesheet function has a name that is in no namespace.

Note:

To prevent the namespace declaration used for the function name appearing in the result document, use the exclude-result-prefixes attribute on the xsl:stylesheet element: see 11.1.3 Namespace Nodes for Literal Result Elements.

The name of the function must not be in a reserved namespace: [see ERR XTSE0080]

The content of the xsl:function element consists of zero or more xsl:param elements that specify the formal arguments of the function, followed by a sequence constructor that defines the value to be returned by the function.

[Definition: The arity of a stylesheet function is the number of xsl:param elements in the function definition.] Optional arguments are not allowed.

[ERR XTSE0760] Because arguments to a stylesheet function call must all be specified, the xsl:param elements within an xsl:function element must not specify a default value: this means they must be empty, and must not have a select attribute.

If the visibility attribute is present with the value abstract then the sequence constructor defining the function body must be empty.

A stylesheet function is included in the in-scope functions of the static context for all XPath expressions used in the containing package, unless

Issue 8 (function-override):

The setting <xsl:function override="yes"> was introduced in XSLT 2.0 as a solution to use cases involving extension functions. As currently defined, it does not license overriding of a function that is present in a library package (just as it does not affect the rules for import precedence). This could prove to be confusing.

The visibility of the function in other packages depends on the value of the visibility attribute and other factors, as described in 3.6 Packages

The optional override attribute defines what happens if this function has the same name and arity as a function provided by the implementer or made available in the static context using an implementation-defined mechanism. If the override attribute has the value yes, then this function is used in preference; if it has the value no, then the other function is used in preference. The default value is yes.

Note:

Specifying override="yes" ensures interoperable behavior: the same code will execute with all processors. Specifying override="no" is useful when writing a fallback implementation of a function that is available with some processors but not others: it allows the vendor's implementation of the function (or a user's implementation written as an extension function) to be used in preference to the stylesheet implementation, which is useful when the extension function is more efficient.

The override attribute does not affect the rules for deciding which of several stylesheet functions with the same name and arity takes precedence.

[ERR XTSE0770] It is a static error for a stylesheet to contain two or more functions with the same expanded QName, the same arity, and the same import precedence, unless there is another function with the same expanded QName and arity, and a higher import precedence.

When the xsl:function declaration appears as a child of xsl:override, there must be a stylesheet function with the same expanded QName and arity in the package referenced by the containing xsl:use-package element; the visibility of that function must be public or abstract, and the overriding and overridden functions must have the same argument types and result type.

As defined in XPath, the function that is executed as the result of a function call is identified by looking in the in-scope functions of the static context for a function whose name and arity matches the name and number of arguments in the function call.

Note:

Functions are not polymorphic. Although the XPath function call mechanism allows two functions to have the same name and different arity, it does not allow them to be distinguished by the types of their arguments.

The optional as attribute indicates the required type of the result of the function. The value of the as attribute is a SequenceTypeXP30, as defined in [XPath 3.0].

[ERR XTTE0780] If the as attribute is specified, then the result evaluated by the sequence constructor (see 5.7 Sequence Constructors) is converted to the required type, using the function conversion rules. It is a type error if this conversion fails. If the as attribute is omitted, the calculated result is used as supplied, and no conversion takes place.

If a stylesheet function has been defined with a particular expanded QName, then a call on function-available will return true when called with an argument that is a EQName that expands to this same expanded QName.

The xsl:param elements define the formal arguments to the function. These are interpreted positionally. When the function is called using a function-call in an XPath expression, the first argument supplied is assigned to the first xsl:param element, the second argument supplied is assigned to the second xsl:param element, and so on.

The as attribute of the xsl:param element defines the required type of the parameter. The rules for converting the values of the actual arguments supplied in the function call to the types required by each xsl:param element are defined in [XPath 3.0]. The rules that apply are those for the case where XPath 1.0 compatibility mode is set to false.

[ERR XTTE0790] If the value of a parameter to a stylesheet function cannot be converted to the required type, a type error is signaled.

If the as attribute is omitted, no conversion takes place and any value is accepted.

Within the body of a stylesheet function, the focus is initially absent; this means that any attempt to reference the context item, context position, or context size is a non-recoverable dynamic error. [ERR XPDY0002] XP30

It is not possible within the body of the stylesheet function to access the values of local variables that were in scope in the place where the function call was written. Global variables, however, remain available.

Example: A Stylesheet Function

The following example creates a recursive stylesheet function named str:reverse that reverses the words in a supplied sentence, and then invokes this function from within a template rule.

<xsl:transform 
  xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
  xmlns:xs="http://www.w3.org/2001/XMLSchema"
  xmlns:str="http://example.com/namespace"
  version="3.0"
  exclude-result-prefixes="str">

<xsl:function name="str:reverse" as="xs:string">
  <xsl:param name="sentence" as="xs:string"/>
  <xsl:sequence  
     select="if (contains($sentence, ' '))
             then concat(str:reverse(substring-after($sentence, ' ')),
                         ' ',
                         substring-before($sentence, ' '))
             else $sentence"/>
</xsl:function>

<xsl:template match="/">
<output>
  <xsl:value-of select="str:reverse('DOG BITES MAN')"/>
</output>
</xsl:template>

</xsl:transform>

An alternative way of writing the same function is to implement the conditional logic at the XSLT level, thus:

<xsl:function name="str:reverse" as="xs:string">
  <xsl:param name="sentence" as="xs:string"/>
  <xsl:choose>
    <xsl:when test="contains($sentence, ' ')">  
      <xsl:sequence 
           select="concat(str:reverse(substring-after($sentence, ' ')),
                                ' ',
                                substring-before($sentence, ' '))"/>
    </xsl:when>
    <xsl:otherwise>
      <xsl:sequence select="$sentence"/>
    </xsl:otherwise>
  </xsl:choose>
</xsl:function>

 

Example: Declaring the Return Type of a Function

The following example illustrates the use of the as attribute in a function definition. It returns a string containing the representation of its integer argument, expressed as a roman numeral. For example, the function call num:roman(7) will return the string "vii". This example uses the xsl:number instruction, described in 12 Numbering. The xsl:number instruction returns a text node, and the function conversion rules are invoked to convert this text node to the type declared in the xsl:function element, namely xs:string. So the text node is atomized to a string.

<xsl:function name="num:roman" as="xs:string">
  <xsl:param name="value" as="xs:integer"/>
  <xsl:number value="$value" format="i"/>
</xsl:function>

 

Example: A Higher-Order Function

XPath 3.0 introduces the ability to pass function items as argument to a function. A function that takes function items as arguments is known as a higher-order function.

The following example is a higher-order function that operates on any tree-structured data, for example an organization chart. Given as input a function that finds the direct subordinates of a node in this tree structure (for example, the direct reports of a manager, or the geographical subdivisions of an administrative area), it determines whether one object is present in the subtree rooted at another object (for example, whether one person is among the staff managed directly or indirectly by a manager, or whether one parcel of land is contained directly or indirectly within another parcel. The function does not check for cycles in the data.

<xsl:function name="f:is-subordinate" as="xs:boolean">
    <xsl:param name="superior" 
               as="node()"/>
    <xsl:param name="subordinate" 
               as="node()"/>
    <xsl:param name="get-direct-children" 
               as="function(node()) as node()*"/>
    <xsl:sequence select="
               some $sub in $get-direct-children($superior) satisfies
                 ($sub is $subordinate or
                  f:is-subordinate($sub, $subordinate, 
                                      $get-direct-children))"/>
</xsl:function>

Given source data representing an organization chart in the form of elements such as:

<employee id="P57832" manager="P68951"/>

the following function can be defined to get the direct reports of a manager:

<xsl:function name="f:direct-reports" 
               as="element(employee)*">
    <xsl:param name="manager" as="element(employee)"/>
    <xsl:sequence select="$manager/../employee
                               [@manager = current()/@id]"/>
    </xsl:function>

It is then possible to test whether one employee $E reports directly or indirectly to another employee $M by means of the function call:

f:is-subordinate($M, $E, f:direct-reports#1)

10.4 Dynamic XPath Evaluation

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

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

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

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

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

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

Note:

Stylesheet authors need to be aware of the security risks associated with the use of xsl:evaluate. The instruction should not be used to execute code from an untrusted source. To avoid the risk of code injection, user-supplied data should never be inserted into the expression using string concatenation, but should always be referenced by use of parameters. Implementations should provide mechanisms allowing calls on xsl:evaluate to be disabled.

The static contextXP30 for the target expression is as follows:

  • XPath 1.0 compatibility mode is false.

  • Statically known namespaces and default element/type namespace:

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

      [ERR XTTE3170] It is a type error if the result of evaluating the namespace-context attribute of the xsl:evaluate instruction is anything other than a single node.

    • if the namespace-context attribute is absent, then the in-scope namespaces of the xsl:evaluate instruction (with the exception of any binding for the default namespace) are used as the statically known namespaces for the target expression, and the value of the innermost [xsl:]xpath-default-namespace attribute, if any, is used as the default namespace for elements and types in the target expression.

    Note:

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

  • Default function namespace: the standard function namespace.

  • In-scope schema definitions: if the schema-aware attribute is present and has the effective value yes, then the in-scope schema definitions from the stylesheet context (that is, the schema definitions imported using xsl:import-schema). Otherwise, the built-in types (see 3.15 Built-in Types).

  • In-scope variables: the variables defined in the contained xsl:with-param elements.

    Note:

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

  • Function signatures: All core functions; constructor functions for atomic types included in the in-scope schema definitions; user-defined functions declared using xsl:function (but not those declared using xsl:accumulator); and an implementation-defined set of extension functions.

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

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

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

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

  • Statically known documents: the empty set

  • Statically known collections: the empty set

  • Statically known default collection type: node()*

The dynamic context for evaluation of the target expression is as follows:

  • The context item, position, and size depend on the result of evaluating the expression in the context-item attribute. If this attribute is absent, or if the result is an empty sequence, then the context item, position, and size for evaluation of the target expression are all absent. If the result of evaluating the context-item expression is a single item, then the target expression is evaluated with a singleton focus based on this item.

    [ERR XTTE3210] If the result of evaluating the context-item expression is a sequence containing more than one item, then a type error is signaled.

  • The variable values consists of the values bound to parameters defined in the contained xsl:with-param elements, which are evaluated as described in 9.3 Values of Variables and Parameters.

  • The XSLT-specific aspects of the dynamic context described in 5.4.4 Additional Dynamic Context Components used by XSLT are all absent.

  • All other aspects of the dynamic context are the same as the dynamic context for the xsl:evaluate instruction itself.

The dynamic context for evaluation of the target expression is the same as the dynamic context for the xsl:evaluate instruction (in particular, the focus is the same), except for

An XSLT 3.0 processor will ignore any xsl:fallback children of the xsl:evaluate instruction; they can be used to define the behavior of an XSLT 1.0 or XSLT 2.0 processor when this instruction is encountered.

The XPath expression is evaluated in the same execution scopeFO30 as the calling XSLT transformation; this means that the results of deterministicFO30 functions such as docFO30 or current-dateTimeFO30 will be consistent between the calling stylesheet and the called XPath expression.

It is a non-recoverable dynamic error if evaluation of the XPath expression fails with a dynamic error. The XPath-defined error code is used unchanged.

Note:

Implementations wanting to avoid the cost of repeated compilation of the same XPath expression should cache the compiled form internally.

Example: Using a dynamic sort key

A common requirement is to sort a table on the value of an expression which is selected at run-time, perhaps by supplying the expression as a string-valued parameter to the stylesheet. Suppose that such an expression is supplied to the parameter:

<xsl:param name="sortkey" as="xs:string" select="'@name'"/>

Then the data may be sorted as follows:

<xsl:sort>
   <xsl:evaluate xpath="$sortkey" as="xs:string" context-item="."/>
</xsl:sort>

Note the importance in this use case of caching the compiled expression, since it is evaluated repeatedly, once for each item in the list being sorted.

 

Example: Getting a function if it exists

The function-lookupFO30 function, if it were not available in the standard library, could be implemented like this:

     <xsl:function name="f:function-lookup">
       <xsl:param name="name" as="xs:QName"/>
       <xsl:param name="arity" as="xs:integer"/>
       <xsl:evaluate xpath="'Q{' || namespace-uri-from-QName($name) || '}' 
                            || local-name-from-QName($name) || '#' || $arity">
         <xsl:with-param name="name" as="xs:QName" select="$name"/>
         <xsl:with-param name="arity" as="xs:integer" select="$arity"/>
       </xsl:evaluate>
     </xsl:function>  
     

The xsl:evaluate instruction uses the supplied QName and arity to construct an expression of the form Q{namespace-uri}local#arity, which is then evaluated to return a function item representing the requested function.

Issue 9 (evaluate-optional-feature):

The Working Group has not yet decided whether xsl:evaluate will be an optional feature of the language, or whether all implementations will be required to provide it.

11 Creating Nodes and Sequences

This section describes instructions that directly create new nodes, or sequences of nodes, atomic values, and/or function items.

11.1 Literal Result Elements

[Definition: In a sequence constructor, an element in the stylesheet that does not belong to the XSLT namespace and that is not an extension instruction (see 23.2 Extension Instructions) is classified as a literal result element.] A literal result element is evaluated to construct a new element node with the same expanded QName (that is, the same namespace URI, local name, and namespace prefix). The result of evaluating a literal result element is a node sequence containing one element, the newly constructed element node.

The content of the element is a sequence constructor (see 5.7 Sequence Constructors). The sequence obtained by evaluating this sequence constructor, after prepending any attribute nodes produced as described in 11.1.2 Attribute Nodes for Literal Result Elements and namespace nodes produced as described in 11.1.3 Namespace Nodes for Literal Result Elements, is used to construct the content of the element, following the rules in 5.7.1 Constructing Complex Content

The base URI of the new element is copied from the base URI of the literal result element in the stylesheet, unless the content of the new element includes an xml:base attribute, in which case the base URI of the new element is the value of that attribute, resolved (if it is a relative URI reference) against the base URI of the literal result element in the stylesheet. (Note, however, that this is only relevant when creating a parentless element. When the literal result element is copied to form a child of an element or document node, the base URI of the new copy is taken from that of its new parent.)

11.1.1 Setting the Type Annotation for Literal Result Elements

The attributes xsl:type and xsl:validation may be used on a literal result element to invoke validation of the contents of the element against a type definition or element declaration in a schema, and to determine the type annotation that the new element node will carry. These attributes also affect the type annotation carried by any elements and attributes that have the new element node as an ancestor. These two attributes are both optional, and if one is specified then the other must be omitted.

The value of the xsl:validation attribute, if present, must be one of the values strict, lax, preserve, or strip. The value of the xsl:type attribute, if present, must be an EQName identifying a type definition that is present in the in-scope schema components for the stylesheet. Neither attribute may be specified as an attribute value template. The effect of these attributes is described in 24.2 Validation.

11.1.2 Attribute Nodes for Literal Result Elements

Attribute nodes for a literal result element may be created by including xsl:attribute instructions within the sequence constructor. Additionally, attribute nodes are created corresponding to the attributes of the literal result element in the stylesheet, and as a result of expanding the xsl:use-attribute-sets attribute of the literal result element, if present.

The sequence that is used to construct the content of the literal result element (as described in 5.7.1 Constructing Complex Content) is the concatenation of the following four sequences, in order:

  1. The sequence of namespace nodes produced as described in 11.1.3 Namespace Nodes for Literal Result Elements.

  2. The sequence of attribute nodes produced by expanding the xsl:use-attribute-sets attribute (if present) following the rules given in 10.2 Named Attribute Sets

  3. The attributes produced by processing the attributes of the literal result element itself, other than attributes in the XSLT namespace. The way these are processed is described below.

  4. The sequence produced by evaluating the contained sequence constructor, if the element is not empty.

Note:

The significance of this order is that an attribute produced by an xsl:attribute, xsl:copy, or xsl:copy-of instruction in the content of the literal result element takes precedence over an attribute produced by expanding an attribute of the literal result element itself, which in turn takes precedence over an attribute produced by expanding the xsl:use-attribute-sets attribute. This is because of the rules in 5.7.1 Constructing Complex Content, which specify that when two or more attributes in the sequence have the same name, all but the last of the duplicates are discarded.

Although the above rules place namespace nodes before attributes, this is not strictly necessary, because the rules in 5.7.1 Constructing Complex Content allow the namespaces and attributes to appear in any order so long as both come before other kinds of node. The order of namespace nodes and attribute nodes in the sequence has no effect on the relative position of the nodes in document order once they are added to a tree.

Each attribute of the literal result element, other than an attribute in the XSLT namespace, is processed to produce an attribute for the element in the result tree.

The value of such an attribute is interpreted as an attribute value template: it can therefore contain expressions contained in curly brackets ({}). The new attribute node will have the same expanded QName (that is, the same namespace URI, local name, and namespace prefix) as the attribute in the stylesheet tree, and its string value will be the same as the effective value of the attribute in the stylesheet tree. The type annotation on the attribute will initially be xs:untypedAtomic, and the typed value of the attribute node will be the same as its string value.

Note:

The eventual type annotation of the attribute in the result tree depends on the xsl:validation and xsl:type attributes of the parent literal result element, and on the instructions used to create its ancestor elements. If the xsl:validation attribute is set to preserve or strip, the type annotation will be xs:untypedAtomic, and the typed value of the attribute node will be the same as its string value. If the xsl:validation attribute is set to strict or lax, or if the xsl:type attribute is used, the type annotation on the attribute will be set as a result of the schema validation process applied to the parent element. If neither attribute is present, the type annotation on the attribute will be xs:untypedAtomic.

If the name of a constructed attribute is xml:id, the processor must perform attribute value normalization by effectively applying the normalize-spaceFO30 function to the value of the attribute, and the resulting attribute node must be given the is-id property.

[ERR XTRE0795] It is a recoverable dynamic error if the name of a constructed attribute is xml:space and the value is not either default or preserve. The optional recovery action is to construct the attribute with the value as requested. This applies however the attribute is constructed (for example, by using a literal result element, by using the xsl:attribute instruction, or by implicit or explicit copying from a source document).

Note:

The xml:base, xml:lang, xml:space, and xml:id attributes have two effects in XSLT. They behave as standard XSLT attributes, which means for example that if they appear on a literal result element, they will be copied to the result tree in the same way as any other attribute. In addition, they have their standard meaning as defined in the core XML specifications. Thus, an xml:base attribute in the stylesheet affects the base URI of the element on which it appears, and an xml:space attribute affects the interpretation of whitespace text nodes within that element. One consequence of this is that it is inadvisable to write these attributes as attribute value templates: although an XSLT processor will understand this notation, the XML parser will not. See also 11.1.5 Namespace Aliasing which describes how to use xsl:namespace-alias with these attributes.

The same is true of the schema-defined attributes xsi:type, xsi:nil, xsi:noNamespaceSchemaLocation, and xsi:schemaLocation. If the stylesheet is processed by a schema processor, these attributes will be recognized and interpreted by the schema processor, but in addition the XSLT processor treats them like any other attribute on a literal result element: that is, their effective value (after expanding attribute value templates) is copied to the result tree in the same way as any other attribute. If the result tree is validated, the copied attributes will again be recognized and interpreted by the schema processor.

None of these attributes will be generated in the result tree unless the stylesheet writes them to the result tree explicitly, in the same way as any other attribute.

[ERR XTSE0805] It is a static error if an attribute on a literal result element is in the XSLT namespace, unless it is one of the attributes explicitly defined in this specification.

Note:

If there is a need to create attributes in the XSLT namespace, this can be achieved using xsl:attribute, or by means of the xsl:namespace-alias declaration.

11.1.3 Namespace Nodes for Literal Result Elements

The created element node will have a copy of the namespace nodes that were present on the element node in the stylesheet tree with the exception of any namespace node whose string value is designated as an excluded namespace. Special considerations apply to aliased namespaces: see 11.1.5 Namespace Aliasing

The following namespaces are designated as excluded namespaces:

  • The XSLT namespace URI (http://www.w3.org/1999/XSL/Transform)

  • A namespace URI declared as an extension namespace (see 23.2 Extension Instructions)

  • A namespace URI designated by using an [xsl:]exclude-result-prefixes attribute either on the literal result element itself or on an ancestor element. The attribute must be in the XSLT namespace only if its parent element is not in the XSLT namespace.

    The value of the attribute is either #all, or a whitespace-separated list of tokens, each of which is either a namespace prefix or #default. The namespace bound to each of the prefixes is designated as an excluded namespace.

    [ERR XTSE0808] It is a static error if a namespace prefix is used within the [xsl:]exclude-result-prefixes attribute and there is no namespace binding in scope for that prefix.

    The default namespace of the parent element of the [xsl:]exclude-result-prefixes attribute (see Section 6.2 Element Nodes DM30) may be designated as an excluded namespace by including #default in the list of namespace prefixes.

    [ERR XTSE0809] It is a static error if the value #default is used within the [xsl:]exclude-result-prefixes attribute and the parent element of the [xsl:]exclude-result-prefixes attribute has no default namespace.

    The value #all indicates that all namespaces that are in scope for the stylesheet element that is the parent of the [xsl:]exclude-result-prefixes attribute are designated as excluded namespaces.

    The designation of a namespace as an excluded namespace is effective within the subtree of the stylesheet module rooted at the element bearing the [xsl:]exclude-result-prefixes attribute; a subtree rooted at an xsl:stylesheet element does not include any stylesheet modules imported or included by children of that xsl:stylesheet element.

The excluded namespaces, as described above, only affect namespace nodes copied from the stylesheet when processing a literal result element. There is no guarantee that an excluded namespace will not appear on the result tree for some other reason. Namespace nodes are also written to the result tree as part of the process of namespace fixup (see 5.7.3 Namespace Fixup), or as the result of instructions such as xsl:copy and xsl:element.

Note:

When a stylesheet uses a namespace declaration only for the purposes of addressing a source tree, specifying the prefix in the [xsl:]exclude-result-prefixes attribute will avoid superfluous namespace declarations in the serialized result tree. The attribute is also useful to prevent namespaces used solely for the naming of stylesheet functions or extension functions from appearing in the serialized result tree.

Example: Excluding Namespaces from the Result Tree

For example, consider the following stylesheet:

<xsl:stylesheet version="1.0"
  xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
  xmlns:a="a.uri"
  xmlns:b="b.uri"
  exclude-result-prefixes="#all">
  
<xsl:template match="/">
  <foo xmlns:c="c.uri" xmlns:d="d.uri" xmlns:a2="a.uri" 
       xsl:exclude-result-prefixes="c"/>
</xsl:template>

</xsl:stylesheet>

The result of this stylesheet will be:

<foo xmlns:d="d.uri"/>

The namespaces a.uri and b.uri are excluded by virtue of the exclude-result-prefixes attribute on the xsl:stylesheet element, and the namespace c.uri is excluded by virtue of the xsl:exclude-result-prefixes attribute on the foo element. The setting #all does not affect the namespace d.uri because d.uri is not an in-scope namespace for the xsl:stylesheet element. The element in the result tree does not have a namespace node corresponding to xmlns:a2="a.uri" because the effect of exclude-result-prefixes is to designate the namespace URI a.uri as an excluded namespace, irrespective of how many prefixes are bound to this namespace URI.

If the stylesheet is changed so that the literal result element has an attribute b:bar="3", then the element in the result tree will typically have a namespace declaration xmlns:b="b.uri" (the processor may choose a different namespace prefix if this is necessary to avoid conflicts). The exclude-result-prefixes attribute makes b.uri an excluded namespace, so the namespace node is not automatically copied from the stylesheet, but the presence of an attribute whose name is in the namespace b.uri forces the namespace fixup process (see 5.7.3 Namespace Fixup) to introduce a namespace node for this namespace.

A literal result element may have an optional xsl:inherit-namespaces attribute, with the value yes or no. The default value is yes. If the value is set to yes, or is omitted, then the namespace nodes created for the newly constructed element are copied to the children and descendants of the newly constructed element, as described in 5.7.1 Constructing Complex Content. If the value is set to no, then these namespace nodes are not automatically copied to the children. This may result in namespace undeclarations (such as xmlns="" or, in the case of XML 1.1, xmlns:p="") appearing on the child elements when a final result tree is serialized.

11.1.4 Conditional Creation of Literal Result Elements

If a literal result element has an xsl:on-empty attribute, then the value of the attribute must be an XPath expression. If the attribute is present and the content of the constructed element contains nothing other than namespace nodes and zero-length text nodes, then instead of returning the constructed element, the instruction returns the result of evaluating the expression in the xsl:on-empty attribute.

In this situation (when no element is returned because the content is empty), the xsl:validation and xsl:type attributes are ignored: no validation of the content is performed.

Note that when a literal result element has one or more attributes (other than attributes in the XSLT namespace), or when it references a non-empty attribute set, the on-empty attribute has no effect because these conditions will not be satisfied.

Example: Generating a wrapper element for a non-empty sequence

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

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

However, the above code would not be guaranteed streamable. To make it streamable, it can be rewritten as:

<events xsl:on-empty="()">
    <xsl:copy-of select="event"/>
</events>

Note:

The reason for introducing the on-empty attribute is primarily to make it easier to write applications that conform to the rules for guaranteed streamability. A common requirement is to generate a wrapper element for a sequence of elements (for example an events wrapper for a sequence of event elements) only if the content sequence is non-empty. Without the xsl:on-empty attribute this is difficult to achieve, because testing whether any event element exists and processing the set of event elements both count as consuming instructions.

11.1.5 Namespace Aliasing

When a stylesheet is used to define a transformation whose output is itself a stylesheet module, or in certain other cases where the result document uses namespaces that it would be inconvenient to use in the stylesheet, namespace aliasing can be used to declare a mapping between a namespace URI used in the stylesheet and the corresponding namespace URI to be used in the result document.

[Definition: A namespace URI in the stylesheet tree that is being used to specify a namespace URI in the result tree is called a literal namespace URI.]

[Definition: The namespace URI that is to be used in the result tree as a substitute for a literal namespace URI is called the target namespace URI.]

Either of the literal namespace URI or the target namespace URI can be null: this is treated as a reference to the set of names that are in no namespace.

<!-- Category: declaration -->
<xsl:namespace-alias
  stylesheet-prefix = prefix | "#default"
  result-prefix = prefix | "#default" />

[Definition: A stylesheet can use the xsl:namespace-alias element to declare that a literal namespace URI is being used as an alias for a target namespace URI.]

The effect is that when names in the namespace identified by the literal namespace URI are copied to the result tree, the namespace URI in the result tree will be the target namespace URI, instead of the literal namespace URI. This applies to:

  • the namespace URI in the expanded QName of a literal result element in the stylesheet

  • the namespace URI in the expanded QName of an attribute specified on a literal result element in the stylesheet

The effect of an xsl:namespace-alias declaration is local to the package in which it appears: that is, it only affects the result of literal result elements within the same package.

Where namespace aliasing changes the namespace URI part of the expanded QName containing the name of an element or attribute node, the namespace prefix in that expanded QName is replaced by the prefix indicated by the result-prefix attribute of the xsl:namespace-alias declaration.

The xsl:namespace-alias element declares that the namespace URI bound to the prefix specified by the stylesheet-prefix is the literal namespace URI, and the namespace URI bound to the prefix specified by the result-prefix attribute is the target namespace URI. Thus, the stylesheet-prefix attribute specifies the namespace URI that will appear in the stylesheet, and the result-prefix attribute specifies the corresponding namespace URI that will appear in the result tree.

The default namespace (as declared by xmlns) may be specified by using #default instead of a prefix. If no default namespace is in force, specifying #default denotes the null namespace URI. This allows elements that are in no namespace in the stylesheet to acquire a namespace in the result document, or vice versa.

If a literal namespace URI is declared to be an alias for multiple different target namespace URIs, then the declaration with the highest import precedence is used.

[ERR XTSE0810] It is a static error if within a package there is more than one such declaration with the same literal namespace URI and the same import precedence and different values for the target namespace URI, unless there is also an xsl:namespace-alias declaration with the same literal namespace URI and a higher import precedence.

[ERR XTSE0812] It is a static error if a value other than #default is specified for either the stylesheet-prefix or the result-prefix attributes of the xsl:namespace-alias element when there is no in-scope binding for that namespace prefix.

When a literal result element is processed, its namespace nodes are handled as follows:

In the event that the same URI is used as a literal namespace URI and a target namespace URI, the second of these rules takes precedence.

Note:

These rules achieve the effect that the element generated from the literal result element will have an in-scope namespace node that binds the result-prefix to the target namespace URI, provided that the namespace declaration associating this prefix with this URI is in scope for both the xsl:namespace-alias instruction and for the literal result element. Conversely, the stylesheet-prefix and the literal namespace URI will not normally appear in the result tree.

Example: Using xsl:namespace-alias to Generate a Stylesheet

When literal result elements are being used to create element, attribute, or namespace nodes that use the XSLT namespace URI, the stylesheet may use an alias.

For example, the stylesheet

<xsl:stylesheet
  version="3.0"
  xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
  xmlns:fo="http://www.w3.org/1999/XSL/Format"
  xmlns:axsl="file://namespace.alias">

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

<xsl:template match="/">
  <axsl:stylesheet version="3.0">
    <xsl:apply-templates/>
  </axsl:stylesheet>
</xsl:template>

<xsl:template match="elements">
  <axsl:template match="/">
     <axsl:comment select="system-property('xsl:version')"/>
     <axsl:apply-templates/>
  </axsl:template>
</xsl:template>

<xsl:template match="block">
  <axsl:template match="{.}">
     <fo:block><axsl:apply-templates/></fo:block>
  </axsl:template>
</xsl:template>

</xsl:stylesheet>

will generate an XSLT stylesheet from a document of the form:

<elements>
<block>p</block>
<block>h1</block>
<block>h2</block>
<block>h3</block>
<block>h4</block>
</elements>

The output of the transformation will be a stylesheet such as the following. Whitespace has been added for clarity. Note that an implementation may output different namespace prefixes from those appearing in this example; however, the rules guarantee that there will be a namespace node that binds the prefix xsl to the URI http://www.w3.org/1999/XSL/Transform, which makes it safe to use the QName xsl:version in the content of the generated stylesheet.

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

<xsl:template match="/">
  <xsl:comment select="system-property('xsl:version')"/>
  <xsl:apply-templates/>
</xsl:template>
  
<xsl:template match="p">
  <fo:block><xsl:apply-templates/></fo:block>
</xsl:template>

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

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

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

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

</xsl:stylesheet>

Note:

It may be necessary also to use aliases for namespaces other than the XSLT namespace URI. For example, it can be useful to define an alias for the namespace http://www.w3.org/2001/XMLSchema-instance, so that the stylesheet can use the attributes xsi:type, xsi:nil, and xsi:schemaLocation on a literal result element, without running the risk that a schema processor will interpret these as applying to the stylesheet itself. Equally, literal result elements belonging to a namespace dealing with digital signatures might cause XSLT stylesheets to be mishandled by general-purpose security software; using an alias for the namespace would avoid the possibility of such mishandling.

Example: Aliasing the XML Namespace

It is possible to define an alias for the XML namespace.

<xsl:stylesheet xmlns:axml="http://www.example.com/alias-xml"
                xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
                version="3.0">

<xsl:namespace-alias stylesheet-prefix="axml" result-prefix="xml"/>

<xsl:template match="/">
  <name axml:space="preserve">
    <first>James</first>
    <xsl:text> </xsl:text>
    <last>Clark</last>
  </name>
</xsl:template>

</xsl:stylesheet>

produces the output:

<name xml:space="preserve"><first>James</first> <last>Clark</last></name>

This allows an xml:space attribute to be generated in the output without affecting the way the stylesheet is parsed. The same technique can be used for other attributes such as xml:lang, xml:base, and xml:id.

Note:

Namespace aliasing is only necessary when literal result elements are used. The problem of reserved namespaces does not arise when using xsl:element and xsl:attribute to construct the result tree. Therefore, as an alternative to using xsl:namespace-alias, it is always possible to achieve the desired effect by replacing literal result elements with xsl:element and xsl:attribute instructions.

11.2 Creating Element Nodes Using xsl:element

<!-- Category: instruction -->
<xsl:element
  name = { qname }
  namespace? = { uri }
  inherit-namespaces? = "yes" | "no"
  use-attribute-sets? = eqnames
  type? = eqname
  validation? = "strict" | "lax" | "preserve" | "strip"
  on-empty? = expression >
  <!-- Content: sequence-constructor -->
</xsl:element>

The xsl:element instruction allows an element to be created with a computed name. The expanded QName of the element to be created is specified by a required name attribute and an optional namespace attribute.

The result of evaluating the xsl:element instruction, in usual circumstances, is the newly constructed element node.

11.2.1 The Content of the Constructed Element Node

The content of the xsl:element instruction is a sequence constructor for the children, attributes, and namespaces of the created element. The sequence obtained by evaluating this sequence constructor (see 5.7 Sequence Constructors) is used to construct the content of the element, as described in 5.7.1 Constructing Complex Content.

The xsl:element element may have a use-attribute-sets attribute, whose value is a whitespace-separated list of QNames that identify xsl:attribute-set declarations. If this attribute is present, it is expanded as described in 10.2 Named Attribute Sets to produce a sequence of attribute nodes. This sequence is prepended to the sequence produced as a result of evaluating the sequence constructor, as described in 5.7.1 Constructing Complex Content.

11.2.2 The Name of the Constructed Element Node

The name attribute is interpreted as an attribute value template, whose effective value must be a lexical QName.

[ERR XTDE0820] It is a non-recoverable dynamic error if the effective value of the name attribute is not a lexical QName.

[ERR XTDE0830] In the case of an xsl:element instruction with no namespace attribute, it is a non-recoverable dynamic error if the effective value of the name attribute is a lexical QName whose prefix is not declared in an in-scope namespace declaration for the xsl:element instruction.

If the namespace attribute is not present then the lexical QName is expanded into an expanded QName using the namespace declarations in effect for the xsl:element element, including any default namespace declaration.

If the namespace attribute is present, then it too is interpreted as an attribute value template. The effective value must be in the lexical space of the xs:anyURI type. If the string is zero-length, then the expanded QName of the element has a null namespace URI. Otherwise, the string is used as the namespace URI of the expanded QName of the element to be created. The local part of the lexical QName specified by the name attribute is used as the local part of the expanded QName of the element to be created.

[ERR XTDE0835] It is a non-recoverable dynamic error if the effective value of the namespace attribute is not in the lexical space of the xs:anyURI datatype or if it is the string http://www.w3.org/2000/xmlns/.

Note:

The XDM data model requires the name of a node to be an instance of xs:QName, and XML Schema defines the namespace part of an xs:QName to be an instance of xs:anyURI. However, the schema specification, and the specifications that it refers to, give implementations some flexibility in how strictly they enforce these constraints.

The prefix of the lexical QName specified in the name attribute (or the absence of a prefix) is copied to the prefix part of the expanded QName representing the name of the new element node. In the event of a conflict a prefix may subsequently be added, changed, or removed during the namespace fixup process (see 5.7.3 Namespace Fixup). The term conflict here means any violation of the constraints defined in [Data Model], for example the use of the same prefix to refer to two different namespaces in the element and in one of its attributes, the use of the prefix xml to refer to a namespace other than the XML namespace, or any use of the prefix xmlns.

11.2.3 Other Properties of the Constructed Element Node

The xsl:element instruction has an optional inherit-namespaces attribute, with the value yes or no. The default value is yes. If the value is set to yes, or is omitted, then the namespace nodes created for the newly constructed element (whether these were copied from those of the source node, or generated as a result of namespace fixup) are copied to the children and descendants of the newly constructed element, as described in 5.7.1 Constructing Complex Content. If the value is set to no, then these namespace nodes are not automatically copied to the children. This may result in namespace undeclarations (such as xmlns="" or, in the case of XML Namespaces 1.1, xmlns:p="") appearing on the child elements when a final result tree is serialized.

The base URI of the new element is copied from the base URI of the xsl:element instruction in the stylesheet, unless the content of the new element includes an xml:base attribute, in which case the base URI of the new element is the value of that attribute, resolved (if it is a relative URI) against the base URI of the xsl:element instruction in the stylesheet. (Note, however, that this is only relevant when creating parentless elements. When the new element is copied to form a child of an element or document node, the base URI of the new copy is taken from that of its new parent.)

11.2.4 The Type Annotation of the Constructed Element Node

The optional attributes type and validation may be used on the xsl:element instruction to invoke validation of the contents of the element against a type definition or element declaration in a schema, and to determine the type annotation that the new element node will carry. These attributes also affect the type annotation carried by any elements and attributes that have the new element node as an ancestor. These two attributes are both optional, and if one is specified then the other must be omitted. The permitted values of these attributes and their semantics are described in 24.2 Validation.

Note:

The final type annotation of the element in the result tree also depends on the type and validation attributes of the instructions used to create the ancestors of the element.

11.2.5 Conditional Construction of Element Nodes

If the on-empty attribute is present and the content of the constructed element as determined by the rules in 11.2.1 The Content of the Constructed Element Node (that is, the result of evaluating the sequence constructor and prepending any attributes generated by the use-attribute-sets attribute) is a sequence containing nothing other than namespace nodes and zero-length text nodes, then instead of returning the newly constructed element node, the instruction returns the result of evaluating the expression in the on-empty attribute.

In this situation (when no element is returned because the content is empty), the validation and type attributes are ignored: no validation of the content is performed.

11.3 Creating Attribute Nodes Using xsl:attribute

<!-- Category: instruction -->
<xsl:attribute
  name = { qname }
  namespace? = { uri }
  select? = expression
  separator? = { string }
  type? = eqname
  validation? = "strict" | "lax" | "preserve" | "strip"
  on-empty? = expression >
  <!-- Content: sequence-constructor -->
</xsl:attribute>

The xsl:attribute element can be used to add attributes to result elements whether created by literal result elements in the stylesheet or by instructions such as xsl:element or xsl:copy. The expanded QName of the attribute to be created is specified by a required name attribute and an optional namespace attribute. Except in error cases, the result of evaluating an xsl:attribute instruction is the newly constructed attribute node.

The string value of the new attribute node may be defined either by using the select attribute, or by the sequence constructor that forms the content of the xsl:attribute element. These are mutually exclusive: if the select attribute is present then the sequence constructor must be empty, and if the sequence constructor is non-empty then the select attribute must be absent. If the select attribute is absent and the sequence constructor is empty, then the string value of the new attribute node will be a zero-length string. The way in which the value is constructed is specified in 5.7.2 Constructing Simple Content.

[ERR XTSE0840] It is a static error if the select attribute of the xsl:attribute element is present unless the element has empty content.

If the separator attribute is present, then the effective value of this attribute is used to separate adjacent items in the result sequence, as described in 5.7.2 Constructing Simple Content. In the absence of this attribute, the default separator is a single space (#x20) when the content is specified using the select attribute, or a zero-length string when the content is specified using a sequence constructor.

The name attribute is interpreted as an attribute value template, whose effective value must be a lexical QName.

[ERR XTDE0850] It is a non-recoverable dynamic error if the effective value of the name attribute is not a lexical QName.

[ERR XTDE0855] In the case of an xsl:attribute instruction with no namespace attribute, it is a non-recoverable dynamic error if the effective value of the name attribute is the string xmlns.

[ERR XTDE0860] In the case of an xsl:attribute instruction with no namespace attribute, it is a non-recoverable dynamic error if the effective value of the name attribute is a lexical QName whose prefix is not declared in an in-scope namespace declaration for the xsl:attribute instruction.

If the namespace attribute is not present, then the lexical QName is expanded into an expanded QName using the namespace declarations in effect for the xsl:attribute element, not including any default namespace declaration.

If the namespace attribute is present, then it too is interpreted as an attribute value template. The effective value must be in the lexical space of the xs:anyURI type. If the string is zero-length, then the expanded QName of the attribute has a null namespace URI. Otherwise, the string is used as the namespace URI of the expanded QName of the attribute to be created. The local part of the lexical QName specified by the name attribute is used as the local part of the expanded QName of the attribute to be created.

[ERR XTDE0865] It is a non-recoverable dynamic error if the effective value of the namespace attribute is not in the lexical space of the xs:anyURI datatype or if it is the string http://www.w3.org/2000/xmlns/.

Note:

The same considerations apply as for elements: [see ERR XTDE0835] in 11.2 Creating Element Nodes Using xsl:element .

The prefix of the lexical QName specified in the name attribute (or the absence of a prefix) is copied to the prefix part of the expanded QName representing the name of the new attribute node. In the event of a conflict this prefix may subsequently be added, changed, or removed during the namespace fixup process (see 5.7.3 Namespace Fixup). If the attribute is in a non-null namespace and no prefix is specified, then the namespace fixup process will invent a prefix. The term conflict here means any violation of the constraints defined in [Data Model], for example the use of the same prefix to refer to two different namespaces in the element and in one of its attributes, the use of the prefix xml to refer to a namespace other than the XML namespace, or any use of the prefix xmlns.

If the name of a constructed attribute is xml:id, the processor must perform attribute value normalization by effectively applying the normalize-spaceFO30 function to the value of the attribute, and the resulting attribute node must be given the is-id property. This applies whether the attribute is constructed using the xsl:attribute instruction or whether it is constructed using an attribute of a literal result element. This does not imply any constraints on the value of the attribute, or on its uniqueness, and it does not affect the type annotation of the attribute, unless the containing document is validated.

Note:

The effect of setting the is-id property is that the parent element can be located within the containing document by use of the idFO30 function. In effect, XSLT when constructing a document performs some of the functions of an xml:id processor, as defined in [xml:id]; the other aspects of xml:id processing are performed during validation.

Example: Creating a List-Valued Attribute

The following instruction creates the attribute colors="red green blue":

<xsl:attribute name="colors" select="'red', 'green', 'blue'"/>

 

Example: Namespaces are not Attributes

It is not an error to write:

<xsl:attribute name="xmlns:xsl" 
   namespace="file://some.namespace"
   select="'http://www.w3.org/1999/XSL/Transform'"/>

However, this will not result in the namespace declaration xmlns:xsl="http://www.w3.org/1999/XSL/Transform" being output. Instead, it will produce an attribute node with local name xsl, and with a system-allocated namespace prefix mapped to the namespace URI file://some.namespace. This is because the namespace fixup process is not allowed to use xmlns as the name of a namespace node.

As described in 5.7.1 Constructing Complex Content, in a sequence that is used to construct the content of an element, any attribute nodes must appear in the sequence before any element, text, comment, or processing instruction nodes. Where the sequence contains two or more attribute nodes with the same expanded QName, the one that comes last is the only one that takes effect.

Note:

If a collection of attributes is generated repeatedly, this can be done conveniently by using named attribute sets: see 10.2 Named Attribute Sets

11.3.1 Setting the Type Annotation for a Constructed Attribute Node

The optional attributes type and validation may be used on the xsl:attribute instruction to invoke validation of the contents of the attribute against a type definition or attribute declaration in a schema, and to determine the type annotation that the new attribute node will carry. These two attributes are both optional, and if one is specified then the other must be omitted. The permitted values of these attributes and their semantics are described in 24.2 Validation.

Note:

The final type annotation of the attribute in the result tree also depends on the type and validation attributes of the instructions used to create the ancestors of the attribute.

11.3.2 Conditional Creation of Attribute Nodes

If the on-empty attribute is present and the string value of the constructed attribute is a zero-length string, then instead of returning the constructed attribute, the instruction returns the result of evaluating the expression in the on-empty attribute.

In this situation (where the constructed attribute is not returned because its value is zero-length) the validation and type attributes are ignored; no validation of the content takes place.

11.4 Creating Text Nodes

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

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

Example: A sequence of text nodes

The following function returns a sequence of three text nodes:

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

When this function is called as follows:

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

the result is:

(---)

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

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

is:

( --- )

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

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

11.4.1 Literal Text Nodes

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

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

11.4.2 Creating Text Nodes Using xsl:text

<!-- Category: instruction -->
<xsl:text
  [disable-output-escaping]? = "yes" | "no" >
  <!-- Content: #PCDATA -->
</xsl:text>

The xsl:text element is evaluated to construct a new text node. The content of the xsl:text element is a single text node whose value forms the string value of the new text node. An xsl:text element may be empty, in which case the result of evaluating the instruction is a text node whose string value is the zero-length string.

The result of evaluating an xsl:text instruction is the newly constructed text node.

A text node that is an immediate child of an xsl:text instruction will not be stripped from the stylesheet tree, even if it consists entirely of whitespace (see 4.4 Stripping Whitespace from a Source Tree).

For the effect of the deprecated disable-output-escaping attribute, see 25.2 Disabling Output Escaping

Note:

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

11.4.3 Generating Text with xsl:value-of

Within a sequence constructor, the xsl:value-of instruction can be used to generate computed text nodes. The xsl:value-of instruction computes the text using an expression that is specified as the value of the select attribute, or by means of contained instructions. This might, for example, extract text from a source tree or insert the value of a variable.

<!-- Category: instruction -->
<xsl:value-of
  select? = expression
  separator? = { string }
  [disable-output-escaping]? = "yes" | "no" >
  <!-- Content: sequence-constructor -->
</xsl:value-of>

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

The string value of the new text node may be defined either by using the select attribute, or by the sequence constructor (see 5.7 Sequence Constructors) that forms the content of the xsl:value-of element. These are mutually exclusive: if the select attribute is present then the sequence constructor must be empty, and if the sequence constructor is non-empty then the select attribute must be absent. If the select attribute is absent and the sequence constructor is empty, then the result of the instruction is a text node whose string value is zero-length. The way in which the value is constructed is specified in 5.7.2 Constructing Simple Content.

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

If the separator attribute is present, then the effective value of this attribute is used to separate adjacent items in the result sequence, as described in 5.7.2 Constructing Simple Content. In the absence of this attribute, the default separator is a single space (#x20) when the content is specified using the select attribute, or a zero-length string when the content is specified using a sequence constructor.

Special rules apply when the instruction is processed with XSLT 1.0 behavior. If no separator attribute is present, and if the select attribute is present, then all items in the atomized result sequence other than the first are ignored.

Example: Generating a List with Separators

The instruction:

<x><xsl:value-of select="1 to 4" separator="|"/></x>

produces the output:

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

Note:

The xsl:copy-of element can be used to copy a sequence of nodes to the result tree without atomization. See 11.9.2 Deep Copy.

For the effect of the deprecated disable-output-escaping attribute, see 25.2 Disabling Output Escaping

11.5 Creating Document Nodes

<!-- Category: instruction -->
<xsl:document
  validation? = "strict" | "lax" | "preserve" | "strip"
  type? = eqname >
  <!-- Content: sequence-constructor -->
</xsl:document>

The xsl:document instruction is used to create a new document node. The content of the xsl:document element is a sequence constructor for the children of the new document node. A document node is created, and the sequence obtained by evaluating the sequence constructor is used to construct the content of the document, as described in 5.7.1 Constructing Complex Content. The temporary tree rooted at this document node forms the result tree.

Except in error situations, the result of evaluating the xsl:document instruction is a single node, the newly constructed document node.

Note:

The new document is not serialized. To construct a document that is to form a final result rather than an intermediate result, use the xsl:result-document instruction described in 24.1 Creating Final Result Trees.

The optional attributes type and validation may be used on the xsl:document instruction to validate the contents of the new document, and to determine the type annotation that elements and attributes within the result tree will carry. The permitted values and their semantics are described in 24.2.2 Validating Document Nodes.

The base URI of the new document node is taken from the base URI of the xsl:document instruction.

The document-uri and unparsed-entities properties of the new document node are set to empty.

Example: Checking Uniqueness Constraints in a Temporary Tree

The following example creates a temporary tree held in a variable. The use of an enclosed xsl:document instruction ensures that uniqueness constraints defined in the schema for the relevant elements are checked.

<xsl:variable name="tree" as="document-node()">
  <xsl:document validation="strict">
    <xsl:apply-templates/>
  </xsl:document>
</xsl:variable>

11.6 Creating Processing Instructions

<!-- Category: instruction -->
<xsl:processing-instruction
  name = { ncname }
  select? = expression >
  <!-- Content: sequence-constructor -->
</xsl:processing-instruction>

The xsl:processing-instruction element is evaluated to create a processing instruction node.

The xsl:processing-instruction element has a required name attribute that specifies the name of the processing instruction node. The value of the name attribute is interpreted as an attribute value template.

The string value of the new processing-instruction node may be defined either by using the select attribute, or by the sequence constructor that forms the content of the xsl:processing-instruction element. These are mutually exclusive: if the select attribute is present then the sequence constructor must be empty, and if the sequence constructor is non-empty then the select attribute must be absent. If the select attribute is absent and the sequence constructor is empty, then the string value of the new processing-instruction node will be a zero-length string. The way in which the value is constructed is specified in 5.7.2 Constructing Simple Content.

[ERR XTSE0880] It is a static error if the select attribute of the xsl:processing-instruction element is present unless the element has empty content.

Except in error situations, the result of evaluating the xsl:processing-instruction instruction is a single node, the newly constructed processing instruction node.

Example: Creating a Processing Instruction

This instruction:

<xsl:processing-instruction name="xml-stylesheet"
  select="('href=&quot;book.css&quot;', 'type=&quot;text/css&quot;)"/>

creates the processing instruction

<?xml-stylesheet href="book.css" type="text/css"?>

Note that the xml-stylesheet processing instruction contains pseudo-attributes in the form name="value". Although these have the same textual form as attributes in an element start tag, they are not represented as XDM attribute nodes, and cannot therefore be constructed using xsl:attribute instructions.

[ERR XTDE0890] It is a non-recoverable dynamic error if the effective value of the name attribute is not both an NCNameNames and a PITargetXML.

Note:

Because these rules disallow the name xml, the xsl:processing-instruction cannot be used to output an XML declaration. The xsl:output declaration should be used to control this instead (see 25 Serialization).

If the result of evaluating the content of the xsl:processing-instruction contains the string ?>, this string is modified by inserting a space between the ? and > characters.

The base URI of the new processing-instruction is copied from the base URI of the xsl:processing-instruction element in the stylesheet. (Note, however, that this is only relevant when creating a parentless processing instruction. When the new processing instruction is copied to form a child of an element or document node, the base URI of the new copy is taken from that of its new parent.)

11.7 Creating Namespace Nodes

<!-- Category: instruction -->
<xsl:namespace
  name = { ncname }
  select? = expression >
  <!-- Content: sequence-constructor -->
</xsl:namespace>

The xsl:namespace element is evaluated to create a namespace node. Except in error situations, the result of evaluating the xsl:namespace instruction is a single node, the newly constructed namespace node.

The xsl:namespace element has a required name attribute that specifies the name of the namespace node (that is, the namespace prefix). The value of the name attribute is interpreted as an attribute value template. If the effective value of the name attribute is a zero-length string, a namespace node is added for the default namespace.

The string value of the new namespace node (that is, the namespace URI) may be defined either by using the select attribute, or by the sequence constructor that forms the content of the xsl:namespace element. These are mutually exclusive: if the select attribute is present then the sequence constructor must be empty, and if the sequence constructor is non-empty then the select attribute must be absent. Since the string value of a namespace node cannot be a zero-length string, either a select attribute or a non-empty sequence constructor must be present. The way in which the value is constructed is specified in 5.7.2 Constructing Simple Content.

[ERR XTDE0905] It is a non-recoverable dynamic error if the string value of the new namespace node is not valid in the lexical space of the datatype xs:anyURI, or if it is the string http://www.w3.org/2000/xmlns/.

[ERR XTSE0910] It is a static error if the select attribute of the xsl:namespace element is present when the element has content other than one or more xsl:fallback instructions, or if the select attribute is absent when the element has empty content.

Note the restrictions described in 5.7.1 Constructing Complex Content for the position of a namespace node relative to other nodes in the node sequence returned by a sequence constructor.

Example: Constructing a QName-Valued Attribute

This literal result element:

<data xsi:type="xs:integer" 
             xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
  <xsl:namespace name="xs" 
                 select="'http://www.w3.org/2001/XMLSchema'"/>
  <xsl:text>42</xsl:text>
</data>

would typically cause the output document to contain the element:

<data xsi:type="xs:integer"
     xmlns:xs="http://www.w3.org/2001/XMLSchema"
     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">42</data>

In this case, the element is constructed using a literal result element, and the namespace xmlns:xs="http://www.w3.org/2001/XMLSchema" could therefore have been added to the result tree simply by declaring it as one of the in-scope namespaces in the stylesheet. In practice, the xsl:namespace instruction is more likely to be useful in situations where the element is constructed using an xsl:element instruction, which does not copy all the in-scope namespaces from the stylesheet.

[ERR XTDE0920] It is a non-recoverable dynamic error if the effective value of the name attribute is neither a zero-length string nor an NCNameNames, or if it is xmlns.

[ERR XTDE0925] It is a non-recoverable dynamic error if the xsl:namespace instruction generates a namespace node whose name is xml and whose string value is not http://www.w3.org/XML/1998/namespace, or a namespace node whose string value is http://www.w3.org/XML/1998/namespace and whose name is not xml.

[ERR XTDE0930] It is a non-recoverable dynamic error if evaluating the select attribute or the contained sequence constructor of an xsl:namespace instruction results in a zero-length string.

For details of other error conditions that may arise, see 5.7 Sequence Constructors.

Note:

It is rarely necessary to use xsl:namespace to create a namespace node in the result tree; in most circumstances, the required namespace nodes will be created automatically, as a side-effect of writing elements or attributes that use the namespace. An example where xsl:namespace is needed is a situation where the required namespace is used only within attribute values in the result document, not in element or attribute names; especially where the required namespace prefix or namespace URI is computed at run-time and is not present in either the source document or the stylesheet.

Adding a namespace node to the result tree will never change the expanded QName of any element or attribute node in the result tree: that is, it will never change the namespace URI of an element or attribute. It might, however, constrain the choice of prefixes when namespace fixup is performed.

Namespace prefixes for element and attribute names are initially established by the rules of the instruction that creates the element or attribute node, and in the event of conflicts, they may be changed by the namespace fixup process described in 5.7.3 Namespace Fixup. The fixup process ensures that an element has in-scope namespace nodes for the namespace URIs used in the element name and in its attribute names, and the serializer will typically use these namespace nodes to determine the prefix to use in the serialized output. The fixup process cannot generate namespace nodes that are inconsistent with those already present in the tree. This means that it is not possible for the processor to decide the prefix to use for an element or for any of its attributes until all the namespace nodes for the element have been added.

If a namespace prefix is mapped to a particular namespace URI using the xsl:namespace instruction, or by using xsl:copy or xsl:copy-of to copy a namespace node, this prevents the namespace fixup process (and hence the serializer) from using the same prefix for a different namespace URI on the same element.

Example: Conflicting Namespace Prefixes

Given the instruction:

<xsl:element name="p:item" 
                 xmlns:p="http://www.example.com/p">
  <xsl:namespace name="p">http://www.example.com/q</xsl:namespace>
</xsl:element>

a possible serialization of the result tree is:

<ns0:item 
    xmlns:ns0="http://www.example.com/p" 
    xmlns:p="http://www.example.com/q"/>

The processor must invent a namespace prefix for the URI p.uri; it cannot use the prefix p because that prefix has been explicitly associated with a different URI.

Note:

The xsl:namespace instruction cannot be used to generate a namespace undeclaration of the form xmlns="" (nor the new forms of namespace undeclaration permitted in [Namespaces in XML 1.1]). Namespace undeclarations are generated automatically by the serializer if undeclare-prefixes="yes" is specified on xsl:output, whenever a parent element has a namespace node for the default namespace prefix, and a child element has no namespace node for that prefix.

11.8 Creating Comments

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

The xsl:comment element is evaluated to construct a new comment node. Except in error cases, the result of evaluating the xsl:comment instruction is a single node, the newly constructed comment node.

The string value of the new comment node may be defined either by using the select attribute, or by the sequence constructor that forms the content of the xsl:comment element. These are mutually exclusive: if the select attribute is present then the sequence constructor must be empty, and if the sequence constructor is non-empty then the select attribute must be absent. If the select attribute is absent and the sequence constructor is empty, then the string value of the new comment node will be a zero-length string. The way in which the value is constructed is specified in 5.7.2 Constructing Simple Content.

[ERR XTSE0940] It is a static error if the select attribute of the xsl:comment element is present unless the element has empty content.

Example: Generating a Comment Node

For example, this

<xsl:comment>This file is automatically generated. Do not edit!</xsl:comment>

would create the comment

<!--This file is automatically generated. Do not edit!-->

In the generated comment node, the processor must insert a space after any occurrence of - that is followed by another - or that ends the comment.

11.9 Copying Nodes

11.9.1 Shallow Copy

<!-- Category: instruction -->
<xsl:copy
  select? = expression
  copy-namespaces? = "yes" | "no"
  inherit-namespaces? = "yes" | "no"
  use-attribute-sets? = eqnames
  type? = eqname
  validation? = "strict" | "lax" | "preserve" | "strip"
  on-empty? = expression >
  <!-- Content: sequence-constructor -->
</xsl:copy>

The xsl:copy instruction provides a way of copying a selected item. The selected item is the item selected by evaluating the expression in the select attribute if present, or the context item otherwise. If the selected item is a node, evaluating the xsl:copy instruction constructs a copy of the selected node, and the result of the xsl:copy instruction is this newly constructed node. By default, the namespace nodes of the context node are automatically copied as well, but the attributes and children of the node are not automatically copied.

When the selected item is an atomic value or function item, the xsl:copy instruction returns this value. The sequence constructor, if present, is not evaluated, and must not generate any type errors.

When the selected item is an attribute node, text node, comment node, processing instruction node, or namespace node, the xsl:copy instruction returns a new node that is a copy of the context node. The new node will have the same node kind, name, and string value as the context node. In the case of an attribute node, it will also have the same values for the is-id and is-idrefs properties. The sequence constructor, if present, is not evaluated, and must not generate any type errors..

When the selected item is a document node or element node, the xsl:copy instruction returns a new node that has the same node kind and name as the selected node. The content of the new node is formed by evaluating the sequence constructor contained in the xsl:copy instruction. If the select attribute is present then the sequence constructor is evaluated with the selected item as the singleton focus; otherwise it is evaluated using the context of the xsl:copy instruction unchanged. The sequence obtained by evaluating this sequence constructor is used (after prepending any attribute nodes or namespace nodes as described in the following paragraphs) to construct the content of the document or element node, as described in 5.7.1 Constructing Complex Content.

If the select expression returns an empty sequence, the xsl:copy instruction returns an empty sequence, and the contained sequence constructor is not evaluated.

[ERR XTTE3180] It is a type error if the result of evaluating the select expression is a sequence of more than one item.

The xsl:copy instruction has an optional use-attribute-sets attribute, whose value is a whitespace-separated list of QNames that identify xsl:attribute-set declarations. This attribute is used only when copying element nodes. This list is expanded as described in 10.2 Named Attribute Sets to produce a sequence of attribute nodes. This sequence is prepended to the sequence produced as a result of evaluating the sequence constructor.

The xsl:copy instruction has an optional copy-namespaces attribute, with the value yes or no. The default value is yes. The attribute is used only when copying element nodes. If the value is set to yes, or is omitted, then all the namespace nodes of the source element are copied as namespace nodes for the result element. These copied namespace nodes are prepended to the sequence produced as a result of evaluating the sequence constructor (it is immaterial whether they come before or after any attribute nodes produced by expanding the use-attribute-sets attribute). If the value is set to no, then the namespace nodes are not copied. However, namespace nodes will still be added to the result element as required by the namespace fixup process: see 5.7.3 Namespace Fixup.

The xsl:copy instruction has an optional inherit-namespaces attribute, with the value yes or no. The default value is yes. The attribute is used only when copying element nodes. If the value is set to yes, or is omitted, then the namespace nodes created for the newly constructed element (whether these were copied from those of the source node, or generated as a result of namespace fixup) are copied to the children and descendants of the newly constructed element, as described in 5.7.1 Constructing Complex Content. If the value is set to no, then these namespace nodes are not automatically copied to the children. This may result in namespace undeclarations (such as xmlns="" or, in the case of XML Namespaces 1.1, xmlns:p="") appearing on the child elements when a final result tree is serialized.

[ERR XTTE0950] It is a type error to use the xsl:copy or xsl:copy-of instruction to copy a node that has namespace-sensitive content if the copy-namespaces attribute has the value no and its explicit or implicit validation attribute has the value preserve. It is also a type error if either of these instructions (with validation="preserve") is used to copy an attribute having namespace-sensitive content, unless the parent element is also copied. A node has namespace-sensitive content if its typed value contains an item of type xs:QName or xs:NOTATION or a type derived therefrom. The reason this is an error is because the validity of the content depends on the namespace context being preserved.

Note:

When attribute nodes are copied, whether with xsl:copy or with xsl:copy-of, the processor does not automatically copy any associated namespace information. The namespace used in the attribute name itself will be declared by virtue of the namespace fixup process (see 5.7.3 Namespace Fixup) when the attribute is added to an element in the result tree, but if namespace prefixes are used in the content of the attribute (for example, if the value of the attribute is an XPath expression) then it is the responsibility of the stylesheet author to ensure that suitable namespace nodes are added to the result tree. This can be achieved by copying the namespace nodes using xsl:copy, or by generating them using xsl:namespace.

The optional attributes type and validation may be used on the xsl:copy instruction to validate the contents of an element, attribute or document node against a type definition, element declaration, or attribute declaration in a schema, and thus to determine the type annotation that the new copy of an element or attribute node will carry. These attributes are ignored when copying an item that is not an element, attribute or document node. When the node being copied is an element or document node, these attributes also affect the type annotation carried by any elements and attributes that have the copied element or document node as an ancestor. These two attributes are both optional, and if one is specified then the other must be omitted. The permitted values of these attributes and their semantics are described in 24.2 Validation.

Note:

The final type annotation of the node in the result tree also depends on the type and validation attributes of the instructions used to create the ancestors of the node.

The base URI of a node is copied, except in the case of an element node having an xml:base attribute, in which case the base URI of the new node is taken as the value of the xml:base attribute, resolved if it is relative against the base URI of the xsl:copy instruction. If the copied node is subsequently attached as a child to a new element or document node, the final copy of the node inherits its base URI from its parent node, unless this is overridden using an xml:base attribute.

When an xml:id attribute is copied, using either the xsl:copy or xsl:copy-of instruction, it is implementation-defined whether the value of the attribute is subjected to attribute value normalization (that is, effectively applying the normalize-spaceFO30 function).

Note:

In most cases the value will already have been subjected to attribute value normalization on the source tree, but if this processing has not been performed on the source tree, it is not an error for it to be performed on the result tree.

11.9.1.1 Conditional Copying of Elements

If an xsl:copy instruction has an on-empty attribute, and the context node is an element or document node, and the content of the copied element or document node contains nothing other than namespace nodes and zero-length text nodes, then instead of returning the constructed element or document node, the instruction returns the result of evaluating the expression in the on-empty attribute.

In this situation (when the copied document or element node is not returned because it is empty), the validation and type attributes are ignored; no validation of the content takes place.

11.9.2 Deep Copy

<!-- Category: instruction -->
<xsl:copy-of
  select = expression
  copy-namespaces? = "yes" | "no"
  type? = eqname
  validation? = "strict" | "lax" | "preserve" | "strip" />

The xsl:copy-of instruction can be used to construct a copy of a sequence of nodes, atomic values, and/or function items with each new node containing copies of all the children, attributes, and (by default) namespaces of the original node, recursively. The result of evaluating the instruction is a sequence of items corresponding one-to-one with the supplied sequence, and retaining its order.

The required select attribute contains an expression, whose value may be any sequence of nodes, atomic values, and/or function items. The items in this sequence are processed as follows:

  • If the item is an element node, a new element is constructed and appended to the result sequence. The new element will have the same expanded QName as the original, and it will have deep copies of the attribute nodes and children of the element node.

    The new element will also have namespace nodes copied from the original element node, unless they are excluded by specifying copy-namespaces="no". If this attribute is omitted, or takes the value yes, then all the namespace nodes of the original element are copied to the new element. If it takes the value no, then none of the namespace nodes are copied: however, namespace nodes will still be created in the result tree as required by the namespace fixup process: see 5.7.3 Namespace Fixup. This attribute affects all elements copied by this instruction: both elements selected directly by the select expression, and elements that are descendants of nodes selected by the select expression.

    The new element will have the same values of the is-id, is-idrefs, and nilled properties as the original element.

  • If the item is a document node, the instruction adds a new document node to the result sequence; the children of this document node will be one-to-one copies of the children of the original document node (each copied according to the rules for its own node kind).

  • If the item is an attribute or namespace node, or a text node, a comment, or a processing instruction, the same rules apply as with xsl:copy (see 11.9.1 Shallow Copy).

  • If the item is an atomic value or a function item, the value is appended to the result sequence, as with xsl:sequence.

The optional attributes type and validation may be used on the xsl:copy-of instruction to validate the contents of an element, attribute or document node against a type definition, element declaration, or attribute declaration in a schema and thus to determine the type annotation that the new copy of an element or attribute node will carry. These attributes are applied individually to each element, attribute, and document node that is selected by the expression in the select attribute. These attributes are ignored when copying an item that is not an element, attribute or document node.

The specified type and validation apply directly only to elements, attributes and document nodes created as copies of nodes actually selected by the select expression, they do not apply to nodes that are implicitly copied because they have selected nodes as an ancestor. However, these attributes do indirectly affect the type annotation carried by such implicitly copied nodes, as a consequence of the validation process.

These two attributes are both optional, and if one is specified then the other must be omitted. The permitted values of these attributes and their semantics are described in 24.2 Validation.

Errors may occur when copying namespace-sensitive elements or attributes using validation="preserve". [see ERR XTTE0950].

The base URI of a node is copied, except in the case of an element node having an xml:base attribute, in which case the base URI of the new node is taken as the value of the xml:base attribute, resolved if it is relative against the base URI of the xsl:copy-of instruction. If the copied node is subsequently attached as a child to a new element or document node, the final copy of the node inherits its base URI from its parent node, unless this is overridden using an xml:base attribute.

11.10 Constructing Sequences

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

The xsl:sequence instruction may be used within a sequence constructor to construct a sequence of nodes, atomic values, and/or function items. This sequence is returned as the result of the instruction. Unlike most other instructions, xsl:sequence can return a sequence containing existing nodes, rather than constructing new nodes. When xsl:sequence is used to select atomic values or function items, the effect is very similar to the xsl:copy-of instruction.

The items comprising the result sequence are evaluated either using the select attribute, or using the contained sequence constructor. These are mutually exclusive; if the instruction has a select attribute, then it must have no children other than xsl:fallback instructions. If there is no select attribute and no contained sequence constructor, the result is an empty sequence.

Any contained xsl:fallback instructions are ignored by an XSLT 2.0 or 3.0 processor, but can be used to define fallback behavior for an XSLT 1.0 processor running in forwards compatibility mode.

Example: Constructing a Sequence of Integers

For example, the following code:

<xsl:variable name="values" as="xs:integer*">
    <xsl:sequence select="(1,2,3,4)"/>
    <xsl:sequence select="(8,9,10)"/>
</xsl:variable>
<xsl:value-of select="sum($values)"/>

produces the output: 37

 

Example: Using xsl:for-each to Construct a Sequence

The following code constructs a sequence containing the value of the @price attribute for selected elements (which we assume to be typed as xs:decimal), or a computed price for those elements that have no @price attribute. It then returns the average price:

<xsl:variable name="prices" as="xs:decimal*">
  <xsl:for-each select="//product">
    <xsl:choose>
      <xsl:when test="@price">
        <xsl:sequence select="@price"/>
      </xsl:when>
      <xsl:otherwise>
        <xsl:sequence select="@cost * 1.5"/>
      </xsl:otherwise>
    </xsl:choose>
  </xsl:for-each>
</xsl:variable>
<xsl:value-of select="avg($prices)"/>

Note that the existing @price attributes could equally have been added to the $prices sequence using xsl:copy-of or xsl:value-of. However, xsl:copy-of would create a copy of the attribute node, which is not needed in this situation, while xsl:value-of would create a new text node, which then has to be converted to an xs:decimal. Using xsl:sequence, which in this case atomizes the existing attribute node and adds an xs:decimal atomic value to the result sequence, is a more direct way of achieving the same result.

This example could alternatively be solved at the XPath level:

<xsl:value-of select="avg(//product/(+@price, @cost*1.5)[1])"/>

The apparently redundant + operator is there to atomize the attribute value: the expression on the right hand side of the / operator must not return a sequence containing both nodes and non-nodes (atomic values or function items).

Note:

The main use case for allowing xsl:sequence to contain a sequence constructor is to allow the instructions within an xsl:fork element to be divided into groups.

It can also be used to limit the scope of local variables or of standard attributes such as [xsl:]default-collation.

12 Numbering

<!-- Category: instruction -->
<xsl:number
  value? = expression
  select? = expression
  level? = "single" | "multiple" | "any"
  count? = pattern
  from? = pattern
  format? = { string }
  lang? = { language }
  letter-value? = { "alphabetic" | "traditional" }
  ordinal? = { string }
  start-at? = { integer }
  grouping-separator? = { char }
  grouping-size? = { integer } />

The xsl:number instruction is used to create a formatted number. The result of the instruction is a newly constructed text node containing the formatted number as its string value.

[Definition: The xsl:number instruction performs two tasks: firstly, determining a place marker (this is a sequence of integers, to allow for hierarchic numbering schemes such as 1.12.2 or 3(c)ii), and secondly, formatting the place marker for output as a text node in the result sequence.] The place marker to be formatted can either be supplied directly, in the value attribute, or it can be computed based on the position of a selected node within the tree that contains it.

[ERR XTSE0975] It is a static error if the value attribute of xsl:number is present unless the select, level, count, and from attributes are all absent.

Note:

The facilities described in this section are specifically designed to enable the calculation and formatting of section numbers, paragraph numbers, and the like. For formatting of other numeric quantities, the format-numberFO30 function may be more suitable: see Section 4.7.2 fn:format-number FO30.

Furthermore, formatting of integers where there is no requirement to calculate the position of a node in the document can now be accomplished using the format-numberFO30 function, which borrows many concepts from the xsl:number specification.

12.1 Formatting a Supplied Number

The place marker to be formatted may be specified by an expression. The value attribute contains the expression. The value of this expression is atomized using the procedure defined in [XPath 3.0], and each value $V in the atomized sequence is then converted to the integer value returned by the XPath expression xs:integer(round(number($V))). If the start-at attribute is present, then its effective value is converted to an integer and decremented by one, and the resulting value is added to each integer in the sequence. The resulting sequence of integers is used as the place marker to be formatted.

If the instruction is processed with XSLT 1.0 behavior, then:

  • all items in the atomized sequence after the first are discarded;

  • If the atomized sequence is empty, it is replaced by a sequence containing the xs:double value NaN as its only item;

  • If any value in the sequence cannot be converted to an integer (this includes the case where the sequence contains a NaN value) then the string NaN is inserted into the formatted result string in its proper position. The error described in the following paragraph does not apply in this case.

[ERR XTDE0980] It is a non-recoverable dynamic error if any undiscarded item in the atomized sequence supplied as the value of the value attribute of xsl:number cannot be converted to an integer, or if the resulting integer is less than 0 (zero).

Note:

The value zero does not arise when numbering nodes in a source document, but it can arise in other numbering sequences. It is permitted specifically because the rules of the xsl:number instruction are also invoked by functions such as format-timeFO30: the minutes and seconds component of a time value can legitimately be zero.

The resulting sequence is formatted as a string using the effective values of the attributes specified in 12.3 Number to String Conversion Attributes; each of these attributes is interpreted as an attribute value template. After conversion, the xsl:number element constructs a new text node containing the resulting string, and returns this node.

Example: Numbering a Sorted List

The following example numbers a sorted list:

<xsl:template match="items">
  <xsl:for-each select="item">
    <xsl:sort select="."/>
    <p>
      <xsl:number value="position()" format="1. "/>
      <xsl:value-of select="."/>
    </p>
  </xsl:for-each>
</xsl:template>

12.2 Numbering based on Position in a Document

If no value attribute is specified, then the xsl:number instruction returns a new text node containing a formatted place marker that is based on the position of a selected node within its containing document. If the select attribute is present, then the expression contained in the select attribute is evaluated to determine the selected node. If the select attribute is omitted, then the selected node is the context node.

[ERR XTTE0990] It is a type error if the xsl:number instruction is evaluated, with no value or select attribute, when the context item is not a node.

[ERR XTTE1000] It is a type error if the result of evaluating the select attribute of the xsl:number instruction is anything other than a single node.

[ERR XTDE1001] It is a dynamic error if the effective value of the start-at attribute of the xsl:number instruction is not in the lexical space of xs:integer. The error may be signaled statically if it can be detected statically.

The following attributes control how the selected node is to be numbered:

  • The level attribute specifies rules for selecting the nodes that are taken into account in allocating a number; it has the values single, multiple or any. The default is single.

  • The count attribute is a pattern that specifies which nodes are to be counted at those levels. If count attribute is not specified, then it defaults to the pattern that matches any node with the same node kind as the selected node and, if the selected node has an expanded QName, with the same expanded QName as the selected node.

  • The from attribute is a pattern that specifies where counting starts.

In addition, the attributes specified in 12.3 Number to String Conversion Attributes are used for number to string conversion, as in the case when the value attribute is specified.

The xsl:number element first constructs a sequence of positive integers using the level, count and from attributes. Where level is single or any, this sequence will either be empty or contain a single number; where level is multiple, the sequence may be of any length. The sequence is constructed as follows:

Let matches-count($node) be a function that returns true if and only if the given node $node matches the pattern given in the count attribute, or the implied pattern (according to the rules given above) if the count attribute is omitted.

Let matches-from($node) be a function that returns true if and only if the given node $node matches the pattern given in the from attribute, or if $node is the root node of a tree. If the from attribute is omitted, then the function returns true if and only if $node is the root node of a tree.

Let $S be the selected node.

When level="single":

  • Let $A be the node sequence selected by the following expression:

       $S/ancestor-or-self::node()[matches-count(.)][1]

    (this selects the innermost ancestor-or-self node that matches the count pattern)

  • Let $F be the node sequence selected by the expression

       $S/ancestor-or-self::node()[matches-from(.)][1]

    (this selects the innermost ancestor-or-self node that matches the from pattern):

  • Let $AF be the value of:

       $A[ancestor-or-self::node()[. is $F]]

    (this selects $A if it is in the subtree rooted at $F, or the empty sequence otherwise)

  • If $AF is empty, return the empty sequence, ()

  • Otherwise return the value of:

       1 + count($AF/preceding-sibling::node()[matches-count(.)])

    (the number of preceding siblings of the counted node that match the count pattern, plus one).

When level="multiple":

  • Let $A be the node sequence selected by the expression

       $S/ancestor-or-self::node()[matches-count(.)]

    (the set of ancestor-or-self nodes that match the count pattern)

  • Let $F be the node sequence selected by the expression

       $S/ancestor-or-self::node()[matches-from(.)][1]

    (the innermost ancestor-or-self node that matches the from pattern)

  • Let $AF be the value of

       $A[ancestor-or-self::node()[. is $F]]

    (the nodes selected in the first step that are in the subtree rooted at the node selected in the second step)

  • Return the result of the expression

       for $af in $AF return 1+count($af/preceding-sibling::node()[matches-count(.)])

    (a sequence of integers containing, for each of these nodes, one plus the number of preceding siblings that match the count pattern)

When level="any":

  • Let $A be the node sequence selected by the expression

       $S/(preceding::node()|ancestor-or-self::node())[matches-count(.)]

    (the set of nodes consisting of the selected node together with all nodes, other than attributes and namespaces, that precede the selected node in document order, provided that they match the count pattern)

  • Let $F be the node sequence selected by the expression

       $S/(preceding::node()|ancestor::node())[matches-from(.)][last()]

    (the last node in document order that matches the from pattern and that precedes the selected node, using the same definition)

  • Let $AF be the node sequence $A[. is $F or . >> $F].

    (the nodes selected in the first step, excluding those that precede the node selected in the second step)

  • If $AF is empty, return the empty sequence, ()

  • Otherwise return the value of the expression count($AF)

The resulting sequence of numbers is referred to as the place marker).

If the start-at attribute is present, then the effective value of the attribute is converted to an integer and decremented by one, and the resulting value is added to each number in the place marker.

The sequence of numbers (the is then converted into a string using the effective values of the attributes specified in 12.3 Number to String Conversion Attributes; each of these attributes is interpreted as an attribute value template. After conversion, the resulting string is used to create a text node, which forms the result of the xsl:number instruction.

Example: Numbering the Items in an Ordered List

The following will number the items in an ordered list:

<xsl:template match="ol/item">
  <fo:block>
    <xsl:number/>
    <xsl:text>. </xsl:text>
    <xsl:apply-templates/>
  </fo:block>
</xsl:template>

 

Example: Multi-Level Numbering

The following two rules will number title elements. This is intended for a document that contains a sequence of chapters followed by a sequence of appendices, where both chapters and appendices contain sections, which in turn contain subsections. Chapters are numbered 1, 2, 3; appendices are numbered A, B, C; sections in chapters are numbered 1.1, 1.2, 1.3; sections in appendices are numbered A.1, A.2, A.3. Subsections within a chapter are numbered 1.1.1, 1.1.2, 1.1.3; subsections within an appendix are numbered A.1.1, A.1.2, A.1.3.

<xsl:template match="title">
  <fo:block>
     <xsl:number level="multiple"
                 count="chapter|section|subsection"
                 format="1.1 "/>
     <xsl:apply-templates/>
  </fo:block>
</xsl:template>

<xsl:template match="appendix//title" priority="1">
  <fo:block>
     <xsl:number level="multiple"
                 count="appendix|section|subsection"
                 format="A.1 "/>
     <xsl:apply-templates/>
  </fo:block>
</xsl:template>

 

Example: Numbering Notes within a Chapter

This example numbers notes sequentially within a chapter, starting from the number 100: :

<xsl:template match="note">
  <fo:block>
     <xsl:number level="any" from="chapter" format="(1) " start-at="100"/>
     <xsl:apply-templates/>
  </fo:block>
</xsl:template>

12.3 Number to String Conversion Attributes

Issue 10 (refactor-format-integer):

The functionality described here has been encapsulated in a new function, format-integerFO30. The specification can be simplified by referring to the specification of that function.

The following attributes are used to control conversion of a sequence of numbers into a string. The numbers are integers greater than or equal to 0 (zero). The attributes are all optional.

The main attribute is format. The default value for the format attribute is 1. The format attribute is split into a sequence of tokens where each token is a maximal sequence of alphanumeric characters or a maximal sequence of non-alphanumeric characters. Alphanumeric means any character that has a Unicode category of Nd, Nl, No, Lu, Ll, Lt, Lm or Lo. The alphanumeric tokens (format tokens) indicate the format to be used for each number in the sequence; in most cases the format token is the same as the required representation of the number 1 (one).

Each non-alphanumeric token is either a prefix, a separator, or a suffix. If there is a non-alphanumeric token but no format token, then the single non-alphanumeric token is used as both the prefix and the suffix. The prefix, if it exists, is the non-alphanumeric token that precedes the first format token: the prefix always appears exactly once in the constructed string, at the start. The suffix, if it exists, is the non-alphanumeric token that follows the last format token: the suffix always appears exactly once in the constructed string, at the end. All other non-alphanumeric tokens (those that occur between two format tokens) are separator tokens and are used to separate numbers in the sequence.

The nth format token is used to format the nth number in the sequence. If there are more numbers than format tokens, then the last format token is used to format remaining numbers. If there are no format tokens, then a format token of 1 is used to format all numbers. Each number after the first is separated from the preceding number by the separator token preceding the format token used to format that number, or, if that is the first format token, then by . (dot).

Example: Formatting a List of Numbers

Given the sequence of numbers 5, 13, 7 and the format token A-001(i), the output will be the string E-013(vii)

Format tokens are interpreted as follows:

  • Any token where the last character has a decimal digit value of 1 (as specified in the Unicode character property database), and the Unicode value of preceding characters is one less than the Unicode value of the last character generates a decimal representation of the number where each number is at least as long as the format token. The digits used in the decimal representation are the set of digits containing the digit character used in the format token. Thus, a format token 1 generates the sequence 0 1 2 ... 10 11 12 ..., and a format token 01 generates the sequence 00 01 02 ... 09 10 11 12 ... 99 100 101. A format token of &#x661; (Arabic-Indic digit one) generates the sequence ١ then ٢ then ٣ ...

  • A format token A generates the sequence A B C ... Z AA AB AC....

  • A format token a generates the sequence a b c ... z aa ab ac....

  • A format token i generates the sequence i ii iii iv v vi vii viii ix x ....

  • A format token I generates the sequence I II III IV V VI VII VIII IX X ....

  • A format token w generates numbers written as lower-case words, for example in English, one two three four ...

  • A format token W generates numbers written as upper-case words, for example in English, ONE TWO THREE FOUR ...

  • A format token Ww generates numbers written as title-case words, for example in English, One Two Three Four ...

  • Any other format token indicates a numbering sequence in which that token represents the number 1 (one) (but see the note below). It is implementation-defined which numbering sequences, additional to those listed above, are supported. If an implementation does not support a numbering sequence represented by the given token, it must use a format token of 1.

    Note:

    In some traditional numbering sequences additional signs are added to denote that the letters should be interpreted as numbers; these are not included in the format token. An example, see also the example below, is classical Greek where a dexia keraia and sometimes an aristeri keraia is added.

For all format tokens other than the first kind above (one that consists of decimal digits), there may be implementation-defined lower and upper bounds on the range of numbers that can be formatted using this format token; indeed, for some numbering sequences there may be intrinsic limits. For example, the formatting token &#x2460; (circled digit one) has a range of 1 to 20 imposed by the Unicode character repertoire. For the numbering sequences described above any upper bound imposed by the implementation must not be less than 1000 (one thousand) and any lower bound must not be greater than 1. Numbers that fall outside this range must be formatted using the format token 1. The numbering sequence associated with the format token 1 has a lower bound of 0 (zero).

The above expansions of numbering sequences for format tokens such as a and i are indicative but not prescriptive. There are various conventions in use for how alphabetic sequences continue when the alphabet is exhausted, and differing conventions for how roman numerals are written (for example, IV versus IIII as the representation of the number 4). Sometimes alphabetic sequences are used that omit letters such as i and o. This specification does not prescribe the detail of any sequence other than those sequences consisting entirely of decimal digits.

Many numbering sequences are language-sensitive. This applies especially to the sequence selected by the tokens w, W and Ww. It also applies to other sequences, for example different languages using the Cyrillic alphabet use different sequences of characters, each starting with the letter #x410 (Cyrillic capital letter A). In such cases, the lang attribute specifies which language's conventions are to be used; it has the same range of values as xml:lang (see [XML 1.0]). If no lang value is specified, the language that is used is implementation-defined. The set of languages for which numbering is supported is implementation-defined. If a language is requested that is not supported, the processor uses the language that it would use if the lang attribute were omitted.

If the optional ordinal attribute is present, and if its value is not a zero-length string, this indicates a request to output ordinal numbers rather than cardinal numbers. For example, in English, the value ordinal="yes" when used with the format token 1 outputs the sequence 1st 2nd 3rd 4th ..., and when used with the format token w outputs the sequence first second third fourth .... In some languages, ordinal numbers vary depending on the grammatical context, for example they may have different genders and may decline with the noun that they qualify. In such cases the value of the ordinal attribute may be used to indicate the variation of the ordinal number required. The way in which the variation is indicated will depend on the conventions of the language. For inflected languages that vary the ending of the word, the preferred approach is to indicate the required ending, preceded by a hyphen: for example in German, appropriate values are -e, -er, -es, -en. It is implementation-defined what combinations of values of the format token, the language, and the ordinal attribute are supported. If ordinal numbering is not supported for the combination of the format token, the language, and the actual value of the ordinal attribute, the request is ignored and cardinal numbers are generated instead.

Example: Ordinal Numbering in Italian

The specification format="1" ordinal="-º" lang="it", if supported, should produce the sequence:

1º 2º 3º 4º ...

The specification format="Ww" ordinal="-o" lang="it", if supported, should produce the sequence:

Primo Secondo Terzo Quarto Quinto ...

The letter-value attribute disambiguates between numbering sequences that use letters. In many languages there are two commonly used numbering sequences that use letters. One numbering sequence assigns numeric values to letters in alphabetic sequence, and the other assigns numeric values to each letter in some other manner traditional in that language. In English, these would correspond to the numbering sequences specified by the format tokens a and i. In some languages, the first member of each sequence is the same, and so the format token alone would be ambiguous. A value of alphabetic specifies the alphabetic sequence; a value of traditional specifies the other sequence. If the letter-value attribute is not specified, then it is implementation-dependent how any ambiguity is resolved.

Note:

Implementations may use extension attributes on xsl:number to provide additional control over the way in which numbers are formatted.

The grouping-separator attribute gives the separator used as a grouping (for example, thousands) separator in decimal numbering sequences, and the optional grouping-size specifies the size (normally 3) of the grouping. For example, grouping-separator="," and grouping-size="3" would produce numbers of the form 1,000,000 while grouping-separator="." and grouping-size="2" would produce numbers of the form 1.00.00.00. If only one of the grouping-separator and grouping-size attributes is specified, then it is ignored.

Example: Format Tokens and the Resulting Sequences

These examples use non-Latin characters which might not display correctly in all browsers, depending on the system configuration.

Description Format Token Sequence
French cardinal words format="Ww" lang="fr" Un, Deux, Trois, Quatre
German ordinal words format="w" ordinal="-e" lang="de" erste, zweite, dritte, vierte
Katakana numbering format="&#x30A2;" ア, イ, ウ, エ, オ, カ, キ, ク, ケ, コ, サ, シ, ス, セ, ソ, タ, チ, ツ, テ, ト, ナ, ニ, ヌ, ネ, ノ, ハ, ヒ, フ, ヘ, ホ, マ, ミ, ム, メ, モ, ヤ, ユ, ヨ, ラ, リ, ル, レ, ロ, ワ, ヰ, ヱ, ヲ, ン
Katakana numbering in iroha order format="&#x30A4;" イ, ロ, ハ, ニ, ホ, ヘ, ト, チ, リ, ヌ, ル, ヲ, ワ, カ, ヨ, タ, レ, ソ, ツ, ネ, ナ, ラ, ム, ウ, ヰ, ノ, オ, ク, ヤ, マ, ケ, フ, コ, エ, テ, ア, サ, キ, ユ, メ, ミ, シ, ヱ, ヒ, モ, セ, ス
Thai numbering format="&#x0E51;" ๑, ๒, ๓, ๔, ๕, ๖, ๗, ๘, ๙, ๑๐, ๑๑, ๑๒, ๑๓, ๑๔, ๑๕, ๑๖, ๑๗, ๑๘, ๑๙, ๒๐
Traditional Hebrew numbering format="&#x05D0;" letter-value="traditional" א, ב, ג, ד, ה, ו, ז, ח, ט, י, יא, יב, יג, יד, טו, טז, יז, יח, יט, כ
Traditional Georgian numbering format="&#x10D0;" letter-value="traditional" ა, ბ, გ, დ, ე, ვ, ზ, ჱ, თ, ი, ია, იბ, იგ, იდ, იე, ივ, იზ, იჱ, ით, კ
Classical Greek numbering (see note) format="&#x03B1;" letter-value="traditional" αʹ, βʹ, γʹ, δʹ, εʹ, ϛʹ, ζʹ, ηʹ, θʹ, ιʹ, ιαʹ, ιβʹ, ιγʹ, ιδʹ, ιεʹ, ιϛʹ, ιζʹ, ιηʹ, ιθʹ, κʹ
Old Slavic numbering format="&#x0430;" letter-value="traditional" А, В, Г, Д, Е, Ѕ, З, И, Ѳ, Ӏ, АӀ, ВӀ, ГӀ, ДӀ, ЕӀ, ЅӀ, ЗӀ, ИӀ, ѲӀ, К

Note that Classical Greek is an example where the format token is not the same as the representation of the number 1.

13 Sorting

[Definition: A sort key specification is a sequence of one or more adjacent xsl:sort elements which together define rules for sorting the items in an input sequence to form a sorted sequence.]

[Definition: Within a sort key specification, each xsl:sort element defines one sort key component.] The first xsl:sort element specifies the primary component of the sort key specification, the second xsl:sort element specifies the secondary component of the sort key specification, and so on.

A sort key specification may occur immediately within an xsl:apply-templates, xsl:for-each, xsl:perform-sort, or xsl:for-each-group element.

Note:

When used within xsl:for-each, xsl:for-each-group, or xsl:perform-sort, xsl:sort elements must occur before any other children.

13.1 The xsl:sort Element

<xsl:sort
  select? = expression
  lang? = { language }
  order? = { "ascending" | "descending" }
  collation? = { uri }
  stable? = { "yes" | "no" }
  case-order? = { "upper-first" | "lower-first" }
  data-type? = { "text" | "number" | eqname } >
  <!-- Content: sequence-constructor -->
</xsl:sort>

The xsl:sort element defines a sort key component. A sort key component specifies how a sort key value is to be computed for each item in the sequence being sorted, and also how two sort key values are to be compared.

The value of a sort key component is determined either by its select attribute or by the contained sequence constructor. If neither is present, the default is select=".", which has the effect of sorting on the actual value of the item if it is an atomic value, or on the typed-value of the item if it is a node. If a select attribute is present, its value must be an XPath expression.

[ERR XTSE1015] It is a static error if an xsl:sort element with a select attribute has non-empty content.

Those attributes of the xsl:sort elements whose values are attribute value templates are evaluated using the same focus as is used to evaluate the select attribute of the containing instruction (specifically, xsl:apply-templates, xsl:for-each, xsl:for-each-group, or xsl:perform-sort).

The stable attribute is permitted only on the first xsl:sort element within a sort key specification

[ERR XTSE1017] It is a static error if an xsl:sort element other than the first in a sequence of sibling xsl:sort elements has a stable attribute.

[Definition: A sort key specification is said to be stable if its first xsl:sort element has no stable attribute, or has a stable attribute whose effective value is yes.]

13.1.1 The Sorting Process

[Definition: The sequence to be sorted is referred to as the initial sequence.]

[Definition: The sequence after sorting as defined by the xsl:sort elements is referred to as the sorted sequence.]

[Definition:  For each item in the initial sequence, a value is computed for each sort key component within the sort key specification. The value computed for an item by using the Nth sort key component is referred to as the Nth sort key value of that item.]

The items in the initial sequence are ordered into a sorted sequence by comparing their sort key values. The relative position of two items A and B in the sorted sequence is determined as follows. The first sort key value of A is compared with the first sort key value of B, according to the rules of the first sort key component. If, under these rules, A is less than B, then A will precede B in the sorted sequence, unless the order attribute of this sort key component specifies descending, in which case B will precede A in the sorted sequence. If, however, the relevant sort key values compare equal, then the second sort key value of A is compared with the second sort key value of B, according to the rules of the second sort key component. This continues until two sort key values are found that compare unequal. If all the sort key values compare equal, and the sort key specification is stable, then A will precede B in the sorted sequence if and only if A preceded B in the initial sequence. If all the sort key values compare equal, and the sort key specification is not stable, then the relative order of A and B in the sorted sequence is implementation-dependent.

Note:

If two items have equal sort key values, and the sort is stable, then their order in the sorted sequence will be the same as their order in the initial sequence, regardless of whether order="descending" was specified on any or all of the sort key components.

The Nth sort key value is computed by evaluating either the select attribute or the contained sequence constructor of the Nth xsl:sort element, or the expression . (dot) if neither is present. This evaluation is done with the focus set as follows:

Note:

As in any other XPath expression, the current function may be used within the select expression of xsl:sort to refer to the item that is the context item for the expression as a whole; that is, the item whose sort key value is being computed.

The sort key values are atomized, and are then compared. The way they are compared depends on their datatype, as described in the next section.

13.1.2 Comparing Sort Key Values

It is possible to force the system to compare sort key values using the rules for a particular datatype by including a cast as part of the sort key component. For example, <xsl:sort select="xs:date(@dob)"/> will force the attributes to be compared as dates. In the absence of such a cast, the sort key values are compared using the rules appropriate to their datatype. Any values of type xs:untypedAtomic are cast to xs:string.

For backwards compatibility with XSLT 1.0, the data-type attribute remains available. If this has the effective value text, the atomized sort key values are converted to strings before being compared. If it has the effective value number, the atomized sort key values are converted to doubles before being compared. The conversion is done by using the stringFO30 or numberFO30 function as appropriate. If the data-type attribute has any other effective value, then this value must be a EQName denoting an expanded QName with a non-absent namespace, and the effect of the attribute is implementation-defined.

[ERR XTTE1020] If any sort key value, after atomization and any type conversion required by the data-type attribute, is a sequence containing more than one item, then the effect depends on whether the xsl:sort element is processed with XSLT 1.0 behavior. With XSLT 1.0 behavior, the effective sort key value is the first item in the sequence. In other cases, this is a type error.

The set of sort key values (after any conversion) is first divided into two categories: empty values, and ordinary values. The empty sort key values represent those items where the sort key value is an empty sequence. These values are considered for sorting purposes to be equal to each other, but less than any other value. The remaining values are classified as ordinary values.

[ERR XTDE1030] It is a non-recoverable dynamic error if, for any sort key component, the set of sort key values evaluated for all the items in the initial sequence, after any type conversion requested, contains a pair of ordinary values for which the result of the XPath lt operator is an error.

Note:

The above error condition may occur if the values to be sorted are of a type that does not support ordering (for example, xs:QName) or if the sequence is heterogeneous (for example, if it contains both strings and numbers). The error can generally be prevented by invoking a cast or constructor function within the sort key component.

The error condition is subject to the usual caveat that a processor is not required to evaluate any expression solely in order to determine whether it raises an error. For example, if there are several sort key components, then a processor is not required to evaluate or compare minor sort key values unless the corresponding major sort key values are equal.

In general, comparison of two ordinary values is performed according to the rules of the XPath lt operator. To ensure a total ordering, the same implementation of the lt operator must be used for all the comparisons: the one that is chosen is the one appropriate to the most specific type to which all the values can be converted by subtype substitution and/or type promotion. For example, if the sequence contains both xs:decimal and xs:double values, then the values are compared using xs:double comparison, even when comparing two xs:decimal values. NaN values, for sorting purposes, are considered to be equal to each other, and less than any other numeric value. Special rules also apply to the xs:string and xs:anyURI types, and types derived by restriction therefrom, as described in the next section.

13.1.3 Sorting Using Collations

The rules given in this section apply when comparing values whose type is xs:string or a type derived by restriction from xs:string, or whose type is xs:anyURI or a type derived by restriction from xs:anyURI.

[Definition: Facilities in XSLT 3.0 and XPath 3.0 that require strings to be ordered rely on the concept of a named collation. A collation is a set of rules that determine whether two strings are equal, and if not, which of them is to be sorted before the other.] A collation is identified by a URI, but the manner in which this URI is associated with an actual rule or algorithm is implementation-defined.

The one collation URI that must be recognized by every implementation is http://www.w3.org/2005/xpath-functions/collation/codepoint, which provides the ability to compare strings based on the Unicode codepoint values of the characters in the string.

For more information about collations, see Section 5.3 Comparison of strings FO30 in [Functions and Operators]. Some specifications, for example [UNICODE TR10], use the term "collation" to describe rules that can be tailored or parameterized for various purposes. In this specification, a collation URI refers to a collation in which all such parameters have already been fixed. Therefore, if a collation URI is specified, other attributes such as case-order and lang are ignored.

Note:

The reason XSLT does not provide detailed mechanisms for defining collating sequences is that many implementations will re-use collating mechanisms available from the underlying implementation platform (for example, from the operating system or from the run-time library of a chosen programming language). These will inevitably differ from one XSLT implementation to another.

If the xsl:sort element has a collation attribute, then the strings are compared according to the rules for the named collation: that is, they are compared using the XPath function call compare($a, $b, $collation).

If the effective value of the collation attribute of xsl:sort is a relative URI, then it is resolved against the base URI of the xsl:sort element.

[ERR XTDE1035] It is a non-recoverable dynamic error if the collation attribute of xsl:sort (after resolving against the base URI) is not a URI that is recognized by the implementation as referring to a collation.

Note:

It is entirely for the implementation to determine whether it recognizes a particular collation URI. For example, if the implementation allows collation URIs to contain parameters in the query part of the URI, it is the implementation that determines whether a URI containing an unknown or invalid parameter is or is not a recognized collation URI. The fact that this error is described as non-recoverable thus does not prevent an implementation applying a fallback collation if it chooses to do so.

The lang and case-order attributes are ignored if a collation attribute is present. But in the absence of a collation attribute, these attributes provide input to an implementation-defined algorithm to locate a suitable collation:

  • The lang attribute indicates that a collation suitable for a particular natural language should be used. The effective value of the attribute must be a value that would be valid for the xml:lang attribute (see [XML 1.0]).

  • The case-order attribute indicates whether the desired collation should sort upper-case letters before lower-case or vice versa. The effective value of the attribute must be either lower-first (indicating that lower-case letters precede upper-case letters in the collating sequence) or upper-first (indicating that upper-case letters precede lower-case).

    When lower-first is requested, the returned collation should have the property that when two strings differ only in the case of one or more characters, then a string in which the first differing character is lower-case should precede a string in which the corresponding character is title-case, which should in turn precede a string in which the corresponding character is upper-case. When upper-first is requested, the returned collation should have the property that when two strings differ only in the case of one or more characters, then a string in which the first differing character is upper-case should precede a string in which the corresponding character is title-case, which should in turn precede a string in which the corresponding character is lower-case.

    So, for example, if lang="en", then A a B b are sorted with case-order="upper-first" and a A b B are sorted with case-order="lower-first".

    As a further example, if lower-first is requested, then a sorted sequence might be "MacAndrew, macintosh, macIntosh, Macintosh, MacIntosh, macintoshes, Macintoshes, McIntosh". If upper-first is requested, the same sequence would sort as "MacAndrew, MacIntosh, Macintosh, macIntosh, macintosh, MacIntoshes, macintoshes, McIntosh".

If none of the collation, lang, or case-order attributes is present, the collation is chosen in an implementation-defined way. It is not required that the default collation for sorting should be the same as the default collation used when evaluating XPath expressions, as described in 5.4.1 Initializing the Static Context and 3.8.1 The default-collation attribute.

Note:

It is usually appropriate, when sorting, to use a strong collation, that is, one that takes account of secondary differences (accents) and tertiary differences (case) between strings that are otherwise equal. A weak collation, which ignores such differences, may be more suitable when comparing strings for equality.

Useful background information on international sorting is provided in [UNICODE TR10]. The case-order attribute may be interpreted as described in section 6.6 of [UNICODE TR10].

13.2 Creating a Sorted Sequence

<!-- Category: instruction -->
<xsl:perform-sort
  select? = expression >
  <!-- Content: (xsl:sort+, sequence-constructor) -->
</xsl:perform-sort>

The xsl:perform-sort instruction is used to return a sorted sequence.

The initial sequence is obtained either by evaluating the select attribute or by evaluating the contained sequence constructor (but not both). If there is no select attribute and no sequence constructor then the initial sequence (and therefore, the sorted sequence) is an empty sequence.

[ERR XTSE1040] It is a static error if an xsl:perform-sort instruction with a select attribute has any content other than xsl:sort and xsl:fallback instructions.

The result of the xsl:perform-sort instruction is the result of sorting its initial sequence using its contained sort key specification.

Example: Sorting a Sequence of Atomic Values

The following stylesheet function sorts a sequence of atomic values using the value itself as the sort key.

<xsl:function name="local:sort" 
          as="xs:anyAtomicType*">
  <xsl:param name="in" as="xs:anyAtomicType*"/>
  <xsl:perform-sort select="$in">
    <xsl:sort select="."/>
  </xsl:perform-sort>
</xsl:function>

 

Example: Writing a Function to Perform a Sort

The following example defines a function that sorts books by price, and uses this function to output the five books that have the lowest prices:

<xsl:function name="bib:books-by-price" 
          as="schema-element(bib:book)*">
  <xsl:param name="in" as="schema-element(bib:book)*"/>
  <xsl:perform-sort select="$in">
    <xsl:sort select="xs:decimal(bib:price)"/>
  </xsl:perform-sort>
</xsl:function>
   ...
   <xsl:copy-of select="bib:books-by-price(//bib:book)
                             [position() = 1 to 5]"/>

 

13.3 Processing a Sequence in Sorted Order

When used within xsl:for-each or xsl:apply-templates, a sort key specification indicates that the sequence of items selected by that instruction is to be processed in sorted order, not in the order of the supplied sequence.

Example: Processing Elements in Sorted Order

For example, suppose an employee database has the form

<employees>
  <employee>
    <name>
      <given>James</given>
      <family>Clark</family>
    </name>
    ...
  </employee>
</employees>

Then a list of employees sorted by name could be generated using:

<xsl:template match="employees">
  <ul>
    <xsl:apply-templates select="employee">
      <xsl:sort select="name/family"/>
      <xsl:sort select="name/given"/>
    </xsl:apply-templates>
  </ul>
</xsl:template>

<xsl:template match="employee">
  <li>
    <xsl:value-of select="name/given"/>
    <xsl:text> </xsl:text>
    <xsl:value-of select="name/family"/>
  </li>
</xsl:template>

When used within xsl:for-each-group, a sort key specification indicates the order in which the groups are to be processed. For the effect of xsl:for-each-group, see 14 Grouping.

14 Grouping

The facilities described in this section are designed to allow items in a sequence to be grouped based on common values; for example it allows grouping of elements having the same value for a particular attribute, or elements with the same name, or elements with common values for any other expression. Since grouping identifies items with duplicate values, the same facilities also allow selection of the distinct values in a sequence of items, that is, the elimination of duplicates.

Note:

Simple elimination of duplicates can also be achieved using the function distinct-valuesFO30 in the core function library: see [Functions and Operators].

In addition these facilities allow grouping based on sequential position, for example selecting groups of adjacent para elements. The facilities also provide an easy way to do fixed-size grouping, for example identifying groups of three adjacent nodes, which is useful when arranging data in multiple columns.

For each group of items identified, it is possible to evaluate a sequence constructor for the group. Grouping is nestable to multiple levels so that groups of distinct items can be identified, then from among the distinct groups selected, further sub-grouping of distinct items in the current group can be done.

It is also possible for one item to participate in more than one group.

14.1 The xsl:for-each-group Element

<!-- Category: instruction -->
<xsl:for-each-group
  select = expression
  group-by? = expression
  group-adjacent? = expression
  group-starting-with? = pattern
  group-ending-with? = pattern
  bind-group? = eqname
  bind-grouping-key? = eqname
  composite? = "yes" | "no"
  collation? = { uri } >
  <!-- Content: (xsl:sort*, sequence-constructor) -->
</xsl:for-each-group>

This element is an instruction that may be used anywhere within a sequence constructor.

[Definition: The xsl:for-each-group instruction allocates the items in an input sequence into groups of items (that is, it establishes a collection of sequences) based either on common values of a grouping key, or on a pattern that the initial or final item in a group must match.] The sequence constructor that forms the content of the xsl:for-each-group instruction is evaluated once for each of these groups.

[Definition: The sequence of items to be grouped, which is referred to as the population, is determined by evaluating the XPath expression contained in the select attribute.]

[Definition: The population is treated as a sequence; the order of items in this sequence is referred to as population order ].

A group is never empty. If the population is empty, the number of groups will be zero.

The assignment of items to groups depends on the group-by, group-adjacent, group-starting-with, and group-ending-with attributes.

[ERR XTSE1080] These four attributes are mutually exclusive: it is a static error if none of these four attributes is present or if more than one of them is present.

[ERR XTSE1090] It is a static error to specify the collation attribute or the composite attribute if neither the group-by attribute nor group-adjacent attribute is specified.

[Definition: If either of the group-by or group-adjacent attributes is present, then for each item in the population a set of grouping keys is calculated, as follows: the expression contained in the group-by or group-adjacent attribute is evaluated; the result is atomized; and any xs:untypedAtomic values are cast to xs:string. If composite="yes" is specified, there is a single grouping key whose value is the resulting sequence; otherwise, there is a set of grouping keys, consisting of the distinct atomic values present in the result sequence. ]

When calculating grouping keys for an item in the population, the expression contained in the group-by or group-adjacent attribute is evaluated with that item as the context item, with its position in population order as the context position, and with the size of the population as the context size.

If the group-by attribute is present, and if the composite attribute is omitted or takes the value no, then an item in the population may have multiple grouping keys: that is, the group-by expression evaluates to a sequence, and each item in the sequence is treated as a separate grouping key. The item is included in as many groups as there are distinct grouping keys (which may be zero).

f the group-adjacent attribute is used, and if the composite attribute is omitted or takes the value no, then each item in the population must have exactly one grouping key value.

[ERR XTTE1100] It is a type error if the result of evaluating the group-adjacent expression is an empty sequence or a sequence containing more than one item, unless composite="yes" is specified.

Grouping keys are compared using the rules for the deep-equalFO30 function. This means that values of type xs:untypedAtomic will be cast to xs:string before the comparison, and that items that are not comparable using the eq operator are considered to be not equal, that is, they are allocated to different groups. It also means that the value NaN is considered equal to itself. If the values are strings, or untyped atomic values, then if there is a collation attribute the values are compared using the collation specified as the effective value of the collation attribute, resolved if relative against the base URI of the xsl:for-each-group element. If there is no collation attribute then the default collation is used.

[ERR XTDE1110] It is a non-recoverable dynamic error if the collation URI specified to xsl:for-each-group (after resolving against the base URI) is a collation that is not recognized by the implementation. (For notes, [see ERR XTDE1035].)

For more information on collations, see 13.1.3 Sorting Using Collations.

The way in which an xsl:for-each-group element is evaluated depends on which of the four group-defining attributes is present:

  • If the group-by attribute is present, the items in the population are examined, in population order. For each item J, the expression in the group-by attribute is evaluated to produce a sequence of zero or more grouping key values. If composite="yes" is specified, there will be a single grouping key, which will in general be a sequence of zero or more atomic values; otherwise, there will be zero or more grouping keys, each of which will be a single atomic value. For each one of these grouping keys, if there is already a group created to hold items having that grouping key value, J is appended to that group; otherwise a new group is created for items with that grouping key value, and J becomes its first member.

    An item in the population may thus be appended to zero, one, or many groups. An item will never be appended more than once to the same group; if two or more grouping keys for the same item are equal, then the duplicates are ignored. An item here means the item at a particular position within the population—if the population contains the same node at several different positions in the sequence then a group may indeed contain duplicate nodes.

    The number of groups will be the same as the number of distinct grouping key values present in the population.

    If the population contains values of different numeric types that differ from each other by small amounts, then the eq operator is not transitive, because of rounding effects occurring during type promotion. The effect of this is described in 14.5 Non-Transitivity.

  • If the group-adjacent attribute is present, the items in the population are examined, in population order. If an item has the same value for the grouping key as its preceding item within the population (in population order), then it is appended to the same group as its preceding item; otherwise a new group is created and the item becomes its first member.

  • If the group-starting-with attribute is present, then its value must be a pattern.

    The items in the population are examined in population order. If an item matches the pattern, or is the first item in the population, then a new group is created and the item becomes its first member. Otherwise, the item is appended to the same group as its preceding item within the population.

  • If the group-ending-with attribute is present, then its value must be a pattern.

    The items in the population are examined in population order. If an item is the first item in the population, or if the previous item in the population matches the pattern, then a new group is created and the item becomes its first member. Otherwise, the item is appended to the same group as its preceding item within the population.

In all cases the order of items within each group is predictable, and reflects the original population order, in that the items are processed in population order and each item is appended at the end of zero or more groups.

Note:

As always, a different algorithm may be used if it achieves the same effect.

[Definition: For each group, the item within the group that is first in population order is known as the initial item of the group.]

The sequence constructor contained in the xsl:for-each-group element is evaluated once for each of the groups, in processing order. The sequences that result are concatenated, in processing order, to form the result of the xsl:for-each-group element. Within the sequence constructor, the context item is the initial item of the relevant group, the context position is the position of this group in the processing order of the groups, and the context size is the number of groups, the current group is the group being processed, and the current grouping key is the grouping key for that group. If the xsl:for-each-group instruction uses the group-starting-with or group-ending-with attributes, then the current grouping key is the empty sequence. This has the effect that within the sequence constructor, a call on position() takes successive values 1, 2, ... last().

14.2 Accessing Information about the Current Group

Two pieces of information are available during the processing of each group (that is, while evaluating the sequence constructor contained in the xsl:for-each-group instruction, and also while evaluating the sort key of a group as expressed by the select attribute or sequence constructor of an xsl:sort child of the xsl:for-each-group element):

  • the group itself, as a sequence of items

  • the grouping-key, which is a single atomic value, or in the case of a composite key, a sequence of atomic values.

There are two ways of getting this information. The preferred way in XSLT 3.0 is to bind variables using the bind-group and bind-grouping-key attributes of the xsl:for-each-group instruction.

If the bind-group attribute is present, then its value must be an EQName, and this causes a local variable binding for this name to be visible within the sequence constructor forming the body of the xsl:for-each-group instruction, and also within any xsl:sort element child of the xsl:for-each-group element. The type of the variable is item()* (any sequence of items), and its value is the content of the group being processed.

If the bind-grouping-key attribute is present, then its value must be a EQName, and this causes a local variable binding for this name to be present within the sequence constructor forming the body of the xsl:for-each-group instruction and also within any xsl:sort element child of the xsl:for-each-group element. The type of the variable is anyAtomicType* (any sequence of atomic values), and its value is the grouping key of the group being processed.

If the variable names bound in the bind-group or bind-grouping-key attributes are used in the select attribute or the sequence constructor within an xsl:sort child of the xsl:for-each-group instruction, then they act as references to the group whose sort key is being computed, or the grouping key of that group, respectively.

[ERR XTSE3220] It is a static error if a variable bound in the bind-group or bind-grouping-key attribute of an xsl:for-each-group instruction is referenced within an expression in the lang, order, collation, stable, case-order, or data-type attributes of an xsl:sort child of that xsl:for-each-group instruction.

[ERR XTSE3230] It is a static error if the bind-grouping-key attribute is present on an xsl:for-each-group instruction unless either the group-by or group-adjacent attribute is present.

For backwards compatibility, XSLT 3.0 also allows information about the group and the grouping key to be obtained using the current-group and current-grouping-key functions respectively. The difference between using bound variables and using these functions is that the variables have static scope (they can only be used lexically within the xsl:for-each-group element), whereas the functions have dynamic scope (they are available in called templates — though not in called functions — as well as within the lexical body of xsl:for-each-group). The fact that the functions have dynamic scope makes certain optimizations difficult, and in particular it makes it impossible to satisfy the rules for streamability. When streamed processing is required, therefore, it is necessary to bind variables to the group and grouping key rather than using the current-group and current-grouping-key functions.

An added benefit of using the bind-group and bind-grouping-key variables is apparent when xsl:for-each-group elements are nested: the grouping variables for the outer instruction remain in scope when processing the inner instruction.

If the bind-group attribute is present on the xsl:for-each-group instruction, then the current group (the value accessed by the current-group function) is set to absent during the processing of the instruction, which has the effect that any call on current-group results in a dynamic error.

If the bind-grouping-key attribute is present on the xsl:for-each-group instruction, or if neither the group-by nor group-adjacent attribute is present, then the current grouping key (the value accessed by the current-grouping-key function) is set to absent during the processing of the instruction, which has the effect that any call on current-grouping-key results in a dynamic error.

The variable bindings established by the bind-group and bind-grouping-key attributes, if present, are visible within all descendant elements of the xsl:for-each-group instruction on which they are declared, other than elements where the variable binding is shadowed by another variable binding. For more information see 9.7 Scope of Variables.

14.2.1 fn:current-group

Summary

Returns the group currently being processed by an xsl:for-each-group or xsl:merge instruction.

Signature

current-group() as item()*
Properties

This function is deterministicFO30, context-dependentFO30, and focus-independentFO30.

Rules

[Definition: The evaluation context for XPath expressions includes a component called the current group, which is a sequence.]

The current group is bound during evaluation of the xsl:for-each-group instruction. If no xsl:for-each-group instruction is being evaluated, the current group will be absent: that is, any reference to it will cause a dynamic error.

The scope of the current group is dynamic: its value is retained through calls on named templates, template rules, functions, and attribute sets.

The function current-group returns the sequence of items making up the current group.

Error Conditions

[ERR XTSE1060] It is a static error if the current-group function is used within a pattern.

[ERR XTDE1061] It is a dynamic error if the current-group function is used when the current group is absent. The error may be reported statically if it can be detected statically.

Notes

The function is classified as focus-dependentFO30, which means that it cannot be used with higher-order functions. Specifically, current-group#0 will not be recognized as a function literal.

14.2.2 fn:current-grouping-key

Summary

Returns the grouping key of the group currently being processed using the xsl:for-each-group or xsl:merge instruction.

Signature

current-grouping-key() as xs:anyAtomicType*
Properties

This function is deterministicFO30, context-dependentFO30, and focus-independentFO30.

Rules

[Definition: The evaluation context for XPath expressions includes a component called the current grouping key, which is a sequence of atomic values. The current grouping key is the grouping key shared in common by all the items within the current group.]

The current grouping key is bound during evaluation of the xsl:for-each-group instruction and during evaluation of the xsl:merge instruction. If no xsl:for-each-group instruction is being evaluated, the current grouping key will be absent, which means that any reference to it causes a dynamic error.

While an xsl:for-each-group instruction with a group-by or group-adjacent attribute is being evaluated, the current grouping key will be a single atomic value if composite="no" is specified (explicitly or implicitly), or a sequence of atomic values if composite="yes" is specified.

While the xsl:merge-action part of an xsl:merge instruction is being evaluated, the current grouping key will be a sequence of atomic values, one for each component of the grouping key, as defined by the xsl:merge-key elements.

At other times, the current grouping key will be absent.

The function current-grouping-key returns the current grouping key.

The grouping keys of all items in a group are not necessarily identical. For example, one might be an xs:float while another is a numerically equal xs:decimal. The current-grouping-key function returns the grouping key of the initial item in the group, after atomization and casting of xs:untypedAtomic values to xs:string.

The function takes no arguments.

Error Conditions

[ERR XTSE1070] It is a static error if the current-grouping-key function is used within a pattern.

[ERR XTDE1071] It is a dynamic error if the current-grouping-key function is used when the current grouping key is absent. The error may be reported statically if it can be detected statically.

Notes

The function is classified as focus-dependentFO30, which means that it cannot be used with higher-order functions. Specifically, current-grouping-key#0 will not be recognized as a function literal.

14.3 Ordering among Groups

[Definition: There is a total ordering among groups referred to as the order of first appearance. A group G is defined to precede a group H in order of first appearance if the initial item of G precedes the initial item of H in population order. If two groups G and H have the same initial item (because the item is in both groups) then G precedes H if the grouping key of G precedes the grouping key of H in the sequence that results from evaluating the group-by expression of this initial item.]

[Definition: There is another total ordering among groups referred to as processing order. If group R precedes group S in processing order, then in the result sequence returned by the xsl:for-each-group instruction the items generated by processing group R will precede the items generated by processing group S.]

If there are no xsl:sort elements immediately within the xsl:for-each-group element, the processing order of the groups is the order of first appearance.

Otherwise, the xsl:sort elements immediately within the xsl:for-each-group element define the processing order of the groups (see 13 Sorting). They do not affect the order of items within each group. Multiple sort key components are allowed, and are evaluated in major-to-minor order. If two groups have the same values for all their sort key components, they are processed in order of first appearance if the sort key specification is stable, otherwise in an implementation-dependent order.

The select expression of an xsl:sort element is evaluated once for each group. During this evaluation, the context item is the initial item of the group, the context position is the position of this item within the set of initial items (that is, one item for each group in the population) in population order, the context size is the number of groups, the current group is the group whose sort key value is being determined, and the current grouping key is the grouping key for that group. If the xsl:for-each-group instruction uses the group-starting-with or group-ending-with attributes, then the current grouping key is the empty sequence.

Example: Sorting Groups

For example, this means that if the grouping key is @category, you can sort the groups in order of their grouping key by writing <xsl:sort select="current-grouping-key()"/>; or you can sort the groups in order of size by writing <xsl:sort select="count(current-group())"/>

14.4 Examples of Grouping

These examples all use the bind-group and bind-grouping-key attributes introduced in XSLT 3.0. For equivalent examples using the current-group and current-grouping-key functions, see the XSLT 2.0 specification.

Example: Grouping Nodes based on Common Values

The following example groups a list of nodes based on common values. The resulting groups are numbered but unsorted, and a total is calculated for each group.

Source XML document:

<cities>
  <city name="Milano"  country="Italia"      pop="5"/>
  <city name="Paris"   country="France"      pop="7"/>
  <city name="München" country="Deutschland" pop="4"/>
  <city name="Lyon"    country="France"      pop="2"/>
  <city name="Venezia" country="Italia"      pop="1"/>
</cities>

More specifically, the aim is to produce a four-column table, containing one row for each distinct country. The four columns are to contain first, a sequence number giving the number of the row; second, the name of the country, third, a comma-separated alphabetical list of the city names within that country, and fourth, the sum of the pop attribute for the cities in that country.

Desired output:

<table>
  <tr>
    <th>Position</th>
    <th>Country</th>
    <th>List of Cities</th>
    <th>Population</th>
  </tr>
  <tr>
    <td>1</td>
    <td>Italia</td>
    <td>Milano, Venezia</td>
    <td>6</td>
  </tr>
  <tr>
    <td>2</td>
    <td>France</td>
    <td>Lyon, Paris</td>
    <td>9</td>
  </tr>  
  <tr>
    <td>3</td>
    <td>Deutschland</td>
    <td>München</td>
    <td>4</td>
  </tr>  
</table>

Solution:

<table xsl:version="3.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <tr>
    <th>Position</th>
    <th>Country</th>
    <th>City List</th>
    <th>Population</th>
  </tr>
  <xsl:for-each-group select="cities/city" group-by="@country" 
       bind-group="cities" bind-grouping-key="country">
    <tr>
      <td><xsl:value-of select="position()"/></td>
      <td><xsl:value-of select="$country"/></td>
      <td>
        <xsl:value-of select="$cities/@name" separator=", "/>
      </td>
      <td><xsl:value-of select="sum($cities/@pop)"/></td>
    </tr>
  </xsl:for-each-group>
</table>

 

Example: A Composite Grouping Key

Sometimes it is necessary to use a composite grouping key: for example, suppose the source document is similar to the one used in the previous examples, but allows multiple entries for the same country and city, such as:

<cities>
  <city name="Milano"  country="Italia"  year="1950"   pop="5.23"/>
  <city name="Milano"  country="Italia"  year="1960"   pop="5.29"/>  
  <city name="Padova"  country="Italia"  year="1950"   pop="0.69"/>
  <city name="Padova"  country="Italia"  year="1960"   pop="0.93"/>    
  <city name="Paris"   country="France"  year="1951"   pop="7.2"/>
  <city name="Paris"   country="France"  year="1961"   pop="7.6"/>
</cities>

Now suppose we want to list the average value of @pop for each (country, name) combination. One way to handle this is to concatenate the parts of the key, for example <xsl:for-each-group select="concat(@country, '/', @name)">. A second solution is to nest one xsl:for-each-group element directly inside another. XSLT 3.0 introduces a third option, which is to define the grouping key as composite:

<xsl:for-each-group select="cities/city" 
                    group-by="@name, @country" 
                    composite="yes"
                    bind-group="group" 
                    bind-grouping-key="key">
  <p><xsl:value-of select="$key[1] || ', ' || $key[2] || ': ' || 
                           avg($group/@pop)"/></p>
                           </xsl:for-each-group>

Note:

The string concatenation operator || is new in XPath 3.0.

 

Example: Identifying a Group by its Initial Element

The next example identifies a group not by the presence of a common value, but rather by adjacency in document order. A group consists of an h2 element, followed by all the p elements up to the next h2 element.

Source XML document:

<body>
  <h2>Introduction</h2>
  <p>XSLT is used to write stylesheets.</p>
  <p>XQuery is used to query XML databases.</p>
  <h2>What is a stylesheet?</h2>
  <p>A stylesheet is an XML document used to define a transformation.</p>
  <p>Stylesheets may be written in XSLT.</p>
  <p>XSLT 2.0 introduces new grouping constructs.</p>
</body>

Desired output:

<chapter>
  <section title="Introduction">
    <para>XSLT is used to write stylesheets.</para>
    <para>XQuery is used to query XML databases.</para>
  </section> 
  <section title="What is a stylesheet?">
    <para>A stylesheet is used to define a transformation.</para>
    <para>Stylesheets may be written in XSLT.</para>
    <para>XSLT 2.0 introduces new grouping constructs.</para>
  </section>
</chapter>

Solution:

<xsl:template match="body">
  <chapter>
        <xsl:for-each-group select="*" group-starting-with="h2"
                       bind-group="h2-et-seq"   >
          <section title="{self::h2}">
            <xsl:for-each select="$h2-et-seq[self::p]">
              <para><xsl:value-of select="."/></para>
            </xsl:for-each> 
          </section>
        </xsl:for-each-group>
  </chapter>
</xsl:template>

The use of title="{self::h2}" rather than title="{.}" is to handle the case where the first element is not an h2 element.

 

Example: Identifying a Group by its Final Element

The next example illustrates how a group of related elements can be identified by the last element in the group, rather than the first. Here the absence of the attribute continued="yes" indicates the end of the group.

Source XML document:

<doc>
  <page continued="yes">Some text</page>
  <page continued="yes">More text</page>    
  <page>Yet more text</page>
  <page continued="yes">Some words</page>
  <page continued="yes">More words</page>    
  <page>Yet more words</page>        
</doc>

Desired output:

<doc>
  <pageset>
    <page>Some text</page>
    <page>More text</page>    
    <page>Yet more text</page>
  </pageset>
  <pageset>
    <page>Some words</page>
    <page>More words</page>    
    <page>Yet more words</page>
  </pageset>
</doc>

Solution:

<xsl:template match="doc">
<doc>
  <xsl:for-each-group select="*" 
                      group-ending-with="page[not(@continued='yes')]"
                      bind-group="pageset">
    <pageset>
      <xsl:for-each select="$pageset">
        <page><xsl:value-of select="."/></page>
      </xsl:for-each> 
    </pageset>
  </xsl:for-each-group>
</doc>
</xsl:template>

 

Example: Adding an Element to Several Groups

The next example shows how an item can be added to multiple groups. Book titles will be added to one group for each indexing term marked up within the title.

Source XML document:

<titles>
    <title>A Beginner's Guide to <ix>Java</ix></title>
    <title>Learning <ix>XML</ix></title>
    <title>Using <ix>XML</ix> with <ix>Java</ix></title>
</titles>

Desired output:

<h2>Java</h2>
    <p>A Beginner's Guide to Java</p>
    <p>Using XML with Java</p>
<h2>XML</h2>
    <p>Learning XML</p>
    <p>Using XML with Java</p>

Solution:

<xsl:template match="titles">
    <xsl:for-each-group select="title" group-by="ix"
                        bind-group="group" bind-grouping-key="key">
      <h2><xsl:value-of select="$key"/></h2>
      <xsl:for-each select="$group">
        <p><xsl:value-of select="."/></p>
      </xsl:for-each>
    </xsl:for-each-group>
</xsl:template>

 

Example: Grouping Alternating Sequences of Elements

In this example, the membership of a node within a group is based both on adjacency of the nodes in document order, and on common values. In this case, the grouping key is a boolean condition, true or false, so the effect is that a grouping establishes a maximal sequence of nodes for which the condition is true, followed by a maximal sequence for which it is false, and so on.

Source XML document:

<p>Do <em>not</em>:
    <ul>
    <li>talk,</li>
    <li>eat, or</li>
    <li>use your mobile telephone</li>
    </ul>
    while you are in the cinema.</p>

Desired output:

<p>Do <em>not</em>:</p>
    <ul>
    <li>talk,</li>
    <li>eat, or</li>
    <li>use your mobile telephone</li>
    </ul>
    <p>while you are in the cinema.</p>

Solution:

This requires creating a p element around the maximal sequence of sibling nodes that does not include a ul or ol element.

This can be done by using group-adjacent, with a grouping key that is true if the element is a ul or ol element, and false otherwise:

<xsl:template match="p">
    <xsl:for-each-group select="node()" 
            group-adjacent="self::ul or self::ol"
            bind-group="group" bind-grouping-key="is-list">
        <xsl:choose>
            <xsl:when test="$is-list">
                <xsl:copy-of select="$group"/>  
            </xsl:when>
            <xsl:otherwise>
                <p>
                    <xsl:copy-of select="$group"/>
                </p>
            </xsl:otherwise>  
        </xsl:choose>
    </xsl:for-each-group>
</xsl:template>

14.5 Non-Transitivity

If the population contains values of different numeric types that differ from each other by small amounts, then the eq operator is not transitive, because of rounding effects occurring during type promotion. It is thus possible to have three values A, B, and C among the grouping keys of the population such that A eq B, B eq C, but A ne C.

For example, this arises when computing

      <xsl:for-each-group group-by="." select="
             xs:float('1.0'),
             xs:decimal('1.0000000000100000000001'),
             xs:double('1.00000000001')">

because the values of type xs:float and xs:double both compare equal to the value of type xs:decimal but not equal to each other.

In this situation the results must be equivalent to the results obtained by the following algorithm:

  • For each item J in the population in population order, for each of the grouping keys K for that item in sequence, the processor identifies those existing groups G such that the grouping key of the initial item of G is equal to K.

  • If there is exactly one group G, then J is added to this group, unless J is already a member of this group.

  • If there is no group G, then a new group is created with J as its first item.

  • If there is more than one group G (which can only happen in exceptional circumstances involving non-transitivity), then one of these groups is selected in an implementation-dependent way, and J is added to this group, unless J is already a member of this group.

The effect of these rules is that (a) every item in a non-singleton group has a grouping key that is equal to that of at least one other item in that group, (b) for any two distinct groups, there is at least one pair of items (one from each group) whose grouping keys are not equal to each other.

15 Merging

The xsl:merge instruction allows a sorted sequence of items to be constructed by merging several input sequences, each of which is already sorted. Each input sequence must have a merge key (one or more atomic values that can be computed as a function of the items in the sequence); the input sequence must be pre-sorted on the value of its merge keys; and the merge keys for the different input sequences must be compatible in the sense that key values from an item in one sequence are always comparable with key values from an item in a different sequence.

For example, if two log files contain details of events sorted by date and time, then the xsl:merge instruction can be used to combine these into a single sequence that is also sorted by date and time.

The data written to the output sequence can be computed in an arbitrary way from the data in the input sequences, provided it follows the ordering of the input sequences.

The xsl:merge instruction can be used to merge several sequences of items that all have the same structure (more precisely, sequences whose merge keys are computed in the same way): for example, log files created by the same application running on different machines in a server farm. Alternatively, xsl:merge can be used to merge sequences that have different structure (sequences whose merge keys are computed in different ways), provided that the computed merge keys are compatible: an example might be two log files created by different applications, using different XML vocabularies, that both contain timestamped events but represent the timestamp in different ways. The xsl:merge-source element represents a set of input sequences that follow common rules, including the rules for computing the merge key. The xsl:merge operation may take any number of xsl:merge-source elements representing different rules for input sequences, and each xsl:merge-source element may describe any number (zero or more) of input sequences. The number of input sequences to the merging operation is thus fixed only at the time the xsl:merge instruction is evaluated, and may vary from one evaluation to another.

The following examples illustrate some of the possibilities. The detailed explanation of the constructs used follows later in this section.

Example: Merging all the files in a collection

This example takes as input a homogeneous collection of XML log files each of which contains a sorted sequence of event elements with a timestamp attribute validated as an instance of xs:dateTime. It merges the events from the input files into a single sorted output file.

<xsl:result-document href="merged-events.xml">
  <events>
    <xsl:merge bind-group="group">
      <xsl:merge-source for-each="collection('log-files')"
                        select="events/event">
        <xsl:merge-key select="@timestamp"/>
      </xsl:merge-source>
      <xsl:merge-action>
        <xsl:copy-of select="$group"/>
      </xsl:merge-action>
    </xsl:merge>
  </events>
</xsl:result-document>

The example assumes that there are several input files each of which has a structure similar to the following, in which the timestamp attribute has a typed value that is an instance of xs:dateTime:

<events>
   <event timestamp="2009-08-20T12:01:01Z">Transaction T1234 started</event>
   <event timestamp="2009-08-20T12:01:08Z">Transaction T1235 started</event>
   <event timestamp="2009-08-20T12:01:12Z">Transaction T1235 ended</event>
   <event timestamp="2009-08-20T12:01:15Z">Transaction T1234 ended</event>
</events>

The output file will have the same structure, and will contain copies of all the event elements from all of the input files, in sorted order. Note that multiple events with the same timestamp can occur either within a single file or across multiple files: the order of appearance of these events in the output file corresponds to the order of the log files within the collection (which might or might not be predictable, depending on the implementation).

 

Example: Merging two heterogeneous files

This example takes as input two log files with different structure, producing a single merged output in which the entries have a common structure:

<xsl:result-document href="merged-events.xml">
  <events>
    <xsl:merge bind-group="grp">
      <xsl:merge-source select="doc('log-file-1.xml')/events/event">
        <xsl:merge-key select="@timestamp"/>
      </xsl:merge-source>
      <xsl:merge-source select="doc('log-files-2.xml')/log/day/record">
        <xsl:merge-key select="dateTime(../@date, time)"/>
      </xsl:merge-source>
      <xsl:merge-action>
        <xsl:apply-templates select="$grp" 
                             mode="standardize-log-entry"/>
      </xsl:merge-action>
    </xsl:merge>
  </events>
</xsl:result-document>

Here the first input file has a structure similar to that shown in the previous example, while the second input has a different structure, of the form:

<log>
  <day date="2009-08-20">
    <record>
      <time>12:01:09-05:00</time>
      <message>Temperature 15.4C</message>
    </record>
    <record>
      <time>12:03:00-05:00</time>
      <message>Temperature 18.2C</message>
    </record>
  </day>
</log>

The templates in mode standardize-log-entry convert the log entries to a common output format, for example:

<xsl:template match="event" mode="standardize-log-entry" 
                            as="schema-element(event)">
  <xsl:copy-of select="." validation="preserve"/>
</xsl:template>
  
<xsl:template match="record" mode="standardize-log-entry" 
                             as="schema-element(event)">
  <event timestamp="{dateTime(../@date, time)}" xsl:validation="strict">
    <xsl:value-of select="message"/>
  </event>
</xsl:template>

Note:

The xsl:merge instruction is designed to enable streaming of data, so that there is no need to allocate memory to hold the input sequences. However, there is no requirement that an implementation should actually use streaming to perform the processing.

15.1 Terminology for merging

[Definition: A merge source definition is the definition of one kind of input to the merge operation. It selects zero or more merge input sequences, and it includes a merge key specification to define how the merge key values are computed for each such merge input sequence.] A merge source definition corresponds to an xsl:merge-source element in the stylesheet.

[Definition: A merge input sequence is an arbitrary sequenceDM30 of items which is already sorted according to the merge key specification for the corresponding merge source definition.]

[Definition: A merge key specification consists of one or more adjacent xsl:merge-key elements which together define how the merge input sequences selected by a merge source definition are sorted. Each xsl:merge-key element defines one merge key component.] For example, a merge key specification for a log file might specify two merge key components, date and time.

[Definition: A merge key component specifies one component of a merge key specification; it corresponds to a single xsl:merge-key element in the stylesheet.]

[Definition:  For each item in a merge input sequence, a value is computed for each merge key component within the merge key specification. The value computed for an item by using the Nth merge key component is referred to as the Nth merge key value of that item.]

[Definition:  The ordered collection of merge key values computed for one item in a merge input sequence (one for each merge key component within the merge key specification) is referred to as a composite merge key value.]

[Definition: A merge activation is a single evaluation of the sequence constructor contained within the xsl:merge-action element, which occurs once for each distinct composite merge key value.]

15.2 The xsl:merge instruction

<!-- Category: instruction -->
<xsl:merge
  bind-group? = eqname
  bind-key? = eqname >
  <!-- Content: (xsl:merge-source+, xsl:merge-action, xsl:fallback*) -->
</xsl:merge>

The effect of the xsl:merge instruction is to produce a sorted result sequence from a number of input sequences.

The input sequences to the merge operation are defined by the xsl:merge-source child elements, as described in the next section.

The sequence constructor contained in the xsl:merge-action element is evaluated once for each distinct composite merge key value to form a partial result sequence. The result of the xsl:merge instruction is the concatenation of these partial result sequences. For example, the action might be to copy the items from all the input sequences to the result sequence without change; or it might be to select the items from one input sequence in preference to the others. In the general case, the items in the partial result sequence are produced by an arbitrary computation that has access to the items (from the various input sequences) that share the same value for the composite merge key.

The xsl:merge-source and xsl:merge-action elements are described in the following sections.

The bind-group attribute establishes the name of a variable which is available for reference within the xsl:merge-action element, and whose value is a sequence of items, from all input sources, that share a common composite merge key value.

The bind-key attribute establishes the name of a variable which is available for reference within the xsl:merge-action element, and whose value is the composite merge key value of these items.

Any xsl:fallback children of the xsl:merge instruction are ignored by an XSLT 3.0 processor, but are used by an XSLT 1.0 or XSLT 2.0 processor to perform fallback processing.

Note:

An xsl:merge instruction that has no input sequences returns an empty sequence. An xsl:merge instruction with a single input sequence performs processing that is very similar in concept to xsl:for-each-group with the group-adjacent attribute, except that it requires the input to be sorted on the grouping key.

15.3 Selecting the sequences to be merged

<xsl:merge-source
  for-each? = expression
  select = expression
  bind-source? = eqname
  streamable? = "yes" | "no"
  sort-before-merge? = "yes" | "no" >
  <!-- Content: xsl:merge-key+ -->
</xsl:merge-source>

Each xsl:merge-source element defines one or more merge input sequences.

In the absence of the for-each attribute, the xsl:merge-source element defines a single merge input sequence. This sequence is the result of evaluating the expression in the select attribute. This is evaluated using the dynamic context of the containing xsl:merge instruction.

When the for-each attribute is present, the xsl:merge-source element defines a collection of merge input sequences. The selection of items in these input sequences is a two-stage process: the for-each attribute of the xsl:merge-source element is an expression that selects a sequence of anchor items, and for each anchor item, the select attribute is evaluated to select the items that make up one merge input sequence. The for-each expression is evaluated with the dynamic context of the containing xsl:merge instruction, while the select attribute is evaluated with the focus for the evaluation as follows:

The bind-source attribute establishes the name of a variable which is available for reference within the xsl:merge-action element, and whose value is a sequence of items, from this source only, that share the composite merge key value for this activation of the xsl:merge-action.

If the sort-before-merge attribute is absent or has the value no, then each input sequence must already be in the correct order for merging (a dynamic error occurs if it is not). If the attribute is present with the value yes, then each input sequence will first be sorted to ensure that it is in the correct order.

Example: Merging several documents with the same structure

The following xsl:merge-source element selects two anchor items (the root nodes of two documents), and for each of these it selects an input sequence consisting of selected event elements within the relevant document.

<xsl:merge-source for-each="doc('log-A.xml'), doc('log-B.xml')"
                  select="events/event">
   <xsl:merge-key select="@timestamp" order="ascending"/>
</xsl:merge-source>

This example can be extended to merge any number of input documents with the same structure:

<xsl:merge-source for-each="collection('log-collection')"
                  select="events/event">
   <xsl:merge-key select="@time" order="ascending"/>
</xsl:merge-source>

In both the above examples the anchor items are document nodes, and the items in the input sequence are elements within the document that is rooted at this node. This is a common usage pattern, but by no means the only way in which the construct can be used.

The number of anchor items selected by an xsl:merge-source element, and therefore the number of input sequences, is variable, but the input sequences selected by one xsl:merge-source element must all use the same expressions to select the items in the input sequence and to compute their merge keys. If different expressions are needed for different input sequences, then multiple xsl:merge-source elements can be used.

Example: Merging two documents with different structure

The following code merges two log files having different internal structure:

<xsl:merge-source select="doc('event-log.xml')/*/event">
  <xsl:merge-key select="@timestamp"/>
</xsl:merge-source>
<xsl:merge-source select="doc('error-log.xml')//error">
  <xsl:merge-key select="dateTime(@date, @time)"/>
</xsl:merge-source>

Although the merge keys are computed in different ways for the two input sequences, the keys must be compatible across the two sequences: in this case they are both atomic values of type xs:dateTime.

In the common case where there is only one input sequence of a particular kind, the for-each attribute of xsl:merge-source may be omitted; the select expression is then evaluated relative to the focus of the xsl:merge instruction itself.

Example: Sorting before merging

Where one or more of the inputs to the merging process is not pre-sorted, a sort can be requested using the sort-before-merge attribute. For example:

<xsl:merge-source select="doc('event-log.xml')/*/event">
  <xsl:merge-key select="@timestamp"/>
</xsl:merge-source>
<xsl:merge-source select="doc('error-log.xml')//error" 
                  sort-before-merge="yes">
  <xsl:merge-key select="dateTime(current-date(), @time)"/>                           
</xsl:merge-source>

[ERR XTSE3190] It is a static error if two sibling xsl:merge-source elements have the same name, whether explicit or implicit.

15.4 Streamable Merging

Any (zero or more) of the inputs to a merging operation may be designated as streamable by including the attribute streamable="yes" on the xsl:merge-source element.

If any xsl:merge-source element is designated as streamable, then in order for streamed processing to be guaranteed, the following conditions must be met:

  1. The for-each attribute must be present on that xsl:merge-source element, and its value must be a function call that calls the document, docFO30, or collectionFO30 function;

  2. The expression in the select attribute of that xsl:merge-source element must be an incrementally consuming expression;

  3. The sort-before-merge attribute of that xsl:merge-source element must either be absent or take its default value of no;

  4. The select expression of each merge key in that xsl:merge-source element must be a motionless expression;

  5. The sequence constructor in the xsl:merge-action element must be either motionless or group-consuming.

Example: Streamed Merging

The following example merges two log files, processing each of them using streaming.

<events>
   <xsl:merge bind-group="grp" bind-key="key">
      <xsl:merge-source for-each="doc('log-file-1.xml')" 
                        select="events/event" 
                        streamable="yes">
         <xsl:merge-key select="@timestamp"/>
      </xsl:merge-source>
      <xsl:merge-source for-each="doc('log-files-2.xml')" 
                        select="log/day/record/snapshot()" 
                        streamable="yes">
         <xsl:merge-key select="dateTime(../@date, time)"/>
      </xsl:merge-source>
      <xsl:merge-action>
         <events time="{$key}">
            <xsl:copy-of select="$grp"/>
         </events>   
      </xsl:merge-action>
   </xsl:merge>
</events>

Note the use of the snapshot function. This is needed because the merge key for the second merge source includes data from a child element of the selected element (making it non-motionless) and also from an attribute of the parent element (making it inaccessible if copy-of were used in place of snapshot).

15.5 Defining the merge keys

The keys on which the input sequences are sorted are referred to as merge keys. If the attribute sort-before-merge has the value yes, the input sequences will be sorted into the correct sequence before the merge operation takes place (alternatively, the processor may use an algorithm that has the same effect as sorting followed by merging). If the attribute is absent or has the value no, then the input sequences must already be in the correct order.

The merge key for each type of input sequence (that is, for each xsl:merge-source element) is defined by a sequence of xsl:merge-key element children of the xsl:merge-source element. Each xsl:merge-key element defines one merge key component. The syntax and semantics of an xsl:merge-key element are closely based on the rules for the xsl:sort element (the only exception being the absence of the stable attribute); the difference is that xsl:merge-key elements do not cause a sort to take place, they merely declare the existing sort order of the input sequence.

<xsl:merge-key
  select? = expression
  lang? = { language }
  order? = { "ascending" | "descending" }
  collation? = { uri }
  case-order? = { "upper-first" | "lower-first" }
  data-type? = { "text" | "number" | eqname } >
  <!-- Content: sequence-constructor -->
</xsl:merge-key>

The select attribute and the contained sequence constructor are mutually exclusive:

[ERR XTSE3200] It is a static error if an xsl:merge-key element with a select attribute has non-empty content.

The effect of the xsl:merge-key elements is defined in terms of the rules for an equivalent sequence of xsl:sort elements: if the rules for sorting (see 13.1.1 The Sorting Process) with stable="yes" would place an item A before an item B in the sorted sequence produced by the sorting process, then A must precede B in the input sequence to the merging process.

The merge keys of the various input sequences to a merge operation must be compatible with each other, since the merge operation will decide the ordering of the result sequence by comparing merge key values across input sequences. This means that across all the xsl:merge-source children of an xsl:merge instruction:

  • Each xsl:merge-source element must have the same number of xsl:merge-key child elements; let this number be N.

  • For each integer J in 1..N, consider the set of xsl:merge-key elements that are in position J among the xsl:merge-key children of their parent xsl:merge-source element. All the xsl:merge-key elements in this set must have the same effective value for their lang, order, collation, case-order, and data-type attributes, where having the same effective value in this case means that either both attributes must be absent, or both must be present and evaluate to the same value; and in addition in the case of collation the absolute URI must be the same after resolving against the base URI.

If any of the attributes lang, order, collation, case-order, or data-type are attribute value templates, then their effective values are evaluated using the focus of the containing xsl:merge instruction.

[ERR XTSE2200] It is a static error if the number of xsl:merge-key children of a xsl:merge-source element is not equal to the number of xsl:merge-key children of another xsl:merge-source child of the same xsl:merge instruction.

[ERR XTDE2210] It is a dynamic error if there are two xsl:merge-key elements that occupy corresponding positions among the xsl:merge-key children of two different xsl:merge-source elements and that have differing effective values for any of the attributes lang, order, collation, case-order, or data-type. Values are considered to differ if the attribute is present on one element and not on the other, or if it is present on both elements with effective values that are not equal to each other. In the case of the collation attribute, the values are compared as absolute URIs after resolving against the base URI.The error may be reported statically if it is detected statically.

[ERR XTDE2220] It is a dynamic error if any input sequence to an xsl:merge instruction contains two items that are not correctly sorted according to the merge key values defined on the xsl:merge-key children of the corresponding xsl:merge-source element, when compared using the collation rules defined by the attributes of the corresponding xsl:merge-key children of the xsl:merge instruction, unless the attribute sort-before-merge is present with the value yes.

[ERR XTTE2230] It is a type error if some item selected by a particular merge key in one input sequence is not comparable using the XPath le operator with some item selected by the corresponding sort key in another input sequence.

15.6 The xsl:merge-action element

The xsl:merge-action child of an xsl:merge instruction defines the processing to be applied for each distinct composite merge key value found in the input sequences to the xsl:merge instruction.

<xsl:merge-action>
  <!-- Content: (sequence-constructor) -->
</xsl:merge-action>

The merge key values for each item in an input sequence are calculated based on the corresponding xsl:merge-key elements, in the same way as sort key values are calculated using a sequence of xsl:sort elements (see 13.1.1 The Sorting Process). If several items from the same or from different input sequences have the same values for all their merge keys (comparing pairwise), then they are considered to form a group. The sequence constructor contained in the xsl:merge-action element is evaluated once for each such group of items, and the result of the xsl:merge instruction is the concatenation of the results obtained by processing each group in turn.

The groups are processed one by one, based on the values of the merge keys for the group. If group G has a set of merge key values M, while group H has a set of merge key values N, then in the result of the xsl:merge instruction, the result of processing group G will precede the result of processing H if and only if M precedes N in the sort order defined by the lang, order, collation, case-order, and data-type attributes of the merge key definitions.

Generally, two sets of sort key values are distinct if any corresponding items in the two sets of values do not compare equal under the rules for the XPath eq operator, under the collating rules for the corresponding merge key definition. In rare cases, when considering more than two sets of sort key values, ambiguities may arise because of the non-transitivity of the eq operator when applied across different numeric types. In this situation, the partitioning of items into sets having distinct key values is handled in the same way as for xsl:for-each-group (see 14.5 Non-Transitivity), and is to some extent implementation-dependent.

The static context for the sequence constructor contained within the xsl:merge-action element includes the variables declared using the bind-group and bind-key attributes of the containing xsl:merge instruction and the bind-source attributes of the xsl:merge-source children of this xsl:merge instruction.

[ERR XTSE3270] It is a static error if the set of variable names declared using the bind-group and bind-key attributes of an xsl:merge instruction and the bind-source attributes of its xsl:merge-source children contains any duplicates.

The variable defined in the bind-key attribute, if any, is bound to the value of the composite merge key value. There may be several input items having merge keys that are equal but distinguishable (for example the number 1.0 as a float and as a double, or the strings "A" and "a" under a case-blind collation); in this case the value of the variable is the value of the merge key computed for the first item in the current group, after atomization and casting of xs:untypedAtomic to xs:string.

The variable defined in the bind-group attribute, if any, is bound to the set of items (zero or more from each input sequence) that have this set of values as their merge key value. The value of this variable is referred to as the current group.

Within the current group, the ordering of items from the input sequences is as follows, in major-to-minor order:

  • Items are first ordered by the xsl:merge-source element that defined the input sequence from which the item was taken; items from xsl:merge-source A precede items from xsl:merge-source B if A precedes B in document order within the stylesheet.

  • Items from different input sequences selected by the same xsl:merge-source element are then ordered based on the order of the anchor items in the sequence selected by evaluating the select attribute of the xsl:merge-source element.

  • Finally, duplicate items from the same input sequence retain their order from the input sequence.

Duplicates are not eliminated: for example, if the same node is selected in more than one input sequence, it may appear twice in the current group.

The variable defined in the bind-source attribute of an xsl:merge-source element, if any, is bound to the current group, filtered to include only those items that originate from the merge source in question.

The focus for evaluation of the sequence constructor contained in the xsl:merge-action element is as follows:

  • The context item is the first item in the current group, that is current-group()[1]

  • The context position is the position of the current group within the sequence of groups (so the first evaluation of xsl:merge-action has position()=1, the second has position()=2, and so on).

  • The context size is the number of groups, that is, the number of distinct sets of merge key values.

Example: Selective processing of merge inputs

Consider a situation where there are two merge sources, named "master" and "update"; the master source identifies a single merge input file (the master file), while the update source identifies a set of N update files, perhaps one for each day of the week. The required logic is that if a merge key is present only in the master file, then the corresponding item should be copied to the output; if it is present in a single update file then that item replaces the corresponding item from the master file; if it is present in several update files, then an error is raised. This can be achieved as follows:

<xsl:merge>
  <xsl:merge-source bind-source="master" 
                    for-each="doc('master.xml')"
                    select="/events/event">
      <xsl:merge-key select="@key"/>
  </xsl:merge-source>
  <xsl:merge-source bind-source="updates" 
                    for-each="collection('updates')"
                    select="/events/event-change">
      <xsl:merge-key select="@affected-key"/>
  </xsl:merge-source>
  <xsl:merge-action>
    <xsl:choose>
      <xsl:when test="empty($master)">
        <xsl:message>
           Error: update is present with no matching master record!
        </xsl:message>
      </xsl:when>
      <xsl:when test="empty($updates)">
        <xsl:copy-of select="$master"/>
      </xsl:when>
      <xsl:when test="count($updates) = 1">
        <xsl:copy-of select="$updates"/>
      </xsl:when>
      <xsl:otherwise>
        <xsl:message>
           Conflict: multiple updates for the same master record!
        </xsl:message>
      </xsl:otherwise>
    </xsl:choose>
  </xsl:merge-action>
</xsl:merge>
            

Some words of explanation:

  • Error messages are produced if there is an update element whose key does not correspond to any element in the master source, or if there is more than one update element corresponding to the same master element.

  • In the absence of errors, if there is a single update element then it is copied to the output; if there is none, then the master element is copied.

15.7 Examples of xsl:merge

Previous sections introduced examples designed to illustrate some specific features of the xsl:merge instruction. This section provides some further examples to illustrate different ways in which the instruction can be used.

Example: Applying transactions to a master file

This example applies transactions from a transaction file to a master file. Records in the master file for which there is no corresponding transaction are copied unchanged. The transaction file contains instructions to delete, replace, or insert records identified by an ID value. The master file is known to be sorted on the ID value; the transaction file is unsorted.

Master file document structure:

<data>
  <record ID="A0001"><...></record>
  <record ID="A0002"><...></record>
  <record ID="A0003"><...></record>
</data>

Transaction file document structure:

<transactions>
  <update record="A0004" action="insert"><...></update>
  <update record="A0002" action="delete"/>
  <update record="A0003" action="replace"><...></update>
</transactions>

Solution:

 <xsl:merge bind-key="merge-key">
  <xsl:merge-source bind-source="master"
                    select="doc('master.xml')/data/record">
      <xsl:merge-key select="@ID"/>
  </xsl:merge-source>
  <xsl:merge-source bind-source="updates"
                    sort-before-merge="yes"
                    select="doc('transactions.xml')/transactions/update">     
      <xsl:merge-key select="@record"/>
  </xsl:merge-source>
  <xsl:merge-action>
    <xsl:choose>
      <xsl:when test="empty($updates)">
        <xsl:copy-of select="$master"/>
      </xsl:when>
      <xsl:when test="$updates/@action=('insert', 'replace')">
        <record ID="{$merge-key}">
          <xsl:copy-of select="$update/*"/>
        </record>
      </xsl:when>
      <xsl:when test="$updates/@action='delete'"/>
    </xsl:choose>
  </xsl:merge-action>
  </xsl:merge>

 

Example: Merging two sequences of numbers

The xsl:merge instruction can be used to determine the union, intersection, or difference of two sequences of numbers (or other atomic values). This code gives the union:

<xsl:merge bind-key="k">
  <xsl:merge-source select="1 to 30">
      <xsl:merge-key select="."/>
  </xsl:merge-source>
  <xsl:merge-source select="20 to 40">
      <xsl:merge-key select="."/>
  </xsl:merge-source>
  <xsl:merge-action>
    <xsl:value-of select="$k"/>
  </xsl:merge-action>
</xsl:merge>
               

While this gives the intersection:

<xsl:merge bind-key="k" bind-group="g">
  <xsl:merge-source select="1 to 30">
      <xsl:merge-key select="."/>
  </xsl:merge-source>
  <xsl:merge-source select="20 to 40">
      <xsl:merge-key select="."/>
  </xsl:merge-source>
  <xsl:merge-action>
    <xsl:if test="count($g) eq 2">
      <xsl:value-of select="$k"/>
    </xsl:if>
  </xsl:merge-action>
</xsl:merge>
               

16 Splitting

16.1 Introduction

Sometimes it is convenient to be able to compute multiple results during a single scan of the input data. For example, a transformation may wish to rename selected elements, and also to output a count of how many elements have been renamed. Traditionally in a functional language this means computing two separate functions of the input sequence, which (in the absence of sophisticated optimization) will result in the input being scanned twice. This is inconsistent with streaming, where the input is only available to be scanned once, and it can also lead to poor performance in non-streaming applications.

To meet this requirement, XSLT 3.0 introduces the instruction xsl:fork. The content of this instruction is a restricted form of sequence constructor, and in a formal sense the effect of the instruction is simply to return the result of evaluating the sequence constructor. However, the presence of the instruction affects the analysis of streamability (see 19.3 Streamability Analysis). In particular, when xsl:fork is used in a context where streaming is required, each independent instruction within the sequence constructor must be streamable, but the analysis assumes that these instructions can all be evaluated during a single pass of the streamed input document.

Note:

The semantics of the instruction require a number of result sequences to be computed during a single pass of the input. A processor may interpret this as a request to use multiple threads. However, implementations using a single thread are feasible, and this instruction is not intended primarily as a means for stylesheet authors to express their intentions with regard to multi-threaded execution.

Note:

Because multiple results are computed during a single pass of the input, and then concatenated into a single sequence, this instruction will generally involve some buffering of results. The amount of memory used should not exceed that needed to hold the results of the instruction. However, within this principle, implementations may adopt a variety of strategies for evaluation; for example, there may be cases where buffering of the input is more efficient than buffering of output.

Generally, stylesheet authors indicate that buffering of input is the preferred strategy by using the copy-of or snapshot functions, and indicate that buffering of output is preferred by using xsl:fork. However, conformant processors are not constrained in their choice of evaluation strategies.

Example: Splitting a transaction file

Consider a transaction file that contains a sequence of debits and credits:

<transactions>
  <transaction value="5.60"/>
  <transaction value="11.20"/>
  <transaction value="-3.40"/>
  <transaction value="8.90"/>
  <transaction value="-1.99"/>
</transactions>

where the requirement is to split this into two separate files containing credits and debits respectively.

This can be achieved in guaranteed-streamable code as follows:

<xsl:stream href="transactions.xml">
  <xsl:fork>
    <xsl:sequence>
      <xsl:result-document href="credits.xml">
        <credits>
          <xsl:for-each select="transactions/transaction[@value ge 0]">
            <xsl:copy-of select="."/>
          </xsl:for-each>
        </credits>
      </xsl:result-document>
    </xsl:sequence>
    <xsl:sequence>
      <xsl:result-document href="debits.xml">
        <debits>
          <xsl:for-each select="transactions/transaction[@value lt 0]">
            <xsl:copy-of select="."/>
          </xsl:for-each>
        </debits>
      </xsl:result-document>
    </xsl:sequence>  
  </xsl:fork>
</xsl:stream>
            

In the absence of the xsl:fork instruction, this would not be streamable, because the sequence constructor includes two consuming instructions. With the addition of the xsl:fork instruction, however, each xsl:result-document instruction is allowed to make a downwards selection.

One possible implementation model for this is as follows: a single thread reads the source document, and sends parsing events such as start-element and end-element to two other threads, each of which is writing one of the two result documents. Each of these implements the downwards-selecting path expression using a process that waits until the next transaction start-element event is received; when this event is received, the process examines the @value attribute to determine whether or not this transaction is to be copied; if it is, then all events until the matching transaction end-element event are copied to the serializer for the result document; otherwise, these events are discarded.

The xsl:sequence instruction may be used as a child of xsl:fork to break the instructions within xsl:fork into a number of separate groups, each of which is considered as (and indeed is) a separate instruction operating in a single pass over the data.

The following section describes the xsl:fork instruction more formally.

16.2 The xsl:fork instruction

<!-- Category: instruction -->
<xsl:fork>
  <!-- Content: ((xsl:sequence | xsl:fallback))+ -->
</xsl:fork>

The result of the xsl:fork instruction is the sequence formed by concatenating the results of evaluating each of its contained xsl:sequence instructions, in order. That is, the result can be determined by treating the content as a sequence constructor and evaluating it as such.

Note:

Any xsl:fallback children will be ignored by an XSLT 3.0 processor.

By using the xsl:fork instruction, the stylesheet author is suggesting to the processor that it would be beneficial to evaluate the contained xsl:sequence instructions during a single pass of a streamed input document. The processor is not required to take any notice of this suggestion.

The presence of an xsl:fork instruction affects the analysis of streamability, as described in 19.3 Streamability Analysis.

Example: Using xsl:fork when streaming

The rules for streamability do not allow two instructions in a sequence constructor to both read child or descendant elements of the context node. This restriction can be avoided by using xsl:fork, as shown below, where each of the two branches of the xsl:fork instruction selects children of the context node.

<xsl:template match="order" mode="a-streamable-mode">                  
  <xsl:variable name="price-and-discount" as="xs:decimal+">
    <xsl:fork>
      <xsl:sequence select="xs:decimal(price)"/>
      <xsl:sequence select="xs:decimal(discount)"/>
    </xsl:fork>
  </xsl:variable>
  <xsl:value-of select="$price-and-discount[1] - $price-and-discount[2]"/>
  </xsl:template>

A possible implementation strategy here is for events from the XML parser to be sent to two separate agents (perhaps but not necessarily running in different threads), one of which computes xs:decimal(price) and the other xs:decimal(discount); on completion the results computed by the two agents are appended to the sequence that forms the value of the variable.

With this strategy, the processor would require sufficient memory to hold the results of evaluating each branch of the fork. If these results (unlike this example) are large, this could defeat the purpose of streaming by requiring large amounts of memory; nevertheless, this code is treated as streamable.

16.3 Examples of splitting with streamed data

This section gives examples of how splitting using xsl:fork can be used to enable streaming of input documents in cases where several results need to be computed during a single pass over the input data.

Example: Deleting elements, and counting deletions

In this example the input is a narrative document containing note elements at any level of nesting. The requirement is to output a copy of the input document in which (a) the note elements have been removed, and (b) a footnote is added at the end indicating how many note elements have been deleted.

<xsl:mode on-no-match="deep-copy" streamable="yes"/>

<xsl:template match="note"/>

<xsl:template match="/*">
  <xsl:fork>
    <xsl:sequence>
      <xsl:apply-templates/>
    </xsl:sequence>
    <xsl:sequence>
      <footnote>
        <p>Removed <xsl:value-of select="count(.//note)"/> 
                 note elements.</p>
      </footnote>
    </xsl:sequence>  
  </xsl:fork>
</xsl:template>
               

The xsl:fork instruction contains two independent branches. These can therefore be evaluated in the same pass over the input data. The first branch (the xsl:apply-templates instruction) causes everything except the note elements to be copied to the result; the second instruction (the literal result element footnote) outputs a count of the number of descendant note elements.

Note that although the processing makes a single pass over the input stream, there is some buffering of results required, because the results of the instructions within the xsl:fork instruction need to be concatenated. In this case an intelligent implementation might be able to restrict the buffered data to a single integer.

In a formal sense, however, the result is exactly the same as if the xsl:fork element were not there.

An alternative way of solving this example problem would be to count the number of note elements using an accumulator: see 18 Accumulators.

17 Regular Expressions

The core function library for XPath 3.0 defines three basic functions that make use of regular expressions:

These functions are described in [Functions and Operators].

For more complex string processing than is possible using these functions, XSLT provides an instruction xsl:analyze-string, which is defined in this section.

The regular expressions used by this instruction, and the flags that control the interpretation of these regular expressions, must conform to the syntax defined in [Functions and Operators] (see Section 5.6.1 Regular expression syntax FO30), which is itself based on the syntax defined in [XML Schema Part 2].

Note:

XPath 3.0 adds a fourth function, analyze-stringFO30, whose functionality is closely modeled on the xsl:analyze-string instruction described in this section, repackaging the facilities in the form of a function.

17.1 The xsl:analyze-string instruction

<!-- Category: instruction -->
<xsl:analyze-string
  select = expression
  regex = { string }
  flags? = { string } >
  <!-- Content: (xsl:matching-substring?, xsl:non-matching-substring?, xsl:fallback*) -->
</xsl:analyze-string>

<xsl:matching-substring>
  <!-- Content: sequence-constructor -->
</xsl:matching-substring>

<xsl:non-matching-substring>
  <!-- Content: sequence-constructor -->
</xsl:non-matching-substring>

The xsl:analyze-string instruction takes as input a string (the result of evaluating the expression in the select attribute) and a regular expression (the effective value of the regex attribute).

If the result of evaluating the select expression is an empty sequence, it is treated as a zero-length string. If the value is not a string, it is converted to a string by applying the function conversion rules.

The flags attribute may be used to control the interpretation of the regular expression. If the attribute is omitted, the effect is the same as supplying a zero-length string. This is interpreted in the same way as the $flags attribute of the functions matchesFO30, replaceFO30, and tokenizeFO30. Specifically, if it contains the letter m, the match operates in multiline mode. If it contains the letter s, it operates in dot-all mode. If it contains the letter i, it operates in case-insensitive mode. If it contains the letter x, then whitespace within the regular expression is ignored. For more detailed specifications of these modes, see [Functions and Operators] (Section 5.6.1.1 Flags FO30).

Note:

Because the regex attribute is an attribute value template, curly brackets within the regular expression must be doubled. For example, to match a sequence of one to five characters, write regex=".{{1,5}}". For regular expressions containing many curly brackets it may be more convenient to use a notation such as regex="{'[0-9]{1,5}[a-z]{3}[0-9]{1,2}'}", or to use a variable.

The xsl:analyze-string instruction may have two child elements: xsl:matching-substring and xsl:non-matching-substring. Both elements are optional, and neither may appear more than once. At least one of them must be present. If both are present, the xsl:matching-substring element must come first.

The content of the xsl:analyze-string instruction must take one of the following forms:

  1. A single xsl:matching-substring instruction, followed by zero or more xsl:fallback instructions

  2. A single xsl:non-matching-substring instruction, followed by zero or more xsl:fallback instructions

  3. A single xsl:matching-substring instruction, followed by a single xsl:non-matching-substring instruction, followed by zero or more xsl:fallback instructions

[ERR XTSE1130] It is a static error if the xsl:analyze-string instruction contains neither an xsl:matching-substring nor an xsl:non-matching-substring element.

Any xsl:fallback elements among the children of the xsl:analyze-string instruction are ignored by an XSLT 2.0 or 3.0 processor, but allow fallback behavior to be defined when the stylesheet is used with an XSLT 1.0 processor operating with forwards-compatible behavior.

This instruction is designed to process all the non-overlapping substrings of the input string that match the regular expression supplied.

[ERR XTDE1140] It is a non-recoverable dynamic error if the effective value of the regex attribute does not conform to the required syntax for regular expressions, as specified in [Functions and Operators]. If the regular expression is known statically (for example, if the attribute does not contain any expressions enclosed in curly brackets) then the processor may signal the error as a static error.

[ERR XTDE1145] It is a non-recoverable dynamic error if the effective value of the flags attribute has a value other than the values defined in [Functions and Operators]. If the value of the attribute is known statically (for example, if the attribute does not contain any expressions enclosed in curly brackets) then the processor may signal the error as a static error.

[ERR XTDE1150] It is a non-recoverable dynamic error if the effective value of the regex attribute is a regular expression that matches a zero-length string: or more specifically, if the regular expression $r and flags $f are such that matches("", $r, $f) returns true. If the regular expression is known statically (for example, if the attribute does not contain any expressions enclosed in curly brackets) then the processor may signal the error as a static error.

The xsl:analyze-string instruction starts at the beginning of the input string and attempts to find the first substring that matches the regular expression. If there are several matches, the first match is defined to be the one whose starting position comes first in the string. If several alternatives within the regular expression both match at the same position in the input string, then the match that is chosen is the first alternative that matches. For example, if the input string is The quick brown fox jumps and the regular expression is jump|jumps, then the match that is chosen is jump.

Having found the first match, the instruction proceeds to find the second and subsequent matches by repeating the search, starting at the first character that was not included in the previous match.

The input string is thus partitioned into a sequence of substrings, some of which match the regular expression, others which do not match it. Each substring will contain at least one character. This sequence of substrings is processed using the instructions within the contained xsl:matching-substring and xsl:non-matching-substring elements. A matching substring is processed using the xsl:matching-substring element, a non-matching substring using the xsl:non-matching-substring element. Each of these elements takes a sequence constructor as its content. If the element is absent, the effect is the same as if it were present with empty content. In processing each substring, the contents of the substring will be the context item (as a value of type xs:string); the position of the substring within the sequence of matching and non-matching substrings will be the context position; and the number of matching and non-matching substrings will be the context size.

If the input is a zero-length string, the number of substrings will be zero, so neither the xsl:matching-substring nor xsl:non-matching-substring elements will be evaluated.

17.2 fn:regex-group

Summary

Returns the string captured by a parenthesized subexpression of the regular expression used during evaluation of the xsl:analyze-string instruction.

Signature

regex-group($group-number as xs:integer) as xs:string
Properties

This function is deterministicFO30, context-dependentFO30, and focus-independentFO30.

Rules

[Definition: While the xsl:matching-substring instruction is active, a set of current captured substrings is available, corresponding to the parenthesized sub-expressions of the regular expression.] These captured substrings are accessible using the function regex-group. This function takes an integer argument to identify the group, and returns a string representing the captured substring.

The Nth captured substring (where N > 0) is the string matched by the subexpression contained by the Nth left parenthesis in the regex, excluding any non-capturing groups, which are written as (?:xxx). The zeroeth captured substring is the string that matches the entire regex. This means that the value of regex-group(0) is initially the same as the value of . (dot).

The function returns the zero-length string if there is no captured substring with the relevant number. This can occur for a number of reasons:

  1. The number is negative.

  2. The regular expression does not contain a parenthesized sub-expression with the given number.

  3. The parenthesized sub-expression exists, and did not match any part of the input string.

  4. The parenthesized sub-expression exists, and matched a zero-length substring of the input string.

The set of captured substrings is a context variable with dynamic scope. It is initially an empty sequence. During the evaluation of an xsl:matching-substring instruction it is set to the sequence of matched substrings for that regex match. During the evaluation of an xsl:non-matching-substring instruction or a pattern or a stylesheet function it is set to an empty sequence. On completion of an instruction that changes the value, the variable reverts to its previous value.

The value of the current captured substrings is unaffected through calls of xsl:apply-templates, xsl:call-template, xsl:apply-imports or xsl:next-match, or by expansion of named attribute sets.

17.3 Examples of Regular Expression Matching

Example: Replacing Characters by Elements

Problem: replace all newline characters in the abstract element by empty br elements:

Solution:

<xsl:analyze-string select="abstract" regex="\n">
  <xsl:matching-substring>
    <br/>
  </xsl:matching-substring>
  <xsl:non-matching-substring>
    <xsl:value-of select="."/>
  </xsl:non-matching-substring>
</xsl:analyze-string>

 

Example: Recognizing non-XML Markup Structure

Problem: replace all occurrences of [...] in the body by cite elements, retaining the content between the square brackets as the content of the new element.

Solution:

<xsl:analyze-string select="body" regex="\[(.*?)\]">
  <xsl:matching-substring>
    <cite><xsl:value-of select="regex-group(1)"/></cite>
  </xsl:matching-substring>
  <xsl:non-matching-substring>
    <xsl:value-of select="."/>
  </xsl:non-matching-substring>
</xsl:analyze-string>

Note that this simple approach fails if the body element contains markup that needs to be retained. In this case it is necessary to apply the regular expression processing to each text node individually. If the [...] constructs span multiple text nodes (for example, because there are elements within the square brackets) then it probably becomes necessary to make two or more passes over the data.

 

Example: Parsing a Date

Problem: the input string contains a date such as 23 March 2002. Convert it to the form 2002-03-23.

Solution (with no error handling if the input format is incorrect):

<xsl:variable name="months" 
        select="'January', 'February', 'March', ..."/>

<xsl:analyze-string select="normalize-space($input)" 
    regex="([0-9]{{1,2}})\s([A-Z][a-z]+)\s([0-9]{{4}})">
    <xsl:matching-substring>
        <xsl:number value="regex-group(3)" format="0001"/>          
        <xsl:text>-</xsl:text>
        <xsl:number value="index-of($months, regex-group(2))" format="01"/>
        <xsl:text>-</xsl:text>
        <xsl:number value="regex-group(1)" format="01"/>
    </xsl:matching-substring>
</xsl:analyze-string>

Note the use of normalize-space to simplify the work done by the regular expression, and the use of doubled curly brackets because the regex attribute is an attribute value template.

18 Accumulators

Accumulators are introduced in XSLT 3.0 to enable data that is read during streamed processing of a document to be accumulated, processed or retained for later use. However, they may equally be used with non-streamed processing.

An accumulator defines a value that is computed progressively while processing the nodes of a document in document order. The value for a given node is available via a pair of functions, one giving the value for a node before processing its descendants, and one given the value for the same node after processing its descendants.

The following sections give first, the syntax rules for defining an accumulator; secondly, and informal description of the semantics; then a more formal definition; and finally, examples. But to illustrate the concept intuitively, the following simple example shows how an accumulator can be used for numbering of nodes

Example: Numbering figures within a chapter

This example assumes document input in which figure elements can appear within chapter elements (which we assume are not nested), and the requirement is to render the figures with a caption that includes the figure number within its containing chapter.

When the document is processed using streaming, the xsl:number instruction is not available, so a solution using accumulators is needed.

The required accumulator can be defined and used like this:

   <xsl:accumulator name="f:figNr" as="xs:integer" 
                    initial-value="0" streamable="yes">
     <xsl:accumulator-rule match="chapter" new-value="0"/>
     <xsl:accumulator-rule match="figure" new-value="$value + 1"/>
   </xsl:accumulator>
   
   <xsl:mode streamable="yes"/>
   <xsl:template match="figure">
     <xsl:apply-templates/>
     <p>Figure <xsl:value-of select="f:figNr()"/></p>
   </xsl:template>  
                  

18.1 Declaring an accumulator

<!-- Category: declaration -->
<xsl:accumulator
  name? = eqname
  post-descent? = eqname
  initial-value? = expression
  as? = sequence-type
  visibility? = "public" | "private" | "final" | "abstract"
  streamable? = "yes" | "no" >
  <!-- Content: xsl:accumulator-rule+ -->
</xsl:accumulator>

<xsl:accumulator-rule
  match = pattern
  phase? = "start" | "end"
  new-value = expression />

An xsl:accumulator element is a declaration that declares one or two functions, each of arity zero. The first function, called the pre-descent function, has the name given by the name attribute, and the second, called the post-descent function, has the name given by the post-descent attribute if present; if absent, the post-descent function is not available. Both names follow the same rules as the name attribute on the xsl:function attribute, which means they must be namespace-qualified. In the event of a conflict with the names of other functions, the same rules apply as for an xsl:function declaration. The visibility of the two functions is determined by the visibility attribute in the same way as for other functions.

[Definition: The functions declared in an xsl:accumulator declaration are referred to as accumulator functions.]

It is a static error [Error code TBA] if neither of the attributes name nor post-descent is present.

The two functions return, respectively, the value of the accumulator before visiting the descendants of a given node, and the value after visiting the descendants of a node. For each of these functions, the arity is zero (there are no arguments), and the function applies implicitly to the context node. The type of the return value (for both functions) is given by the as attribute of the xsl:accumulator element.

Because (when streaming) accumulator functions can only be called in specific circumstances, it is not permitted to make dynamic calls on these functions. Therefore, accumulator functions cannot be bound to function items using the NamedFunctionRefXP30 syntax (qname#arity); they cannot be partially applied (by using ? in place of a function argument); they cannot be discovered dynamically using function-lookupFO30; a call on function-available returns false; and they are not available for use in XPath expressions executed using xsl:evaluate. [Error conditions TBA]

The initial value of the accumulator is obtained by evaluating the expression in the initial-value attribute. The values for individual nodes in a tree are obtained by applying the rules contained within the xsl:accumulator declaration, as described in subsequent sections.

The expression in the initial-value attribute is evaluated with the same static and dynamic context as the expression in the select attribute of a global variable declaration, except that no function declared by any xsl:accumulator declaration, including this one, is available.

The expression in the new-value attribute of xsl:accumulator-rule is evaluated with the a static context that follows the normal rules for expressions in stylesheets, except that:

  • An additional variable is present in the context. The name of this variable is value (in no namespace), and its type is the type that appears in the as attribute of the xsl:accumulator declaration.

  • No function declared by any xsl:accumulator declaration, including this one, is available.

  • The context item for evaluation of the expression will always be a node that matches the pattern in the match attribute.

The result of both the initial-value and new-value expressions is converted to the type declared in the as attribute by applying the function conversion rules. A type error occurs if conversion is not possible. The as attribute defaults to item()*.a

If the streamable attribute is present with the value yes, then in every contained xsl:accumulator-rule, the pattern in the match attribute must be a motionless pattern, and the expression in the new-value attribute must be a motionless expression. The two functions that comprise the value of the accumulator variable will be motionless expressions; the second (returning the post-descent value) is constrained to be used only in a post-descent instruction of a streamable template.

18.2 Informal Model for Accumulators

Informally, an accumulator is evaluated by traversing a document in tree-walking order. Each node is visited twice, once before processing its descendants, and once after processing its descendants. For consistency, this applies even to leaf nodes: each is visited twice. Attribute and namespace nodes, however, are not visited.

Before the traversal starts, a variable (called the accumulator variable) is initialized to the value of the expression given as the initial-value attribute.

On each node visit, the xsl:accumulator-rule elements are examined to see if there is a matching rule. For a match to occur, the pattern in the match attribute must match the node, and the phase attribute must be start if this is the first visit, and end if it is the second visit. If there is a matching rule, then a new value is computed for the accumulator variable using the expression contained in that rule's new-value attribute. If there is more than one matching rule, the last in document order is used. If there is no matching rule, the value of the accumulator variable does not change.

Each node is labeled with a pre-descent value for the accumulator, which is the value of the accumulator variable immediately after processing the first visit to that node, and with a post-descent value for the accumulator, which is the value of the accumulator variable immediately before processing the second visit.

Although this description is expressed in procedural terms, it can be seen that the two values of the accumulator for any given node depend only on the node and its preceding and (in the case of the post-descent value) descendant nodes. Calculation of both values is therefore deterministic and free of side-effects; moreover, it is clear that the values can be computed during a streaming pass of a document, provided that the rules themselves use only information that is available without repositioning the input stream.

18.3 Formal Model for Accumulators

[Definition: A traversal of a tree is a sequence of traversal events.]

[Definition: a traversal event (shortened to event in this section) is a pair comprising a phase (start or end) and a node.] It is modelled as a map with two entries: map{"phase" := p, "node" := n} where p is the string "start" or "end" and n is a node.

The traversal of a document contains two traversal events for each node in the tree, other than attribute and namespace nodes. One of these events (the "start event") has phase = "start", the other (the "end event") has phase = "end".

The order of traversal events within a traversal is such that, given any two nodes M and N with start/end events denoted by M0, M1, N0, and N1, :

  • For any node N, N0 precedes N1;

  • If M is an ancestor of N then M0 precedes N0 and N1 precedes M1;

  • If M is on the preceding axis of N then M1 precedes N0.

The accumulator defines a (private) incrementor function Δ as follows:

  1. The signature of Δ is function ($value as T, $event as map(*)) as T, where T is the sequence type declared in the as attribute of the accumulator declaration;

  2. The implementation of the function is equivalent to the following algorithm:

    1. Let R be the set of xsl:accumulator-rule elements among the children of the accumulator declaration whose phase attribute equals $event.get("phase") and whose match attribute is a pattern that matches $event.get("node")

    2. If R is empty, return $value

    3. Let Q be the xsl:accumulator-rule in R that is last in document order

    4. Return the value of the expression in the next-value attribute of Q, evaluating the expression with a singleton focus set to $event.get("node") and with a dynamic context that binds the variable whose name is the accumulator name to the value $value

For every node N, other than attribute and namespace nodes, the accumulator defines a pre-descent value B(N) and a post-descent value A(N) whose values are as follows:

  1. Let T be the traversal of the tree rooted at fn:root(N)

  2. Let SB be the subsequence of T starting at the first event in T and ending with the start event for node N (that is, the event map{ "phase":="start", "node":=N })

  3. Let SA be the subsequence of T starting at the first event in T, and ending with the event that immediately precedes the end event for node N (that is, the event map{ "phase":="end", "node":=N })

  4. Let Z be the result of evaluating the expression contained in the initial-value attribute of the xsl:accumulator declaration, using the same context as is used for evaluating global variables

  5. Then the pre-descent value B(N) is the value of fn:fold-left(Δ, Z, SB), and the post-descent value A(N) is the value of fn:fold-left(Δ, Z, SA)

18.4 Examples of Accumulators

Example: Remember the title of a document

Consider an XHTML document in which the title of the document is represented by the content of the first title element appearing as a child of the head element, which in turn appears as a child of the html element. Suppose that we want to process the document in streaming mode, and that we want to avoid outputting the content of the h1 element if it is the same as the document title.

This can be achieved by remembering the value of the title in an accumulator variable.

  <xsl:accumulator name="f:title" as="xs:string?" initial-value="()">
    <xsl:accumulator-rule match="html/head/title" new-value="string(.)"/>
  </xsl:accumulator>
  

Subsequently, while processing an h1 element appearing later in the document, the value can be referenced:

  <xsl:template match="h1">
    <xsl:if test="string(.) ne f:title()">
      <div class="heading-1"><xsl:apply-templates/></div>
    </xsl:if>
  </xsl:template>

Note:

This example assumes that in streaming mode, string(.) is permitted for a leaf node (requiring some lookahead). This is not currently the case.

 

Example: Keep a word count

Suppose that there is a requirement to output, at the end of the HTML rendition of a document, a paragraph giving the total number of words in the document.

An accumulator can be used to maintain the word count:

  <xsl:accumulator name="f:word-count" 
                   post-descent="f:final-word-count" 
                   as="xs:integer" 
                   initial-value="0">
    <xsl:accumulator-rule match="text()" 
         new-value="$value + count(tokenize(string(.), '\W+'))"/>
  </xsl:accumulator>
  

The final value can be output at the end of the document:

   <xsl:template match="/">
     <xsl:apply-templates/>
     <p>Word count: <xsl:value-of select="f:final-word-count()"/></p>
   </xsl:template>

 

Example: Output hierarchic section numbers

Consider a document in which section elements are nested within section elements to arbitrary depth, and there is a requirement to render the document with hierarchic section numbers of the form 3.5.1.4.

The current section number can be maintained in an accumulator in the form of a sequence of integers, managed as a stack. The number of integers represents the current level of nesting, and the value of each integer represents the number of preceding sibling sections encountered at that level. For convenience the first item in the sequence represents the top of thenstack.

<xsl:accumulator name="f:section-nr" as="xs:integer*" 
                 initial-value="0">
  <xsl:accumulator-rule match="section" phase="start" 
                 new-value="0, head($value)+1, tail($value)"/>
  <xsl:accumulator-rule match="section" phase="end" 
                 new-value="tail($value) (:pop:)"/>
</xsl:accumulator>  

To illustrate this, consider the values after processing a series of start and end tags:

events accumulator value required section number
<section> 0, 1 1
<section> 0, 1, 1 1.1
</section> 1, 1
<section> 0, 2, 1 1.2
</section> 2, 1
<section> 0, 3, 1 1.3
<section> 0, 1, 3, 1 1.3.1
</section> 1, 3, 1
<section> 0, 2, 3, 1 1.3.2
</section> 2, 3, 1
</section> 3, 1
</section> 1

The section number for a section can thus be generated as:

       <xsl:template match="section">
         <p><xsl:value-of select="reverse(tail(f:section-nr()))" separator="."/></p>
         <xsl:apply-templates/>
       </xsl:template>
                  

 

Example: Compute a histogram showing the number of books, by publisher
 <xsl:accumulator name="a:histogram" as="map(xs:string, xs:integer)"
    initial-value="map{}">
    <xsl:accumulator-rule match="book"
       new-value="if ($value.contains(@publisher)) 
                  then $value.put(@publisher, $a:histogram.get(@publisher)+1)
                  else $value.put(@publisher, 1)"/>
 </xsl:accumulator>

The new-value expression is evaluated with the variable $value set to the current value, and with the context node as the node being visited.

19 Streaming

This specification provides a number of facilities designed to enable streaming: that is, transformation of a source document on-the-fly, as it is parsed, without constructing a complete tree representation of the document in memory.

These facilities include:

  • The xsl:stream instruction, which reads an external document (identified by URI) and initiates streaming of that document.

  • Streaming templates, which allow rule-based invocation of template rules applied to the nodes in a streamed document.

  • A number of additional functions, such as attributes, designed to ensure that stylesheets can be analyzed for streamability. (Unlike the attribute axis, @*, the attributes function returns atomized attribute values, which cannot be used as the base for uncontrolled navigation around the document.)

These facilities impose constraints on the stylesheet code to ensure that a streamable evaluation is possible. Much of this section is concerned with the definition of the rules for streamability.

[Definition: A guaranteed-streamable construct is a construct that follows the rules given in 19.3 Streamability Analysis. Every processor that claims conformance as a streaming processor must be able to process such a construct using streaming, that is, by processing the contents of the source document on the fly as it is read, without the need to buffer the entire document or any entire element in memory. ]

In certain contexts, in particular the xsl:stream instruction and a template rule whose mode is declared with streamable="yes", the stylesheet author has the opportunity to request that evaluation should using streaming. In this case the rules are as follows:

For a streaming processor:

  • If the construct conforms to the rules for being guaranteed-streamable then it must be processed using streaming.

  • If the construct is not guaranteed-streamable then it must still be processed: the specification imposes no rules on how it is processed (it might or might not use streaming). However, a processor that claims conformance as a streaming processor must at user option notify the user that streaming has been requested for a construct that is not guaranteed streamable, and indicate whether or not the implementation is able to process it in a streaming manner.

  • If the evaluation does not use streaming (which will only happen if the construct is not guaranteed-streamable) then the processor should signal a warning indicating that streaming was not possible; the processor may provide a user option to abandon processing in this case.

For a non-streaming processor, the processor must evaluate the construct delivering the same results as if execution used streaming, but with no constraints on the evaluation strategy. (Processing may, of course, fail due to insufficient memory being available, or for other reasons.)

Note:

This specification does not attempt to legislate precisely what constitutes evaluation "using streaming". The most important test is that the amount of memory needed should be for practical purposes independent of the size of the source document, and in particular that the finite size of memory available should not impose a limit on the size of source document that can be processed.

The rules are designed to ensure that streaming processors can analyze streamability using rules different from those in this specification, provided that all constructs that are guaranteed-streamable according to this specification are actually streamable by the implementation. Furthermore, non-streaming processors are not required to analyze streamability at all.

The rules in this version of the specification are deliberately restrictive in order to keep the rules simple. In particular, the rules have been chosen so that they can be assessed by simple syntactic examination of the source code, without recourse to static type analysis or dataflow analysis. Implementations may well be able to relax the rules, and are permitted to do so.

19.1 The xsl:stream instruction

<!-- Category: instruction -->
<xsl:stream
  href = { uri } >
  <!-- Content: sequence-constructor -->
</xsl:stream>

The xsl:stream instruction reads a source document whose URI is supplied, and processes the content of the document using streaming by evaluating the contained sequence constructor.

For example, if a document represents a book holding a sequence of chapters, then the following code can be used to split the book into multiple XML files, one per chapter, without allocating memory to hold the entire book in memory at one time:

<xsl:stream href="book.xml">
  <xsl:for-each select="book">             
    <xsl:for-each select="chapter">
      <xsl:result-document href="chapter{position()}.xml">
        <xsl:copy-of select="."/>
      </xsl:result-document>
    </xsl:for-each>
  </xsl:for-each>  
</xsl:stream>

The document to be read is determined by the effective value of the href attribute (which is defined as an attribute value template). This must be a valid URI reference. If it is an absolute URI reference, it is used as is; if it is a relative URI reference, it is made absolute by resolving it against the base URI of the xsl:stream element. The process of obtaining a document node given a URI is the same as for the docFO30 function. However, unlike the docFO30 function, the xsl:stream instruction offers no guarantee that the resulting document will be stable (that is, that multiple calls specifying the same URI will return the same document).

Specifically, if the xsl:stream instruction is evaluated several times (or if different xsl:stream instructions are evaluated) with the same URI (after making it absolute) as the value of the href attribute, it is implementation-dependent whether the same nodes or different nodes are returned on each occasion; it is also possible that the actual document content will be different.

The result of the xsl:stream instruction is the same as the result of the following (non-streaming) process:

  1. The source document is read from the supplied URI and parsed to form an instance of the XDM data model. This is the streamed document.

  2. The contained sequence constructor is evaluated with the document node of the streamed document as the context item, and with the context position and context size set to one, and the resulting sequence is returned as the result of the xsl:stream instruction.

Note:

The rules for streamability ensure that the sequence constructor (and therefore the xsl:stream instruction) cannot return any nodes from the streamed document. For example, it cannot contain the instruction <xsl:sequence select="//chapter"/>. If nodes from this document are to be returned, they must first be copied, for example by using the xsl:copy-of instruction or by calling the copy-of or snapshot functions.

Because the xsl:stream instruction cannot return nodes from the streamed document, any nodes it does return will be conventional (unstreamed) nodes that can be processed without restriction. For example, if xsl:stream is invoked within a stylesheet function f:firstChapter, and the sequence constructor consists of the instruction <xsl:copy-of select="//chapter"/>, then the calling code can manipulate the resulting chapter elements as ordinary trees rooted at parentless element nodes.

19.1.1 Examples of xsl:stream

The xsl:stream instruction can be used to initiate processing of a document using streaming with a variety of coding styles, illustrated in the examples below.

These examples no longer work; it is no longer possible to compute an aggregate over descendant values using a path expression. Instead, traversal using templates is required.

Example: Using xsl:stream with aggregate functions

The following example computes the number of transactions in a transaction file

Input:

<transactions>
  <transaction value="12.51"/>
  <transaction value="3.99"/>
</transactions>

Stylesheet code:

<xsl:stream href="transactions.xml">
  <count>
    <xsl:for-each select="transactions">
      <xsl:iterate select="transaction">
        <xsl:param name="count" select="0" as="xs:decimal"/>
        <xsl:next-iteration>
          <xsl:with-param name="count" select="$count+1"/>
        </xsl:next-iteration>
        <xsl:on-completion>
          <xsl:value-of select="$count"/>
        </xsl:on-completion>
      </xsl:iterate>
    </xsl:for-each>
  </count>
</xsl:stream>

Result:

<count>2</count>

The following example computes the highest-value transaction in the same input file:

<xsl:stream href="transactions.xml">
  <maxValue>
    <xsl:for-each select="transactions">
      <xsl:iterate select="transaction">
        <xsl:param name="max" select="()"  as="xs:decimal?"/>
        <xsl:variable name="this" as="xs:decimal" 
                      select="data(@value)"/>
        <xsl:variable name="newMax" as="xs:decimal" 
                      select="if ($this gt $max) then $this else $max"/>
        <xsl:next-iteration>
          <xsl:with-param name="max" select="$newMax"/>
        </xsl:next-iteration>
        <xsl:on-completion>
          <xsl:value-of select="$newMax"/>
        </xsl:on-completion>
      </xsl:iterate>
    </xsl:for-each>
  </maxValue>
</xsl:stream>

Result:

<maxValue>12.51</maxValue>

To compute both the count and the maximum value in a single pass over the input, it is possible to use two variables.

 

Example: Using xsl:stream with xsl:for-each to process a collection of input documents

This example displays a list of the chapter titles extracted from each book in a collection of books.

Each input document is assumed to have a structure such as:

<book>
  <chapter number-of-pages="18">
    <title>The first chapter of book A</title>
    ...
  </chapter>
  <chapter number-of-pages="15">
    <title>The second chapter of book A</title>
    ...
  </chapter>
  <chapter number-of-pages="12">
    <title>The third chapter of book A</title>
    ...
  </chapter>
</book>

Stylesheet code:

<chapter-titles>
  <xsl:for-each select="uri-collection('books')">
    <xsl:stream href="{.}">
      <xsl:for-each select="book">
        <xsl:for-each select="chapter">
           <title><xsl:value-of select="title"/></title>
        </xsl:for-each>
      </xsl:for-each>
    </xsl:stream>
  </xsl:for-each>
</chapter-titles>

Output:

<chapter-titles>
  <title>The first chapter of book A</title>
  <title>The second chapter of book A</title>
  ...
  <title>The first chapter of book B</title>
  ...
</chapter-titles>

Note:

This example uses the function uri-collectionFO30 to obtain the document URIs of all the documents in a collection, so that each one can be processed in turn using xsl:stream.

 

Example: Using xsl:stream with xsl:iterate

This example assumes that the input is a book with multiple chapters, as shown in the previous example, with the page count for each chapter given as an attribute of the chapter. The transformation determines the starting page number for each chapter by accumulating the page counts for previous chapters, and rounding up to an odd number if necessary.

<chapter-start-page>
   <xsl:stream href="book.xml">
      <xsl:iterate select="book/chapter">
         <xsl:param name="start-page" select="1"/>
         <chapter title="{title}" start-page="{$start-page}"/>
         <xsl:next-iteration>
            <xsl:with-param name="start-page" 
                            select="$start-page + @number-of-pages + 
                                      (@number-of-pages mod 2)"/>
         </xsl:next-iteration>
      </xsl:iterate>
   </xsl:stream>
</chapter-start-page>

Output:

<chapter-start-page>
  <chapter title="The first chapter of book A" start-page="1"/>
  <chapter title="The second chapter of book A" start-page="19"/>
  <chapter title="The third chapter of book A" start-page="35"/>
  ...
</chapter-start-page>
                     

 

Example: Using xsl:stream with xsl:for-each-group

This example assumes that the input is a book with multiple chapters, and that each chapter belongs to a part, which is present as an attribute of the chapter (for example, chapters 1-4 might constitute Part 1, the next three chapters forming Part 2, and so on):

<book>
  <chapter part="1">
    <title>The first chapter of book A</title>
    ...
  </chapter>
  <chapter part="1">
    <title>The second chapter of book A</title>
    ...
  </chapter>
  ...
  <chapter part="2">
    <title>The fifth chapter of book A</title>
    ...
  </chapter>
</book>

The transformation copies the full text of the chapters, creating an extra level of hierarchy for the parts.

<book>
   <xsl:stream href="book.xml">
      <xsl:for-each select="book">
         <xsl:for-each-group select="chapter" group-adjacent="data(@part)">
            <part number="{current-grouping-key()}">
               <xsl:copy-of select="current-group()"/>
            </part>
         </xsl:for-each-group>
      </xsl:for-each>
   </xsl:stream>
</book>

Output:

<book>
  <part number="1">
    <chapter title="The first chapter of book A" part="1">
      ...
    </chapter>
    <chapter title="The second chapter of book A" part="1">
      ...
    </chapter>
    ...
  </part>
  <part number="2">
    <chapter title="The fifth chapter of book A" part="2">
    ...
    </chapter>
    ...
  </part>
</book>
    

 

Example: Using xsl:stream with xsl:apply-templates

This example copies an XML document while deleting all the ednote elements at any level of the tree, together with their descendants. This example is a complete stylesheet, which is intended to be evaluated by nominating main as the initial template. The use of on-no-match="deep-copy" in the xsl:mode declaration means that the built-in template rule copies nodes unchanged, except where overridden by a user-defined template rule.

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

<xsl:mode name="delete-ednotes" streamable="yes" on-no-match="deep-copy"/>

<xsl:template name="main">
   <xsl:stream href="book.xml">
      <xsl:apply-templates mode="delete-ednotes"/>
   </xsl:stream>
</xsl:template>

<xsl:template match="ednote" mode="delete-ednotes"/>

</xsl:transform>

Additional template rules could be added to process other elements and attributes in the same pass through the data: for example, to modify the value of a last-updated attribute (wherever it appears) to the current date and time, the following rule suffices:

<xsl:template match="@last-updated">
  <xsl:attribute name="last-updated" select="current-dateTime()"/>
</xsl:template>

19.2 Streamable Templates

[Definition: If any of the modes to which a template rule is applicable is a streamable mode, then the template rule must satisfy certain rules to ensure that it can be evaluated using streaming. A template that satisfies these rules is referred to as a guaranteed-streamable template.] Specifically:

19.3 Streamability Analysis

This section describes the rules that determine whether the contents of a template within a streamable mode are guaranteed streamable, which ensures that the template will be streamable using any conformant streaming processor.

Note:

The rules in this section operate on the expression tree that is typically output by the XSLT and XPath parser. For the most part, the rules depend only on identifying the syntactic constructs that are present. However, the analysis does require as a pre-condition that function calls have been resolved to the extent that the corresponding function signature is known, and that variable references referring to grouping variables (those declared in a bind-XXX attribute of an xsl:for-each-group, xsl:merge, or xsl:merge-source element) have been identified as such.

[Definition: The term construct refers to the union of the following: a sequence constructor, an instruction, an attribute set, an attribute value template, an expression, or a pattern.]

[Definition: Every construct has a sweep, which is a measure of the extent to which the current position in the input stream moves during the evaluation of the expression. The sweep is one of: motionless, group-consuming, consuming, or free-ranging.] This list of values is ordered, for example a free-ranging expression has wider sweep than a consuming expression, and so on.

[Definition: A motionless construct is any construct deemed motionless by the rules in this section (19.3 Streamability Analysis).] Informally, a motionless construct is one that can be evaluated without changing the current position in the input stream. The classification of a construct as motionless depends on the context in which the expression appears; a construct such as . that returns a node in a streamed document will not be classified as motionless unless the context ensures that the node will not be used as the origin for further navigation of the source tree.

[Definition: A group-consuming construct is any construct deemed group-consuming by the rules in this section (19.3 Streamability Analysis).] Informally, a group-consuming construct is one whose evaluation requires repositioning of the input stream from the start of the first node in the current group (always a contiguous sequence of children of the context node) to the end of the last node in the current group.

[Definition: A consuming construct is any construct deemed consuming by the rules in this section (19.3 Streamability Analysis).] Informally, a consuming construct is one whose evaluation requires repositioning of the input stream from the start of the current node to the end of the current node.

[Definition: A free-ranging construct is any construct deemed free-ranging by the rules in this section (19.3 Streamability Analysis).] Informally, a free-ranging construct is one whose evaluation may require access to information that is not available from the subtree rooted at the current node, together with information about ancestors of the current node and their attributes.

The following sections describe this categorization for each kind of construct:

19.3.1 Syntactic Context

[Definition: The classification of a construct depends on some cases on the syntactic context in which it appears. This is determined by the kind of construct in which it is immediately contained, and its role within the containing construct.]

Example: The effect of syntactic context on streamability

Consider the expression ., which returns the context item.

The expression name(.) is motionless, because it is possible to determine the name of the context node without advancing the input stream. To achieve this result, the first argument of nameFO30 is classified as an inspection context, and the context item expression appearing in an inspection context is classified as motionless.

The expression data(.) is classified as consuming, because in order to determine the typed value of an element it is necessary to read the subtree rooted at that element. This is achieved by classifying the first argument of dataFO30 as a node-value context; the context item expression appearing in a node-value context is classified as consuming.

The streamability of the expression . intersect $x cannot be determined without knowing where it appears: while exists(. intersect $x) is motionless, data(. intersect $x) is consuming. The syntactic context of the operands of intersect is therefore classified as an inherited context, which means that the context of the operands is the same as the context of the intersect expression itself.

In the expression $f(.) (a dynamic function call), the streamability analysis has no way of determining what the called function will do with the context item, and it therefore concludes that the expression is not dynamically streamable. To achieve this, the argument of a dynamic function call is classified as a navigational context (meaning that if a node is supplied, the callee may perform arbitrary navigation within the tree containing this node), and when . appears in a navigational context, it is classified as free-ranging.

This is relevant in cases where the result of the expression delivers one or more nodes. There are four kinds of syntactic context, based on how the containing expression uses the returned nodes: inspection contexts, value contexts, inherited contexts, and navigation contexts. These are defined as follows:

  • [Definition: An inspection context has the characteristic that when the value of the expression is a node, the containing expression can be evaluated without consuming the subtree rooted at that node.] Inspection contexts are:

    1. all contexts that use the effective boolean valueXP30 of the expression, specifically:

      1. the argument to the functions booleanFO30, notFO30, emptyFO30, and existsFO30;

      2. the operands of the and and or operators;

      3. the condition expression in an XPath if/then/else expression;

      4. the expression appearing in the satisfies clause of a QuantifiedExpr;

      5. the expression appearing in the test attribute of xsl:if or xsl:when.

    2. an expression used as a predicate in an AxisStep or FilterExpression

    3. the operands of the operators is, <<, and >>

    4. the first argument to the functions nameFO30, node-nameFO30, namespace-uriFO30, local-nameFO30, generate-idFO30, base-uriFO30, document-uriFO30, nilledFO30, pathFO30, attributes, has-childrenFO30, in-scope-prefixesFO30, and countFO30

    5. the first operand of the operator / or ! if the second operand is a call to one of the above functions with . as the explicit or implicit argument;

    6. the operand of instance of;

    7. the second argument of the function namespace-uri-for-prefixFO30;

    8. the second argument of the function resolve-QNameFO30;

    9. the second argument of the function langFO30;

    10. an expression used in a context where a function is required, specifically (a) the expression E in a dynamic function call E(args...), (b) an argument in a function call where the required type of the relevant argument has the ItemType function(*) or a subtype thereof.

  • [Definition: In a node value context, the containing expression needs access to information obtained from the subtree rooted at the returned node.]

    This includes cases where the containing expression uses the typed value or string value of the returned node, as well as cases where the returned node is copied.

    Node value contexts are:

    1. the argument to any FunctionCall where the type of the corresponding parameter in the function signature has an atomic ItemType;

    2. an operand of an atomizing operator (+, -, *, div, idiv, mod, =, !=, >, <, >=, <=, eq, ne, gt, lt, ge, le, ||, to);

    3. the operand of a cast or castable expression;

    4. the first argument of the functions dataFO30 and stringFO30;

    5. the first argument of the operator / or ! if the second argument is a call to one of the above functions with . as the explicit or implicit argument;

    6. the select attribute of one of the instructions xsl:analyze-string, xsl:attribute, xsl:comment, xsl:copy, xsl:copy-of, xsl:namespace, xsl:processing-instruction, xsl:value-of

    7. the group-adjacent attribute of xsl:for-each-group;

    8. an expression embedded within an attribute value template of an XSLT instruction or a literal result element

  • [Definition: In an inherited context, the syntactic context of an expression is the same as the syntactic context of its containing expression.]

    The following are inherited contexts:

    1. The operand of a union, intersect, or except operator;

    2. The operand of a comma (,) operator;

    3. The operand of a treat as expression;

    4. The expressions in the then and else branches of a conditional expression;

    5. The expressions in the return clause of a for or let expression;

    6. An expression contained within parentheses;

    7. The last StepExpr operand within a RelativePathExpr;

    8. The expression E in a filter expression or axis expression of the form E[P];

    9. The first argument of the functions subsequenceFO30, insert-beforeFO30, removeFO30, headFO30, tailFO30, exactly-oneFO30, zero-or-oneFO30, one-or-moreFO30, unorderedFO30, innermostFO30, or outermostFO30.

    Note:

    The distinguishing feature of the above contexts is that the value of the subexpression forms the result, or part of the result, of the containing expression.

  • [Definition: In a navigation context, the containing expression potentially performs arbitrary navigation from the returned node to other nodes in the same tree, or reordering of the nodes in a supplied node sequence, which is therefore incompatible with streaming.]

    Any context not included in one of the categories listed above is classified as a navigation context. Examples include:

    1. The select attribute of xsl:variable, xsl:param, or xsl:with-param;

    2. The select attribute of xsl:sequence;

    3. An argument to a call on a user-defined function where the corresponding function signature does not cause the node to be atomized;

    4. The left-hand operand of the operators /, //, and !;

    5. The first argument to the reverseFO30 function;

    6. An argument to a dynamic function call.

19.3.2 General Rules for Streamability

Many constructs share the same streamability rules. A construct is classified as a first-order construct if it satisfies two conditions:

  1. Its semantics can be described as a simple function of the values obtained by evaluating each of its sub-constructs exactly once with the same dynamic context as the containing construct.

  2. If any of the sub-constructs may deliver a sequence of multiple nodes, then the result of the construct can be determined by processing those nodes one at a time in order, that is, without retaining the entire sequence in memory.

Examples of first-order constructs are: an arithmetic expression, an attribute value template, a sequence constructor, and the xsl:value-of instruction. By contrast, an xsl:for-each instruction or a filter expression are not first-order because in both cases one of the sub-constructs is evaluated repeatedly, with a different dynamic context; and a conditional expression is not first-order because some of the sub-constructs are not evaluated. An xsl:perform-sort or a call on the reverseFO30 function are not first-order because they need to consider the input sequence as a whole, rather than processing it one item at a time.

The sweep of a first-order construct depends on the sweep of its sub-constructs as follows:

  1. If the construct has no sub-constructs, then it is motionless.

  2. If all immediately contained sub-constructs are motionless, the construct is motionless.

  3. If exactly one immediately contained sub-construct is group-consuming and all others are motionless, then the construct is group-consuming.

  4. If exactly one immediately contained sub-construct is consuming and all others are motionless, then the construct is consuming.

  5. Otherwise, the construct is free-ranging.

Note:

Informally: the sweep of the construct is the maximum sweep of any of its sub-constructs, except that if more than one sub-construct consumes the input stream, then the construct is classified as free-ranging to indicate that it cannot be streamed.

19.3.3 Classifying Sequence Constructors

A sequence constructor is a first-order construct whose sub-constructs are the contained instructions. It is classified according to the general rules for streamability given in 19.3.2 General Rules for Streamability.

Note:

Informally, this rule states that a sequence constructor is not streamable if it contains more than one instruction that moves the position of the input stream.

Instructions within a sequence constructor are further classified to control the use of accumulator functions:

  1. [Definition: A motionless instruction having no consuming instruction as a preceding sibling is referred to as a pre-descent instruction.]

  2. [Definition: A motionless instruction having a consuming instruction as a preceding sibling is referred to as a post-descent instruction.]

  3. In addition, the following are classified as post-descent instructions:

    1. Any instruction whose parent is an xsl:if instruction, if the test expression is a consuming expression;

    2. Any instruction whose parent is an xsl:when instruction, if the test expression of the parent xsl:when or of any preceding sibling of the parent xsl:when is a consuming expression

Note:

The above definitions mean that when a sequence constructor is non-consuming, all its instructions are considered to be pre-descent instructions; this has the effect that none of the instructions can reference a post-descent accumulator function. If this is inconvenient, a workaround is to add a dummy consuming instruction to the sequence constructor, for example:

   <xsl:template match="text()">
     <xsl:value-of select="acc:before-descent()"/>
     <xsl:copy-of select="child::node()"/>
     <xsl:value-of select="acc:after-descent()"/>
   </xsl:template>

19.3.4 Classifying Instructions

This section describes how instructions are classified with respect to their streamability.

The list that follows describes the rules for each instruction individually.

Instructions are classified as follows:

Literal result elements

A literal result element is a first-order construct whose sub-constructs are:

  1. The contained sequence constructor;

  2. Any expressions contained in attribute value templates among the literal result element's attributes.

  3. The attribute sets named in the xsl:use-attribute-sets attribute, if present.

The sweep of the literal result element is determined using the general rules in 19.3.2 General Rules for Streamability.

Instruction xsl:analyze-string

If all expressions contained in the regex attribute value template are motionless, and if the sequence constructors contained in the xsl:matching-substring and xsl:non-matching-substring sequence constructors are not group-consuming, then the sweep of the instruction is the sweep of the select expression.

Otherwise, the instruction is free-ranging.

Instruction xsl:apply-imports

The sweep of the instruction is the first of the following that applies:

  1. If there is a child xsl:with-param element that has a select expression which is not motionless or a contained sequence constructor which is not motionless, the instruction is free-ranging.

  2. Otherwise, then the instruction is consuming.

Instruction xsl:apply-templates

The sweep of the instruction is the first of the following that applies:

  1. If there is a child xsl:with-param element that has a select expression which is not motionless or a contained sequence constructor which is not motionless, then free-ranging.

  2. If there is a child xsl:sort element that has a select expression which is group-consuming or a contained sequence constructor which is group-consuming, then free-ranging.

  3. If all the following conditions are satisfied, then the instruction is motionless:

    1. The select expression is motionless;

    2. Any expressions contained in attribute value templates among the attributes of any xsl:sort children are motionless;

  4. If all the following conditions are satisfied, then group-consuming:

    1. the explicit or implicit mode is streamable (if mode="#current" is specified, then all possible modes are streamable)

    2. there are no xsl:sort children;

    3. the select expression is a variable reference to a variable declared in the bind-group attribute of the innermost ancestor xsl:for-each-group instruction;

  5. If all the following conditions are satisfied, then consuming:

    1. the explicit or implicit mode is streamable (if mode="#current" is specified, then all possible modes are streamable);

    2. there are no xsl:sort children;

    3. the select expression is incrementally consuming.

  6. Otherwise, free-ranging.

Instruction xsl:assert

The xsl:assert instruction is a first-order construct whose sub-constructs are:

  1. The enabled expression, if present;

  2. The test expression;

  3. The select expression, if present;

  4. The contained sequence constructor.

The sweep of the xsl:assert instruction is determined using the general rules in 19.3.2 General Rules for Streamability.

Instruction xsl:attribute

The xsl:attribute instruction is a first-order construct whose sub-constructs are:

  1. The expression in the select attribute, if present;

  2. The contained sequence constructor;

  3. Any expressions contained in the name namespace, and separator attribute value templates.

The sweep of the xsl:attribute instruction is determined using the general rules in 19.3.2 General Rules for Streamability.

Instruction xsl:break

If the select expression and the contained sequence constructor (where present) are motionless, the instruction is motionless.

Otherwise, the instruction is free-ranging.

Instruction xsl:call-template

The first of the following that applies:

  1. If there is a child xsl:with-param element that has a select expression which is not motionless or a contained sequence constructor which is not motionless, the instruction is free-ranging.

  2. If the referenced template has a child xsl:context-item element with the attribute use="prohibited", then motionless.

  3. Otherwise, free-ranging.

Instruction xsl:choose

The first of the following that applies:

  1. If all test conditions are motionless, then the sweep of the instruction is the maximum sweep of the sequence constructors contained in child xsl:when and xsl:otherwise elements.

  2. If every sequence constructor contained in a child xsl:when or xsl:otherwise element is motionless, and if there is at most one test condition that is not motionless, then the sweep of the instruction is the sweep of that test condition.

  3. Otherwise, free-ranging.

Instruction xsl:comment

The xsl:comment instruction is a first-order construct whose sub-constructs are:

  1. The expression in the select attribute, if present;

  2. The contained sequence constructor.

The sweep of the xsl:comment instruction is determined using the general rules in 19.3.2 General Rules for Streamability.

Instruction xsl:copy

The sub-constructs of xsl:copy are:

  1. The expression in the select attribute, if present;

  2. The contained sequence constructor;

  3. The attribute-sets named in the use-attribute-sets attribute, if present.

The sweep of the instruction is the first of the following that applies:

  1. If all sub-constructs are motionless, then motionless;

  2. If the select attribute is absent, or is ., then the first of the following that applies:

    1. If all sub-constructs other than the select expression are motionless, then motionless;

    2. If the contained sequence constructor is group-consuming and all referenced attribute sets are motionless, then group-consuming

    3. If the contained sequence constructor is consuming and all referenced attribute sets are motionless, then consuming.

  3. If the select attribute is present and is motionless, then the first of the following that applies:

    1. If all referenced attribute sets are motionless, then motionless.

    2. Otherwise, free-ranging.

  4. Otherwise, free-ranging.

Instruction xsl:copy-of

The xsl:copy-of instruction is a first-order construct whose only sub-construct is its select expression.

The sweep of the xsl:copy-of instruction is determined using the general rules in 19.3.2 General Rules for Streamability (in practice, this means that the sweep of the instruction is the same as the sweep of the select expression).

Instruction xsl:document

The xsl:document instruction is a first-order construct whose only sub-construct is its contained sequence constructor.

The sweep of the xsl:document instruction is determined using the general rules in 19.3.2 General Rules for Streamability (in practice, this means that the sweep of the instruction is the same as the sweep of the contained sequence constructor).

Instruction xsl:element

The xsl:element instruction is a first-order construct whose sub-constructs are:

  1. The contained sequence constructor;

  2. Any expressions contained in the name and namespace attribute value templates;

  3. The attribute sets named in the use-attribute-sets attribute, if present.

The sweep of the xsl:element instruction is determined using the general rules in 19.3.2 General Rules for Streamability

Instruction xsl:evaluate

If the expressions contained in the xpath, context-item, namespace-context, base-uri, and schema-aware attributes, as well as the select attributes and contained sequence constructors of any child xsl:with-param elements, are all motionless, then the sweep of the instruction is motionless.

Otherwise, the instruction is free-ranging.

Instruction xsl:for-each

The sweep of the instruction is the first of the following that applies:

  1. If any of the following conditions is true, then free-ranging:

    1. The sequence constructor contained in the instruction is group-consuming;

    2. The select expression of an xsl:sort child element is group-consuming;

    3. The sequence constructor contained in an xsl:sort child element is group-consuming.

  2. If all the following conditions are true, then motionless:

    1. The select expression is motionless;

    2. All expressions contained in attribute value templates in child xsl:sort elements are motionless;

    3. The instruction does not contain (at any depth) a reference to a variable declared in the bind-group attribute of an xsl:for-each-group element that is an ancestor of the xsl:for-each instruction.

  3. If all the following conditions are true, then group-consuming:

    1. the contained sequence constructor is motionless or consuming;

    2. there is no xsl:sort child element;

    3. the select expression is a variable reference to a variable declared in the bind-group attribute of the innermost ancestor xsl:for-each-group instruction;

  4. If all the following conditions are true, then consuming:

    1. the contained sequence constructor is motionless or consuming

    2. there is no xsl:sort child element

    3. the select expression is incrementally consuming.

  5. Otherwise, free-ranging.

Instruction xsl:for-each-group

The sub-constructs of the xsl:for-each-group instruction are divided into two groups, as follows.

The outer-focus sub-constructs are all of the following that are not absent (these are all evaluated with the same focus as the xsl:for-each-group instruction itself):

  • The select expression

  • Any expressions in the collation attribute value template

  • Any expressions in attribute value templates of child xsl:sort element

The inner-focus sub-constructs are all of the following that are not absent (these are all evaluated with a focus based on the selected population):

  • The group-by expression

  • The group-adjacent expression

  • The group-starting-with pattern

  • The group-ending-with pattern

  • The contained sequence constructor

  • Every select expression of a child xsl:sort elements

  • Every sequence constructor appearing as the content of a child xsl:sort element

The sweep of the instruction is the first of the following that applies:

  1. If all outer-focus sub-constructs are motionless, and if no inner focus sub-construct contains (at any depth) a reference to a variable declared in the bind-group attribute of an xsl:for-each-group instruction that is an ancestor of this xsl:for-each-group instruction, then motionless.

  2. If there is a group-by attribute, then free-ranging.

  3. If there is no bind-group attribute, then free-ranging.

  4. If there is a group-adjacent attribute but no bind-grouping-key attribute, then free-ranging.

  5. If all the following conditions are satisfied, then group-consuming:

    1. the contained sequence constructor is motionless or consuming

    2. the select expression is a variable reference to a variable declared in the bind-group attribute of the innermost ancestor xsl:for-each-group instruction.

    3. there is no xsl:sort child element.

    4. all other sub-constructs are motionless.

  6. If all the following conditions are satisfied, then consuming:

    1. the contained sequence constructor is motionless or consuming

    2. the select expression is incrementally consuming.

    3. there is no xsl:sort child element.

    4. all other sub-constructs are motionless.

  7. Otherwise, the instruction is free-ranging.

Instruction xsl:fork

The sweep of the instruction is the maximum sweep of the xsl:sequence child instructions.

Instruction xsl:if

The sweep of the instruction is the first of the following that applies:

  1. If the test condition is motionless, then the sweep of the contained sequence constructor.

  2. If the contained sequence constructor is motionless, then the sweep of the test condition.

  3. Otherwise, free-ranging.

Instruction xsl:iterate

The sub-constructs of the xsl:iterate instruction are divided into three groups, as follows.

  1. The outer-focus sub-constructs are all of the following that are not absent (these are all evaluated with the same focus as the xsl:iterate instruction itself):

  2. The inner-focus sub-constructs of the xsl:iterate instruction are all of the following that are not absent (these are all evaluated with a focus based on the sequence selected by the select expression):

  3. The no-focus sub-constructs of the xsl:iterate instruction are all of the following that are not absent (these are all evaluated with an absent focus):

The sweep of the instruction is the first of the following that applies:

  1. If all outer-focus sub-constructs are motionless, and if no sub-construct contains (at any level) a reference to a variable declared in the bind-group attribute of an xsl:for-each-group instruction that is an ancestor of this xsl:iterate instruction, then motionless.

  2. If all the following conditions are satisfied, then group-consuming:

    1. the contained sequence constructor is motionless or consuming

    2. the select expression is a variable reference to a variable declared in the bind-group attribute of the innermost ancestor xsl:for-each-group instruction.

    3. all other inner-focus and outer-focus sub-constructs are motionless.

  3. If all the following conditions are satisfied, then consuming:

    1. the contained sequence constructor is motionless or consuming

    2. the select expression is incrementally consuming.

    3. all other inner-focus and outer-focus sub-constructs are motionless.

  4. Otherwise, free-ranging.

Note:

It is a consequence of the rules given that if an xsl:iterate instruction is to be streamable, then all related xsl:param, xsl:on-completion, xsl:break, and xsl:next-iteration elements must be motionless.

Instruction xsl:merge

If all xsl:merge-source children are motionless then the instruction is motionless.

Otherwise, the instruction is free-ranging.

Note:

The xsl:merge instruction will often process its input using streaming, but the rule here is concerned with the sweep of the instruction with respect to the document containing the context node, which will not usually be one of the primary inputs to the merging process. A merge operation that processes several input documents in a streaming manner might thus be classified as free-ranging with respect to the principal source document of the transformation.

A more ambitious implementation might attempt to recognize the case where one of the merge sources involves consuming a subtree of the principal source document: that is, the case where one merge source is a consuming expression and the other sources are motionless.

Instruction xsl:message

The xsl:message instruction is a first-order construct whose sub-constructs are:

  1. The terminate attribute value template;

  2. The select expression, if present, is motionless;

  3. The contained sequence constructor is motionless.

The sweep of the xsl:message instruction is determined using the general rules in 19.3.2 General Rules for Streamability.

Instruction xsl:namespace

The xsl:namespace instruction is a first-order construct whose sub-constructs are:

  1. The expression in the select attribute, if present;

  2. The contained sequence constructor;

  3. Any expressions contained in the name attribute value template.

The sweep of the xsl:namespace instruction is determined using the general rules in 19.3.2 General Rules for Streamability.

Instruction xsl:next-iteration

If the select expression and the contained sequence constructor of every child xsl:with-param element (where present) are motionless, the instruction is motionless.

Otherwise, the instruction is free-ranging.

Instruction xsl:next-match

The sweep of the instruction is the first of the following that applies:

  1. If there is a child xsl:with-param element that has a select expression which is not motionless or a contained sequence constructor which is not motionless, the instruction is free-ranging.

  2. Otherwise, the instruction is consuming.

Instruction xsl:number

The sweep of the instruction is the first of the following that applies:

  1. If there is a value attribute, and if all expressions appearing in attributes of the xsl:number element other than the value attribute are motionless, then the sweep of the value expression.

  2. If there is a select attribute, and if all expressions appearing in attributes of the xsl:number element including the select attribute are motionless, then motionless.

  3. Otherwise, free-ranging.

Instruction xsl:perform-sort

The sweep of the instruction is the first of the following that applies:

  1. If all the following conditions are true, then motionless:

    1. The select expression is motionless;

    2. All expressions in attribute value templates of contained xsl:sort elements are motionless.

  2. Otherwise, free-ranging.

Note:

The select expression of a contained xsl:sort does not need to be motionless, because it is evaluated with a different context.

Instruction xsl:processing-instruction

The xsl:processing-instruction instruction is a first-order construct whose sub-constructs are:

  1. The expression in the select attribute, if present;

  2. The contained sequence constructor;

  3. Any expressions contained in the name attribute value template.

The sweep of the xsl:processing-instruction instruction is determined using the general rules in 19.3.2 General Rules for Streamability.

Instruction xsl:result-document

The xsl:result-document instruction is a first-order construct whose sub-constructs are:

  1. The contained sequence constructor;

  2. Any expressions contained in attribute value templates among the attributes of the instruction.

The sweep of the xsl:result-document instruction is determined using the general rules in 19.3.2 General Rules for Streamability.

Instruction xsl:sequence

The xsl:sequence instruction is a first-order construct whose sub-constructs are the select expression (if present) and the contained sequence constructor.

The sweep of the xsl:sequence instruction is determined using the general rules in 19.3.2 General Rules for Streamability.

Instruction xsl:stream

The sweep of the instruction is the sweep of the attribute value template in its href attribute.

Note:

xsl:stream starts a new streaming process on a new document, but in most cases it will be motionless with respect to the context item of the template in which it appears.

Instruction xsl:text and text nodes

The instruction is motionless

Instruction xsl:try

The sweep of the instruction is the first of the following that applies:

  1. If the select expression and/or sequence constructor of the xsl:catch element are motionless, then the sweep of the select expression and/or sequence constructor of the xsl:try element (whichever is present);

  2. Otherwise, free-ranging.

Instruction xsl:value-of

The xsl:value-of instruction is a first-order construct whose sub-constructs are:

  1. The expression in the select attribute, if present;

  2. The contained sequence constructor;

  3. Any expressions contained in the separator attribute value template.

The sweep of the xsl:value-of instruction is determined using the general rules in 19.3.2 General Rules for Streamability.

Instruction xsl:variable

If there is a select expression, then the sweep of the instruction is the sweep of the select expression.

Otherwise (there is a sequence constructor, possibly empty), the sweep of the instruction is the sweep of the sequence constructor.

19.3.5 Classifying Attribute Sets

An attribute set is a first-order construct whose sub-constructs are:

  1. Any xsl:attribute instruction contained in the attribute set.

  2. Any attribute set referenced by the attribute set in its use-attribute-sets attribute.

The sweep of an attribute set is determined using the general rules in 19.3.2 General Rules for Streamability.

Note:

Attribute sets will usually be motionless, unless they access the context item, in which case they will typically be consuming.

19.3.6 Classifying Attribute Value Templates

An attribute value template is a first-order construct whose sub-constructs are the expressions contained within curly braces.

The sweep of an attribute value template is determined using the general rules in 19.3.2 General Rules for Streamability.

19.3.7 Classifying Expressions

Given these syntactic contexts, expressions are classified using the rules in this section.

In the analysis that follows, expressions are classified according to the most specific production rule that they match for which there is an entry in this section. For example, the expression 3 satisfies the productions NumericLiteral, Literal, and ArithmeticExpression; the most specific of these for which there is an entry in this section is Literal. A production P is considered more specific than a production Q (QP) if every expression that matches P also matches Q.

Th production rules for different kinds of expression are listed (with their names and numbers) in the order in which they appear in Appendix A.1 of the XPath 3.0 specification.

Expr [6]

Note:

Because of the rules given above, this entry applies only to an expression that contains one or more comma (,) operators.

The sweep of an Expr is the maximum sweep of any of its contained ExprSimple operands, except that if more than one of these operands is consuming or group-consuming, then the sweep of the expression is free-ranging.

ForExpr [8]

If all immediately contained subexpressions are motionless, then motionless; otherwise free-ranging.

Note:

The analysis does not enable guaranteed streamed processing of expressions of the form for $x in child::section return $x/para, because this requires data flow analysis (tracing from the binding of a variable to its usages), rather than purely syntactic analysis. Some implementations may be able to stream such constructs.

As a workaround, the above expression can be rewritten as a path expression, or as an xsl:for-each instruction.

LetExpr [11]

A LetExpr is a first-order expression, and follows the general rule given in 19.3.2 General Rules for Streamability. Writing the expression as let $v := S return A, the two sub-constructs of a LetExpr are S and A.

Note:

So, for example let $x := 3 return abs($x) is motionless, while let $x := . return name($x) is free-ranging; this is because the analysis makes no attempt to examine the ways in which the variable $x is actually used.

QuantifiedExpr [14]

If all immediately contained subexpressions are motionless, then motionless; otherwise free-ranging.

IfExpr [15]

Writing the expression as if (C) then T else E, the sweep of the expression is the first of the following that applies:

  1. If C is motionless (in an inspection context), then the maximum sweep of T and E;

  2. If T and E are both motionless, then the sweep of C;

  3. Otherwise, free-ranging.

OrExpr [16]
AndExpr [17]
ComparisonExpr [18]
StringConcatExpr [19]
RangeExpr [20]
AdditiveExpr [21]
MultiplicativeExpr [22]
UnionExpr [23]
IntersectExceptExpr [24]
InstanceOfExpr [25]
TreatExpr [26]
CastableExpr [27]
CastExpr [28]
UnaryExpr [29]
GeneralComp [31]
ValueComp [32]
NodeComp [33]
PathExpr [34]

If the PathExpr is not a RelativePathExpr, then the sweep of the expression is free-ranging.

RelativePathExpr [35]

The rules that follow are applied after expanding any // pseudo-operator to /descendant-or-self::node()/.

The sweep of the expression is the first of the following that applies:

  1. If the first StepExpr is motionless, then motionless;

    Note:

    Examples are expressions such as doc('x')//a or $e/salary which reference data in unstreamed documents.

  2. If the syntactic context is an inspection context and the RelativePathExpr takes the form of a RelativePathPattern that itself conforms to the rules for a motionless pattern (see 19.3.10 Classifying Patterns), then consuming;

    Note:

    Example: exists(descendant::section)

    The rationale for this rule is that with such a construct is possible to process the descendants of the context node one at a time, in document order, testing each one to see whether it matches the corresponding pattern, and if it does, performing the inspection action while the input stream is positioned at the start of the node.

  3. If the syntactic context is an node value context and the expression is incrementally consuming, then consuming;

    Note:

    Examples are <xsl:value-of select="tbody/tr[1]/td[2]"/> or <xsl:value-of select="outermost(.//table)/caption"/>; but not <xsl:value-of select=".//table/caption"/>, because of the possibility that this will select elements that are nested inside one another.

  4. If the expression is an inherited attribute expression, then the first of the following that applies:

    1. If the syntactic context is an inspection context or a node value context, then motionless;

    2. Otherwise, free-ranging.

    Note:

    An example is <xsl:value-of select="../@status"/>

  5. Otherwise, free-ranging

AxisStep [37]

The sweep of the expression is the first of the following that applies:

  1. If the PredicateList contains a Predicate that is not motionless, then free-ranging;

  2. If the axis is attribute or namespace and the syntactic context is a node value context or inspection context, then motionless;

  3. If the axis is self, then:

    1. If the syntactic context is an inspection context, then motionless;

    2. If the syntactic context is a node value context, then consuming;

  4. If the axis is parent, ancestor, or ancestor-or-self, and the syntactic context is an inspection context, then motionless;

  5. If the axis is child, and the syntactic context is a node value context or inspection context, then consuming;

  6. If the axis is descendant or descendant-or-self, and the syntactic context is an inspection context, then consuming;

  7. Otherwise, free-ranging.

Note:

This analysis does not attempt to classify para[title] as a consuming expression; an implementation might choose to do so.

Note:

When an AxisStep appears as part of a path expression, the classification of the path expression does not necessarily depend on how the AxisStep is classified.

ForwardStep [38]

A ForwardStep is analyzed as an AxisStep [37] with an empty PredicateList.

AbbrevForwardStep [40]

The expression is expanded so that it explicitly uses the child or attribute axis, and is then analyzed according to the rules for a ForwardStep.

ReverseStep [41]

A ReverseStep is analyzed as an AxisStep [37] with an empty PredicateList.

AbbrevReverseStep [43]

The expression is expanded to parent::node() and is then analyzed according to the rules for a ReverseStep [41].

PostfixExpr [47]

A PostFixExpr can be classified as either a filter expression or a dynamic function call depending on whether the last subexpression is a Predicate (in square brackets) or an ArgumentList (in parentheses).

For a filter expression of the form B[P] (where B might itself be a filter expression), the sweep is the first of the following that applies:

  1. If P is motionless, then the sweep of B;

  2. Otherwise, free-ranging.

For a dynamic function call, the general rule in 19.3.2 General Rules for Streamability applies.

Literal [52]

A Literal is motionless.

VarRef [54]

If the variable reference is a reference to a variable declared in a bind-group attribute of a containing xsl:for-each-group instruction, then:

  1. If all the following conditions are true then the sweep of the expression is group-consuming:

    1. The syntactic context is an inspection context or node value context;

    2. The xsl:for-each-group element in question is the nearest ancestor xsl:for-each-group

  2. Otherwise, the sweep of the expression is free-ranging

Otherwise, the sweep of the expression is motionless.

ParenthesizedExpr [56]

If there is no contained expression (the expression is ()), the sweep is motionless.

Otherwise, the sweep of the expression is the sweep of the contained expression

ContextItemExpr [57]

The sweep of the expression is the first of the following that applies:

  1. If the expression appears in an inspection context: motionless

  2. If the expression appears in a node value context: consuming

  3. Otherwise: free-ranging

FunctionCall [58]

Where a function takes the context item as the default value of an argument, and the argument is omitted, the analysis given here treats the expression as if . were supplied as an explicit argument.

Note:

The classification of the argument expressions is sensitive to their syntactic context: for example the argument to name(.) has a different sweep from the argument to format-number(.), which differs again from my:user-function(.).

If the function call is a partial function application (that is, one or more of the arguments is given as ?), then the sweep is free-ranging.

Otherwise, the sweep is determined as follows:

  1. If the function is root#0FO30, last#0FO30, current#0, current-group#0, then free-ranging;

  2. Otherwise, the function call is a first-order construct, and the general rule in 19.3.2 General Rules for Streamability applies.

NamedFunctionRef [62]

A NamedFunctionRef is motionless.

InlineFunctionExpr [63]

The sweep of the expression is the first of the following that applies:

  1. If the body of the inline function is group-consuming (that is, it contains a reference to a variable defined in the bind-group attribute of an xsl:for-each-group element external to the inline function), then free-ranging.

  2. Otherwise, motionless.

19.3.8 Incrementally consuming expressions

In certain contexts, such as the select attribute of an xsl:for-each, xsl:iterate, xsl:apply-templates, or xsl:for-each-group instruction within a streaming template, an expression is required that satisfies the following conditions:

  • The expression returns a sequence of nodes;

  • The nodes must be within the subtree rooted at the context node;

  • The nodes must be in document order;

  • The nodes must have disjoint sub-trees (which implies that no node in the sequence may have another node in the sequence as an ancestor or descendant);

  • A streaming processor can determine that a node is a member of the sequence on its first visit to the node, that is, when processing the start tag of an element.

An expression that can be statically guaranteed to deliver such a sequence of nodes is referred to as an incrementally consuming expression. To define this concept, we first introduce a subsidiary definition:

[Definition: An expression is a child-selection expression if it is any of the following:]

  1. a ForwardStepXP30 using the child axis

  2. a filter expression or axis step (see Section 3.2.1 Filter Expressions XP30) comprising a base expression that is a child-selection expression followed by one or more predicates each of which is motionless

  3. a union, except, or intersect expression (see Section 3.4.2 Combining Node Sequences XP30) whose operands are both child-selection expressions

[Definition: An expression is incrementally consuming if it satisfies any of the following conditions:]

  1. The expression is a child-selection expression.

  2. The expression is a path expression (RelativePathExprXP30) each of whose steps is an incrementally consuming expression, and each of whose operators is either / or ! (not //).

    Note:

    When applied to incrementally consuming expressions, the two operators / and ! are equivalent. The operator // is not allowed because it is capable of selecting two nodes one of which is an ancestor of the other.

  3. The expression is a call on the outermostFO30 function with an argument that is a consuming expression.

    Note:

    In the case of an instruction such as <xsl:apply-templates select="outermost(.//section)"/> where the path expression would otherwise select nodes whose subtrees are not disjoint, this selects the outermost sections for processing; the template rule for processing a section can then apply itself recursively to the next level of sections, and so on.

    Calling outermostFO30 can also be useful in cases where the selected nodes are not in fact nested. For example the call outermost(.//section/title) will in all likelihood select exactly the same elements as the expression .//section/title; but the former expression is streamable because the processor can determine statically that the selected elements have disjoint subtrees.

Note:

Implementations may recognize other kinds of expression as incrementally consuming, for example by making use of schema information.

Some examples of incrementally consuming expressions follow:

  • *

  • child::node()[not(self::comment())]

  • title

  • div/head

  • div/para[1]

  • (chap|appendix)/head

  • table[@class='data']!tbody!tr[1]!th

  • schema-element(div)[@class='para']

19.3.9 Inherited attribute expressions

During a streaming pass of a document, a processor is expected to retain in memory the attributes of the current node and of all its ancestors, and to make this information available using expressions of the form ../@status or ancestor::div[last()]/@id

However, the use of such expressions is restricted because further navigation from an ancestor node (for example, to its children) is not possible when streaming.

This restriction is achieved by defining this class of expression to be motionless provided that it appears in an node-value or inspection context.

[Definition:  An inherited attribute expression is an expression that satisfies all of the following conditions: ]

  1. The expression is a RelativePathExprXP30 consisting of one or more steps, in which every operator is / or ! (not //).

  2. The last step is an axis step using the attribute axis, in which every predicate is motionless.

  3. Every step before the last is an axis step using one of the axes parent, ancestor, ancestor-or-self, or self, and every predicate in such a step is motionless.

Some examples of attribute inheritance expressions follow:

  • @status

  • ../@status

  • ../../@*

  • ancestor::*[@xml:lang][1]/@xml:lang

Note:

Implementations may recognize other kinds of expression as attribute inheritance expressions, for example expressions that use the union, intersect, or except operators.

19.3.10 Classifying Patterns

The patterns used as match patterns in streaming templates and for the group-starting-with and group-ending-with instructions in an xsl:for-each-group instruction within a streaming template are required to be motionless patterns.

Informally, a motionless pattern is a pattern that can be evaluated by a streaming processor when the input stream is positioned at the start tag of an element, without advancing the input stream.

A pattern is motionless if it conforms to all the following restrictions:

  1. If it is a RootedPattern then it must start with / or // (not with a function call).

  2. Every Predicate in the pattern must satisfy all of the following constraints:

    1. The expression in the predicate must be motionless.

    2. The predicate must not contain a call on either of the functions positionFO30 or lastFO30.

    3. The expression in the predicate must be guaranteed to return a single boolean. Specifically, it must be one of the following:

      1. A function call on a function whose declared return type is xs:boolean with occurrence indicator either ? or absent.

      2. A QuantifiedExpr

      3. A non-trivial AndExpr or OrExpr

      4. A non-trivial ComparisonExpr

      5. A non-trivial InstanceofExpr or CastableExpr

      6. A ParenthesizedExpr that immediately contains one of the kinds of expression in this list.

      The term non-trivial is used here in the sense that an expression must match the production and must contain the operator that distinguishes it as belonging to this production and not to a more specific production: thus @status = 'live' is a non-trivial ComparisonExpr, unlike pqr and 'live' both of which match the ComparisonExpr production but lack the distinguishing operator.

A pattern that is not motionless is classified as free-ranging.

19.4 fn:copy-of

Summary

Returns a deep copy of the node supplied as the $node argument, or the context node if the argument is absent.

Signatures

copy-of() as node()
copy-of($node as node()?) as node()?
Properties

The zero-argument form of this function is nondeterministicFO30, focus-dependentFO30, and context-independentFO30.

The one-argument form of this function is nondeterministicFO30, focus-independentFO30, and context-independentFO30.

Rules

The zero-argument form of this function has the same effect as calling copy-of(.), that is, supplying the context item as an implicit argument.

The function returns a deep copy of the node supplied as the argument $node. If the argument is an empty sequence, the function returns an empty sequence. The effect is the same as that of the xsl:copy-of instruction with copy-namespaces set to yes and validation set to preserve.

If the function is called more than once with the same argument, it is implementation-dependent whether each call returns the same node, or whether multiple calls return different nodes. That is, the result of the expression copy-of($X) is copy-of($X) is implementation-dependent.

The copy-of function is available for use (and is primarily intended for use) when a source document is processed using streaming. It can also be used when not streaming. The effect is to take a copy of the subtree rooted at the current node, and to make this available as a normal tree, that can be processed without any of the restrictions that apply while streaming, for example only being able to process children once. The copy, of course, does not include siblings or ancestors of the context node, so any attempt to navigate to siblings or ancestors will result in an empty sequence being returned.

Examples

Using copy-of() while streaming:

This example copies from the source document all employees who work in marketing and are based in Dubai. Because there are two accesses using the child axis, it is not possible to do this without buffering each employee in memory, which can be achieved using the copy-of function.

<xsl:stream href="employees.xml">
  <xsl:sequence select="employees/employee/copy-of()
                          [department='Marketing' and location='Dubai']"/>
</xsl:stream>

19.5 fn:snapshot

Summary

Returns a copy of a node together with its ancestors and descendants and their attributes and namespaces.

Signatures

snapshot() as node()
snapshot($node as node()?) as node()?
Properties

The zero-argument form of this function is nondeterministicFO30, focus-dependentFO30, and context-independentFO30.

The one-argument form of this function is nondeterministicFO30, focus-independentFO30, and context-independentFO30.

Rules

The zero-argument form of this function has the same effect as calling snapshot(.), that is, supplying the context item as an implicit argument.

The function returns a snapshot of the node supplied as the argument $node. If the argument is an empty sequence, the function returns an empty sequence.

If the function is called more than once with the same argument, it is implementation-dependent whether each call returns the same node, or whether multiple calls return different nodes. That is, the result of the expression snapshot($X) is snapshot($X) is implementation-dependent.

[Definition: A snapshot of a node N is a deep copy of N, as produced by the xsl:copy-of instruction with copy-namespaces set to yes and validation set to preserve, with the additional property that for every ancestor of N, the copy also has a corresponding ancestor whose name, node-kind, and base URI are the same as the corresponding ancestor of N, and that has copies of the attributes and namespaces of the corresponding ancestor of N. But the ancestor has a type annotation of xs:anyType, has the properties nilled, is-ID, and is-IDREF set to false, and has no children other than the child that is a copy of N or one of its ancestors.]

More formally, a snapshot of a node is the result of the following function.

<xsl:function name="fn:snapshot" as="node()?">
  <xsl:param name="origin" as="node()?"/>
  
  <!-- create a copy of the tree containing the supplied node, retaining only
       * the supplied node with its attributes and namespaces
       * the ancestors of the supplied node with their attributes and namespaces
       * the descendants of the supplied node with their attributes and namespaces
       -->
  <xsl:variable name="root-copy" as="node()">
    <xsl:apply-templates select="root($origin)" mode="snapshot">
      <xsl:with-param name="origin" select="$origin" tunnel="yes"/>
    </xsl:apply-templates>
  </xsl:variable>
  
  <!-- find and return the node in the copied tree that corresponds to the origin node
       --> 
  <xsl:sequence select="($root-copy/descendant-or-self::node()/(.|@*|namespace::*)
      [f:corresponds(., $origin)]"/>
</xsl:function>

<xsl:template match="node()" mode="snapshot">
  <xsl:param name="origin" as="node()" tunnel="yes"/>
  <xsl:choose>
    <xsl:when test=". is $origin">
      <xsl:copy-of select="." validation="preserve"/>
    </xsl:when>
    <xsl:when test=". intersect $origin/ancestor::node()">
      <xsl:copy validation="strip">
        <xsl:copy-of select="@*" validation="preserve"/>
        <xsl:apply-templates mode="snapshot"/>
      </xsl:copy>
    </xsl:when>
    <xsl:otherwise/>
  </xsl:choose>
</xsl:template>

<!-- f:corresponds compares two nodes and returns true if all the following are true:
     * they are at the same depth in their respective trees
     * they have the same name (or none)
     * they have the same node kind
     The tests on node name and node kind are needed only when the origin node is an
     attribute or namespace.
     -->
<xsl:function name="f:corresponds" as="xs:boolean">
  <xsl:param name="node1" as="node()"/>
  <xsl:param name="node2" as="node()"/>
  <xsl:sequence select="
    count($node1/ancestor::node()) = count($node2/ancestor::node()) and
    deep-equal(node-name($node1), node-name($node2)) and
    f:node-kind($node1) = f:node-kind($node2)"/>    
</xsl:function>

<!-- f:node-kind returns a string identifying the node kind of the supplied node
     -->
<xsl:function name="f:node-kind" as="xs:string">
  <xsl:param name="node" as="node()"/>
  <xsl:choose>
    <xsl:when test="$node instance of document-node()">D</xsl:when>
    <xsl:when test="$node instance of element(*)">E</xsl:when>
    <xsl:when test="$node instance of attribute(*)">A</xsl:when>
    <xsl:when test="$node instance of text()">T</xsl:when>
    <xsl:when test="$node instance of comment()">C</xsl:when>
    <xsl:when test="$node instance of processing-instruction()">P</xsl:when>
    <xsl:when test="$node instance of namespace-node()">N</xsl:when>
  </xsl:choose>
</xsl:function>
 

The snapshot function is available for use (and is primarily intended for use) when a source document is processed using streaming. It can also be used when not streaming. The effect is to take a copy of the subtree rooted at the current node, along with copies of the ancestors and their attributes, and to make this available as a normal tree, that can be processed without any of the restrictions that apply while streaming, for example only being able to process children once. The copy, of course, does not include siblings of the context node or of its ancestors, so any attempt to navigate to these siblings will result in an empty sequence being returned.

Examples

Using snapshot() while streaming:

This example copies from the source document all employees who work in marketing and are based in Dubai. It assumes that employees are grouped by location. Because there are two accesses using the child axis (referencing department and salary), it is not possible to do this without buffering each employee in memory. The snapshot function is used in preference to the simpler copy-of so that access to attributes of the parent location element remains possible.

<xsl:stream href="employees.xml">
  <xsl:for-each select="locations/location[@name='Dubai']
                          /employee/snapshot()[department='Marketing']">
    <employee>
      <location code="{../@code}"/>
      <salary value="{salary}"/>
    </employee>
  </xsl:for-each>
</xsl:stream>

19.6 fn:point-copy

Summary

Returns a copy of a node together with its attributes and namespaces, but without ancestors or descendants.

Signatures

point-copy() as node()
point-copy($node as node()?) as node()?
Properties

The zero-argument form of this function is nondeterministicFO30, focus-dependentFO30, and context-independentFO30.

The one-argument form of this function is nondeterministicFO30, focus-independentFO30, and context-independentFO30.

Rules

The zero-argument form of this function has the same effect as calling point-copy(.), that is, supplying the context item as an implicit argument.

The function returns a point-copy of the node supplied as the argument $node. If the argument is an empty sequence, the function returns an empty sequence.

If the function is called more than once with the same argument, it is implementation-dependent whether each call returns the same node, or whether multiple calls return different nodes. That is, the result of the expression point-copy($X) is point-copy($X) is implementation-dependent.

[Definition: A point-copy of a node N is a node that has the same node kind, name, attribute values, in-scope namespaces, and base URI as N. The point-copy has no parent or siblings. If the type annotation of N is a simple type or a complex type with simple content, then the point-copy has the same type annotation, typed value and string value as N, and unless the string value is zero-length, a child text node whose content is the same as the string value (but with no comments or processing instructions among its children). If the type annotation of N is a complex type with complex content (including xs:anyType and xs:untyped) then the point-copy will have a type annotation of xs:untyped, a string value and typed value of a zero-length string, and no child nodes. ]

Notes

The point-copy is designed to be used when streaming, and in particular, when positioned at the start tag of an element. The rules cause the content of the element node to be retained in the case where it has simple content. The streamability rules classify this function as motionless, which means that the implementation requires a small amount of look-ahead; the intent is that calling the function does not change the state of the input stream.

19.7 fn:attributes

Summary

Returns the attributes of a node in the form of a map.

Signatures

attributes() as map(xs:anyAtomicType, xs:anyAtomicType*)
attributes($node as node()?) as map(xs:anyAtomicType, xs:anyAtomicType*)
Properties

The zero-argument form of this function is nondeterministicFO30, focus-dependentFO30, and context-independentFO30.

The one-argument form of this function is nondeterministicFO30, focus-independentFO30, and context-independentFO30.

Rules

The zero-argument form of this function has the same effect as calling attributes(.), that is, supplying the context item as an implicit argument.

The function returns a map whose keys are the names of the attributes of the supplied $node, and whose associated values are the atomized values of the attributes.

For an attribute whose name is in no namespace, the corresponding key will be an instance of xs:NCName holding the local name of the attribute. In other cases, the key will be an instance of xs:QName holding the qualified name.

Notes

If the supplied node is not an element node, the result will be an empty map.

The purpose of the function is to make retrieval of attributes convenient when streaming. Because the attribute values are returned in atomized form, there is no danger of attribute nodes being used as a base for uncontrolled navigation around the document, so the streamability analysis needs to impose fewer restrictions. For the purposes of streamability, the function is motionless.

The entry in the map holds the typed value of the attribute, not its string value.

Examples

An attribute whose name is unqualified can be retrieved with an expression of the form attributes()("status").

An attribute whose name is namespace-qualified can be retrieved with an expression of the form attributes()(xs:QName(XML_NAMESPACE, "lang").

19.8 fn:look-ahead

Summary

Returns a point copy of the first following sibling of the context node if there is one, or an empty sequence otherwise.

Signature

look-ahead() as node()?
Properties

This function is nondeterministicFO30, focus-dependentFO30, and context-independentFO30.

Rules

This function is intended for use while streaming. It provides information about the node that is the immediate following sibling of the current node, if there is one. Whitespace text nodes are not skipped, unless they have been stripped from the tree in advance.

The information is returned in the form of a point-copy of the immediately following sibling node.

If the function is called more than once with the same argument, it is implementation-dependent whether each call returns the same node, or whether multiple calls return different nodes. That is, the result of the expression look-ahead() is look-ahead() is implementation-dependent.

The rules for streamability permit this function to be called only in the post-descent part of a streaming template, that is, in the part of the code that is evaluated after the content of the context node has been consumed.

Notes

One use case is simply to test whether the current node is the last in a sequence of siblings; another is to test whether the context node is followed by a node of a particular name.

Examples

The following expression tests whether the current node is the last in a sequence of siblings, and if so, outputs a horizontal rule:

<xsl:if test="not(look-ahead())"><hr/></xsl:if>               
               

The following code outputs a horizontal rule between any two elements whose names differ:

<xsl:if test="name(.) != name(look-ahead())"><hr/></xsl:if>               
               

20 Additional Functions

This section describes XSLT-specific additions to the core function library. Some of these additional functions also make use of information specified by declarations in the stylesheet; this section also describes these declarations.

20.1 fn:document

Summary

Provides access to XML documents identified by a URI.

Signatures

document($uri-sequence as item()*) as node()*
document( $uri-sequence  as item()*,
$base-node  as node()) as node()*
Properties

The one-argument form of this function is deterministicFO30, focus-independentFO30, and context-dependentFO30. It depends on dynamic base uri.

The two-argument form of this function is deterministicFO30, focus-independentFO30, and context-independentFO30.

Rules

The document function allows access to XML documents identified by a URI.

The first argument contains a sequence of URI references. The second argument, if present, is a node whose base URI is used to resolve any relative URI references contained in the first argument.

A sequence of absolute URI references is obtained as follows.

  • For an item in $uri-sequence that is an instance of xs:string, xs:anyURI, or xs:untypedAtomic, the value is cast to xs:anyURI. If the resulting URI reference is an absolute URI reference then it is used as is. If it is a relative URI reference, then it is resolved against the base URI of $base-node if supplied, or against the base URI from the static context otherwise (this will usually be the base URI of the stylesheet module). A relative URI reference is resolved against a base URI using the rules defined in [RFC3986].

  • For an item in $uri-sequence that is a node, the node is atomized. The result must be a sequence whose items are all instances of xs:string, xs:anyURI, or xs:untypedAtomic. Each of these values is cast to xs:anyURI, and if the resulting URI reference is an absolute URI reference then it is used as is. If it is a relative URI reference, then it is resolved against the base URI of $base-node if supplied, or against the base URI of the node that contained it otherwise.

Each of these absolute URI references is then processed as follows. Any fragment identifier that is present in the URI reference is removed, and the resulting absolute URI is cast to a string and then passed to the docFO30 function defined in [Functions and Operators]. This returns a document node. If an error occurs during evaluation of the docFO30 function, the processor may either signal this error in the normal way, or may recover by ignoring the failure, in which case the failing URI will not contribute any nodes to the result of the document function.

If the URI reference contained no fragment identifier, then this document node is included in the sequence of nodes returned by the document function.

If the URI reference contained a fragment identifier, then the fragment identifier is interpreted according to the rules for the media type of the resource representation identified by the URI, and is used to select zero or more nodes that are descendant-or-self nodes of the returned document node. As described in 2.3 Initiating a Transformation, the media type is available as part of the evaluation context for a transformation.

The sequence of nodes returned by the function is in document order, with no duplicates. This order has no necessary relationship to the order in which URIs were supplied in the $uri-sequence argument.

Error Conditions

[ERR XTRE1160] When a URI reference contains a fragment identifier, it is a recoverable dynamic error if the media type is not one that is recognized by the processor, or if the fragment identifier does not conform to the rules for fragment identifiers for that media type, or if the fragment identifier selects something other than a sequence of nodes (for example, if it selects a range of characters within a text node). The optional recovery action is to ignore the fragment identifier and return the document node. The set of media types recognized by a processor is implementation-defined.

[ERR XTDE1162] When a URI reference is a relative reference, it is a dynamic error if no base URI is available to resolve the relative reference. This can arise for example when the URI is contained in a node that has no base URI (for example a parentless text node), or when the second argument to the function is a node that has no base URI, or when the base URI from the static context is undefined.

Notes

One effect of these rules is that unless XML entities or xml:base are used, and provided that the base URI of the stylesheet module is known, document("") refers to the document node of the containing stylesheet module (the definitive rules are in [RFC3986]). The XML resource containing the stylesheet module is processed exactly as if it were any other XML document, for example there is no special recognition of xsl:text elements, and no special treatment of comments and processing instructions.

The XPath rules for function calling ensure that it is a type error if the supplied value of the second argument is anything other than a single node. If XPath 1.0 compatibility mode is enabled, then a sequence of nodes may be supplied, and the first node in the sequence will be used.

20.2 Keys

Keys provide a way to work with documents that contain an implicit cross-reference structure. They make it easier to locate the nodes within a document that have a given value for a given attribute or child element, and they provide a hint to the implementation that certain access paths in the document need to be efficient.

20.2.1 The xsl:key Declaration

<!-- Category: declaration -->
<xsl:key
  name = eqname
  match = pattern
  use? = expression
  composite? = "yes" | "no"
  collation? = uri >
  <!-- Content: sequence-constructor -->
</xsl:key>

The xsl:key declaration is used to declare keys. The name attribute specifies the name of the key. The value of the name attribute is an EQName, which is expanded as described in 5.1 Qualified Names. The match attribute is a Pattern; an xsl:key element applies to all nodes that match the pattern specified in the match attribute.

[Definition: A key is defined as a set of xsl:key declarations in the same package that share the same name.]

The key name is scoped to the containing package, and is available for use in calls to the key function within that package.

The value of the key may be specified either using the use attribute or by means of the contained sequence constructor.

[ERR XTSE1205] It is a static error if an xsl:key declaration has a use attribute and has non-empty content, or if it has empty content and no use attribute.

If the use attribute is present, its value is an expression specifying the values of the key. The expression will be evaluated with a singleton focus based on the node that matches the pattern. The result of evaluating the expression is atomized.

Similarly, if a sequence constructor is present, it is used to determine the values of the key. The sequence constructor will be evaluated with the node that matches the pattern as the context node. The result of evaluating the sequence constructor is atomized.

[Definition: The expression in the use attribute and the sequence constructor within an xsl:key declaration are referred to collectively as the key specifier. The key specifier determines the values that may be used to find a node using this key.]

When evaluation of the key specifier results in a sequence (after atomization) containing more than one atomic value, the effect depends on the value of the composite attribute:

  • When the attribute is absent or has the value no, each atomic value in the sequence acts as an individual key. For example, if match="book" use="author" composite="no" is specified, then a book element may be located using the value of any author element.

  • When the attribute is present and has the value yes, the sequence of atomic values is treated as a composite key that must be matched in its entirety. For example, if match="book" use="author" composite="yes" is specified, then a book element may be located using the value of all its author elements, supplied in the correct order.

If there are several xsl:key declarations in the same package with the same key name, then they must all have the same effective value for their composite attribute. The effective value is the actual value of the attribute if present, or "no" if the attribute is absent.

Note:

There is no requirement that all the values of a key should have the same type.

The presence of an xsl:key declaration makes it easy to find a node that matches the match pattern if any of the values of the key specifier (when applied to that node) are known. It also provides a hint to the implementation that access to the nodes by means of these values needs to be efficient (many implementations are likely to construct an index or hash table to achieve this). Note that the key specifier in general returns a sequence of values, and any one of these may be used to locate the node.

Note:

An xsl:key declaration is not bound to a specific source document. The source document to which it applies is determined only when the key function is used to locate nodes using the key. Keys can be used to locate nodes within any source document (including temporary trees), but each use of the key function searches one document only.

The optional collation attribute is used only when deciding whether two strings are equal for the purposes of key matching. Specifically, two key values $a and $b are considered equal if the result of the function call deep-equal($a, $b, $collation) is true. The effective collation for an xsl:key declaration is the collation specified in its collation attribute if present, resolved against the base URI of the xsl:key element, or the default collation that is in scope for the xsl:key declaration otherwise; the effective collation must be the same for all the xsl:key declarations making up a key.

[ERR XTSE1210] It is a static error if the xsl:key declaration has a collation attribute whose value (after resolving against the base URI) is not a URI recognized by the implementation as referring to a collation.

[ERR XTSE1220] It is a static error if there are several xsl:key declarations in the same package with the same key name and different effective collations. Two collations are the same if their URIs are equal under the rules for comparing xs:anyURI values, or if the implementation can determine that they are different URIs referring to the same collation.

[ERR XTSE1222] It is a static error if there are several xsl:key declarations in the stylesheet with the same key name and different effective values for the composite attribute.

It is possible to have:

  • multiple xsl:key declarations with the same name;

  • a node that matches the match patterns of several different xsl:key declarations, whether these have the same key name or different key names;

  • a node that returns more than one value from its key specifier (which can be treated either as separate individual key values, or as a single composite key value);

  • a key value that identifies more than one node (the key values for different nodes do not need to be unique).

An xsl:key declaration with higher import precedence does not override another of lower import precedence; all the xsl:key declarations in the stylesheet are effective regardless of their import precedence.

20.2.2 fn:key

Summary

Returns the nodes that match a supplied key value.

Signatures

key( $key-name  as xs:string,
$key-value  as xs:anyAtomicType*) as node()*
key( $key-name  as xs:string,
$key-value  as xs:anyAtomicType*,
$top  as node()) as node()*
Properties

The two-argument form of this function is deterministicFO30, focus-dependentFO30, and context-dependentFO30.

The three-argument form of this function is deterministicFO30, focus-independentFO30, and context-dependentFO30.

Rules

The key function does for keys what the element-with-idFO30 function does for IDs.

The $key-name argument specifies the name of the key. The value of the argument must be a lexical QName, which is expanded as described in 5.1 Qualified Names.

The $key-value argument to the key function is considered as a sequence. The effect depends on the value of the composite attribute of the corresponding xsl:key declaration.

  • If composite is no or absent, the set of requested key values is formed by atomizing the supplied value of the argument, using the standard function conversion rules. Each of the resulting atomic values is considered as a requested key value. The result of the function is a sequence of nodes, in document order and with duplicates removed, comprising those nodes in the selected subtree (see below) that are matched by an xsl:key declaration whose name is the same as the supplied key name, where the result of evaluating the key specifier contains a value that is equal to one of these requested key values, under the rules appropriate to the XPath eq operator for the two values in question, using the collation attributes of the xsl:key declaration when comparing strings. No error is reported if two values are encountered that are not comparable; they are regarded for the purposes of this function as being not equal.

    If the second argument is an empty sequence, the result of the function will be an empty sequence.

  • If composite is yes, the requested key value is the sequence formed by atomizing the supplied value of the argument, using the standard function conversion rules. The result of the function is a sequence of nodes, in document order and with duplicates removed, comprising those nodes in the selected subtree (see below) that are matched by an xsl:key declaration whose name is the same as the supplied key name, where the result of evaluating the key specifier is deep-equal to the requested key value, under the rules appropriate to the deep-equalFO30 function applied to the two values in question, using the collation attributes of the xsl:key declaration when comparing strings. Note that the deep-equalFO30 function reports no error if two values are encountered that are not comparable; they are regarded for the purposes of this function as being not equal.

    If the second argument is an empty sequence, the result of the function will be the set of nodes having an empty sequence as the value of the key specifier.

Different rules apply when XSLT 1.0 compatible behavior is enabled. Specifically, if any of the xsl:key elements in the definition of the key is processed with XSLT 1.0 behavior, and if the effective value of the composite attribute is no, then the value of the key specifier and the value of the second argument of the key function are both converted after atomization to a sequence of strings, by applying a cast to each item in the sequence, before performing the comparison.

The third argument is used to identify the selected subtree. If the argument is present, the selected subtree is the set of nodes that have $top as an ancestor-or-self node. If the argument is omitted, the selected subtree is the document containing the context node. This means that the third argument effectively defaults to /.

The result of the key function can be described more specifically as follows. The result is a sequence containing every node $N that satisfies the following conditions:

  • $N/ancestor-or-self::node() intersect $top is non-empty. (If the third argument is omitted, $top defaults to /)

  • $N matches the pattern specified in the match attribute of an xsl:key declaration whose name attribute matches the name specified in the $key-name argument.

  • When composite="no", and the key specifier of that xsl:key declaration is evaluated with a singleton focus based on $N, the atomized value of the resulting sequence includes a value that compares equal to at least one item in the atomized value of the sequence supplied as $key-value, under the rules of the eq operator with the collation selected as described above.

    When composite="yes", and the key specifier of that xsl:key declaration is evaluated with a singleton focus based on $N, the atomized value of the resulting sequence compares equal to the atomized value of the sequence supplied as $key-value, under the rules of the deep-equalFO30 function with the collation selected as described above.

The sequence returned by the key function will be in document order, with duplicates (that is, nodes having the same identity) removed.

Error Conditions

[ERR XTDE1260] It is a non-recoverable dynamic error if the value is not a valid QName, or if there is no namespace declaration in scope for the prefix of the QName, or if the name obtained by expanding the QName is not the same as the expanded name of any xsl:key declaration in the containing package. If the processor is able to detect the error statically (for example, when the argument is supplied as a string literal), then the processor may optionally signal this as a static error.

[ERR XTDE1270] It is a non-recoverable dynamic error to call the key function with two arguments if there is no context node, or if the root of the tree containing the context node is not a document node; or to call the function with three arguments if the root of the tree containing the node supplied in the third argument is not a document node.

Notes

Untyped atomic values are converted to strings, not to the type of the other operand. This means, for example, that if the expression in the use attribute returns a date, supplying an untyped atomic value in the call to the key function will return an empty sequence.

Examples
Example: Using a Key to Follow Cross-References

Given a declaration

<xsl:key name="idkey" match="div" use="@id"/>

an expression key("idkey",@ref) will return the same nodes as id(@ref), assuming that the only ID attribute declared in the XML source document is:

<!ATTLIST div id ID #IMPLIED>

and that the ref attribute of the context node contains no whitespace.

 

Example: Using a Key to Generate Hyperlinks

Suppose a document describing a function library uses a prototype element to define functions

<prototype name="sqrt" return-type="xs:double">
  <arg type="xs:double"/>
</prototype>

and a function element to refer to function names

<function>sqrt</function>

Then the stylesheet could generate hyperlinks between the references and definitions as follows:

<xsl:key name="func" match="prototype" use="@name"/>

<xsl:template match="function">
<b>
  <a href="#{generate-id(key('func',.))}">
    <xsl:apply-templates/>
  </a>
</b>
</xsl:template>

<xsl:template match="prototype">
  <p>
    <a name="{generate-id()}">
      <b>Function: </b>
      ...
    </a>
  </p>
  </xsl:template>

When called with two arguments, the key function always returns nodes that are in the same document as the context node. To retrieve a node from any other document, it is necessary either to change the context node, or to supply a third argument.

Example: Using Keys to Reference other Documents

For example, suppose a document contains bibliographic references in the form <bibref>XSLT</bibref>, and there is a separate XML document bib.xml containing a bibliographic database with entries in the form:

<entry name="XSLT">...</entry>

Then the stylesheet could use the following to transform the bibref elements:

<xsl:key name="bib" match="entry" use="@name"/>

<xsl:template match="bibref">
  <xsl:variable name="name" select="."/>
  <xsl:apply-templates select="document('bib.xml')/key('bib',$name)"/>
</xsl:template>

Note:

This relies on the ability in XPath 2.0 to have a function call on the right-hand side of the / operator in a path expression.

The following code would also work:

<xsl:key name="bib" match="entry" use="@name"/>

<xsl:template match="bibref">
  <xsl:apply-templates select="key('bib', ., document('bib.xml'))"/>
</xsl:template>

 

Example: Using a Composite Key

This example uses a composite key consisting of first name and last name to locate employees in an employee file.

The key can be defined like this:

<xsl:key name="emp-name-key" 
         match="employee" 
         use="name/first, name/last" 
         composite="yes"/>                     
         

A particular employee can then be located using the function call:

key('emp-name-key', ('Tim', 'Berners-Lee'), doc('employees.xml'))

20.3 Defining a Decimal Format

The definition of the format-numberFO30 function is now in [Functions and Operators]. What remains here is the definition of the xsl:decimal-format declaration, which provides the context for this function when used in an XSLT stylesheet.

<!-- Category: declaration -->
<xsl:decimal-format
  name? = eqname
  decimal-separator? = char
  grouping-separator? = char
  infinity? = string
  minus-sign? = char
  NaN? = string
  percent? = char
  per-mille? = char
  zero-digit? = char
  digit? = char
  pattern-separator? = char />

The xsl:decimal-format element controls the interpretation of a picture string used by the format-numberFO30 function.

[Definition: The picture string is the string supplied as the second argument of the format-numberFO30 function.]

Note:

The format-numberFO30 function, previously defined in this specification, is now a core function defined in [Functions and Operators].

A package may contain multiple xsl:decimal-format declarations and may include or import stylesheet modules that also contain xsl:decimal-format declarations. The name of an xsl:decimal-format declaration is the value of its name attribute, if any.

[Definition: All the xsl:decimal-format declarations in a package that share the same name are grouped into a named decimal format; those that have no name are grouped into a single unnamed decimal format.]

The scope of an xsl:decimal-format name is the package in which it is declared; the name is available for use only in calls to format-numberFO30 that appear within the same package.

If a package does not contain a declaration of the unnamed decimal format, a declaration equivalent to an xsl:decimal-format element with no attributes is implied.

The attributes of the xsl:decimal-format declaration establish values for a number of variables used as input to the algorithm followed by the format-numberFO30 function. An outline of the purpose of each attribute is given below; however, the definitive explanations are given as part of the specification of format-numberFO30.

For any named decimal format, the effective value of each attribute is taken from an xsl:decimal-format declaration that has that name, and that specifies an explicit value for the required attribute. If there is no such declaration, the default value of the attribute is used. If there is more than one such declaration, the one with highest import precedence is used.

For any unnamed decimal format, the effective value of each attribute is taken from an xsl:decimal-format declaration that is unnamed, and that specifies an explicit value for the required attribute. If there is no such declaration, the default value of the attribute is used. If there is more than one such declaration, the one with highest import precedence is used.

[ERR XTSE1290] It is a static error if a named or unnamed decimal format contains two conflicting values for the same attribute in different xsl:decimal-format declarations having the same import precedence, unless there is another definition of the same attribute with higher import precedence.

The following attributes control the interpretation of characters in the picture string supplied to the format-numberFO30 function, and also specify characters that may appear in the result of formatting the number. In each case the value must be a single character [see ERR XTSE0020].

  • decimal-separator specifies the character used for the decimal-separator-sign; the default value is the period character (.)

  • grouping-separator specifies the character used for the grouping-sign, which is typically used as a thousands separator; the default value is the comma character (,)

  • percent specifies the character used for the percent-sign; the default value is the percent character (%)

  • per-mille specifies the character used for the per-mille-sign; the default value is the Unicode per-mille character (#x2030)

  • zero-digit specifies the character used for the digit-zero-sign; the default value is the digit zero (0). This character must be a digit (category Nd in the Unicode property database), and it must have the numeric value zero. This attribute implicitly defines the Unicode character that is used to represent each of the values 0 to 9 in the final result string: Unicode is organized so that each set of decimal digits forms a contiguous block of characters in numerical sequence.

[ERR XTSE1295] It is a static error if the character specified in the zero-digit attribute is not a digit or is a digit that does not have the numeric value zero.

The following attributes control the interpretation of characters in the picture string supplied to the format-numberFO30 function. In each case the value must be a single character [see ERR XTSE0020].

  • digit specifies the character used for the digit-sign in the picture string; the default value is the number sign character (#)

  • pattern-separator specifies the character used for the pattern-separator-sign, which separates positive and negative sub-pictures in a picture string; the default value is the semi-colon character (;)

The following attributes specify characters or strings that may appear in the result of formatting the number:

  • infinity specifies the string used for the infinity-symbol; the default value is the string Infinity

  • NaN specifies the string used for the NaN-symbol, which is used to represent the value NaN (not-a-number); the default value is the string NaN

  • minus-sign specifies the character used for the minus-symbol; the default value is the hyphen-minus character (-, #x2D). The value must be a single character.

[ERR XTSE1300] It is a static error if, for any named or unnamed decimal format, the variables representing characters used in a picture string do not each have distinct values. These variables are decimal-separator-sign, grouping-sign, percent-sign, per-mille-sign, digit-zero-sign, digit-sign, and pattern-separator-sign.

Every (named or unnamed) decimal format defined in a package is added to the statically known decimal formatsXP30 in the static contextXP30 of every expression in the package, excluding expressions appearing in [xsl:]use-when attributes.

20.4 Miscellaneous Additional Functions

20.4.1 fn:current

Summary

Returns the item that is the context item for the evaluation of the containing XPath expression

Signature

current() as item()
Properties

This function is deterministicFO30, context-dependentFO30, and focus-dependentFO30.

Rules

The current function, used within an XPath expression, returns the item that was the context item at the point where the expression was invoked from the XSLT stylesheet. This is referred to as the current item. For an outermost expression (an expression not occurring within another expression), the current item is always the same as the context item. Thus,

<xsl:value-of select="current()"/>

means the same as

<xsl:value-of select="."/>

However, within square brackets, or on the right-hand side of the / operator, the current item is generally different from the context item.

If the current function is used within a pattern, its value is the item that is being matched against the pattern.

Error Conditions

[ERR XTDE1360] If the current function is evaluated within an expression that is evaluated when the context item is absent, a non-recoverable dynamic error occurs.

Examples

The instruction:

<xsl:apply-templates select="//glossary/entry[@name=current()/@ref]"/>

will process all entry elements that have a glossary parent element and that have a name attribute with value equal to the value of the current item's ref attribute. This is different from

<xsl:apply-templates select="//glossary/entry[@name=./@ref]"/>

which means the same as

<xsl:apply-templates select="//glossary/entry[@name=@ref]"/>

and so would process all entry elements that have a glossary parent element and that have a name attribute and a ref attribute with the same value.

20.4.2 fn:unparsed-entity-uri

Summary

Returns the URI (system identifier) of an unparsed entity

Signature

unparsed-entity-uri($entity-name as xs:string) as xs:anyURI
Properties

This function is deterministicFO30, focus-dependentFO30, and context-independentFO30.

Rules

The unparsed-entity-uri function returns the URI of the unparsed entity whose name is given by the value of the $entity-name argument, in the document containing the context node. It returns the zero-length xs:anyURI if there is no such entity. This function maps to the dm:unparsed-entity-system-id accessor defined in [Data Model].

Error Conditions

[ERR XTDE1370] It is a non-recoverable dynamic error if the unparsed-entity-uri function is called when there is no context node, or when the root of the tree containing the context node is not a document node.

20.4.3 fn:unparsed-entity-public-id

Summary

Returns the public identifier of an unparsed entity

Signature

unparsed-entity-public-id($entity-name as xs:string) as xs:anyURI
Properties

This function is deterministicFO30, focus-dependentFO30, and context-independentFO30.

Rules

The unparsed-entity-public-id function returns the public identifier of the unparsed entity whose name is given by the value of the $entity-name argument, in the document containing the context node. It returns the zero-length string if there is no such entity, or if the entity has no public identifier. This function maps to the dm:unparsed-entity-public-id accessor defined in [Data Model].

Error Conditions

[ERR XTDE1380] It is a non-recoverable dynamic error if the unparsed-entity-public-id function is called when there is no context node, or when the root of the tree containing the context node is not a document node.

20.4.4 system-property

Summary
Signature
Rules

21 XPath Extensions

XSLT 3.0 extends the type system and data model of XPath 3.0 with additional datatypes and associated functions and operators defined in this section.

21.1 Maps

A map is an additional kind of item.

[Definition: A map comprises a collation and a set of entries. Each entry comprises a key which is an arbitrary atomic value, and an arbitrary sequence called the associated value. Within a map, no two entries have the same key, when compared using the eq operator under the map's collation. It is not necessary that all the keys should be mutually comparable (for example, they can include a mixture of integers and strings). Key values will never be of type xs:untypedAtomic, and they will never be the xs:float or xs:double value NaN.]

The function call map:get($map, $key) can be used to retrieve the value associated with a given key.

A map can also be viewed as a function from keys to associated values. To achieve this, a map is also a function item. The function corresponding to the map has the signature function($key as xs:anyAtomicValue) as item()*. Calling the function has the same effect as calling the get function: the expression $map($key) returns the same result as get($map, $key). For example, if $books-by-isbn is a map whose keys are ISBNs and whose associated values are book elements, then the expression $books-by-isbn("0470192747") returns the book element with the given ISBN. The fact that a map is a function item allows it to be passed as an argument to higher-order functions that expect a function item as one of their arguments.

Like all other values, maps are immutable. For example, the map:remove function creates a new map by removing an entry from an existing map, but the existing map is not changed by the operation.

Like sequences, maps have no identity. It is meaningful to compare the contents of two maps, but there is no way of asking whether they are "the same map": two maps with the same content are indistinguishable.

21.1.1 The Type of a Map

The syntax of ItemTypeXP30 as defined in XPath is extended as follows:

MapType
[17]    ItemType    ::=    ... | MapType
[18]    MapType    ::=    'map' '(' ( '*' | (AtomicOrUnionTypeXP30 ',' SequenceTypeXP30) ')'

The ItemType map(K, V) matches an item M if (a) M is a map, and (b) every entry in M has a key that matches K and an associated value that matches V. For example, map(xs:integer, element(employee)) matches a map if all the keys in the map are integers, and all the associated values are employee elements. Note that a map (like a sequence) carries no intrinsic type information separate from the types of its entries, and the type of existing entries in a map does not constrain the type of new entries that can be added to the map.

The ItemType map(*) is equivalent to map(xs:anyAtomicType, item()*), and matches any map regardless of its contents.

Because a map is a function, the type map(K, V) is derived from function(K) as V, and instances of map(K, V) can be used wherever the required type is function(K) as V.

21.1.2 Functions that operate on Maps

The functions defined in this section use a conventional namespace prefix map, which is assumed to be bound to the namespace URI http://www.w3.org/2011/xpath-functions/map.

There is no operation to atomize a map or convert it to a string.

The number of entries in the map may be obtained as count(map:keys($map)).

21.1.2.1 map:new
Summary

Creates a new map: either an empty map, or a map that combines entries from a number of existing maps.

Signatures

new() as map(*)
new($maps as map(*)*) as map(*)
new( $maps  as map(*)*,
$collation  as xs:string) as map(*)
Properties

This function is deterministicFO30, context-dependentFO30, and focus-independentFO30. It depends on collations.

Rules

The function map:new constructs and returns a new map.

The zero-argument form of the function returns an empty map whose collation is the default collation in the static context. It is equivalent to calling the one-argument form of the function with an empty sequence as the value of the first argument.

The one-argument form of the function returns a map that is formed by combining the contents of the maps supplied in the $input argument. It is equivalent to calling the two-argument form of the function with the default collation from the static context as the second argument.

The two-argument form of the function returns a map that is formed by combining the contents of the maps supplied in the $input argument. The collation of the new map is the value of the $collation argument. The supplied maps are combined as follows:

  1. There is one entry in the new map for each distinct key value present in the union of the input maps, where keys are considered distinct according to the rules of the fn:distinct-values function with $collation as the collation.

  2. The associated value for each such key is taken from the last map in the input sequence $input that contains an entry with this key. If this map contains more than one entry with this key (which can happen if its collation is different from that of the new map) then it is implementation-dependent which of them is selected.

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

Examples

let $week := map{0:="Sonntag", 1:="Montag", 2:="Dienstag", 3:="Mittwoch", 4:="Donnerstag", 5:="Freitag", 6:="Samstag"}

The expression map:new() returns map{}. (Returns an empty map, whose collation is the default collation from the static context).

The expression map:new(()) returns map{}. (Returns an empty map, whose collation is the default collation from the static context).

The expression map:new((map:entry(0, "no"), map:entry(1, "yes"))) returns map{0:="no", 1:="yes"}. (Returns a map with two entries; the collation of the map is the default collation from the static context).

The expression map:new((map:entry(0, "no"), map:entry(1, "yes"))) returns map{0:="no", 1:="yes"}. (Returns a map with two entries; the collation of the map is the default collation from the static context).

The expression map:new(($week, map{7:="Unbekannt"})) returns map{0:="Sonntag", 1:="Montag", 2:="Dienstag", 3:="Mittwoch", 4:="Donnerstag", 5:="Freitag", 6:="Samstag", 7:="Unbekannt"}. (The value of the existing map is unchanged; a new map is created containing all the entries from $week, supplemented with a new entry.).

The expression map:new(($week, map{6:="Sonnabend"})) returns map{0:="Sonntag", 1:="Montag", 2:="Dienstag", 3:="Mittwoch", 4:="Donnerstag", 5:="Freitag", 6:="Sonnabend"}. (The value of the existing map is unchanged; a new map is created containing all the entries from $week, with one entry replaced by a new entry. Both input maps contain an entry with the key value 6; the one used in the result is the one that comes last in the input sequence.).

The expression map:new((map{"A":=1}, map{"a":=2}), "http://collation.example.com/caseblind") returns map{"a":=2}. (Assuming that the keys of the two entries are equal under the rules of the chosen collation, only one of the entries can appear in the result; the one that is chosen is the one from the last map in the input sequence. If both entries were in the same map, it would be implementation-dependent which was chosen.).

21.1.2.2 map:collation
Summary

Returns the URI of the supplied map's collation

Signature

collation($input as map(*)) as xs:string
Properties

This function is deterministicFO30, context-independentFO30, and focus-independentFO30.

Rules

The function map:collation returns the collation URI of the map supplied as $input.

Examples

The expression map:collation(map:new((), "http://collation.example.com/caseblind")) returns "http://collation.example.com/caseblind".

21.1.2.3 map:keys
Summary

Returns a sequence containing all the key values present in a map

Signature

keys($input as map(*)) as xs:anyAtomicType*
Properties

This function is deterministicFO30, context-independentFO30, and focus-independentFO30.

Rules

The function map:keys takes any map as its $input argument and returns the keys that are present in the map as a sequence of atomic values, in implementation-dependent order.

Examples

The expression map:keys(map{1:="yes", 2:="no"}) returns some permutation of (1,2). (The result is in implementation-dependent order.).

21.1.2.4 map:contains
Summary

Tests whether a supplied map contains an entry for a given key

Signature

contains( $map  as map(*),
$key  as xs:anyAtomicType) as xs:boolean
Properties

This function is deterministicFO30, context-independentFO30, and focus-independentFO30.

Rules

The function map:contains returns true if the map supplied as $map contains an entry with a key equal to the supplied value of $key; otherwise it returns false. The equality comparison uses the map's collation; no error occurs if the map contains keys that are not comparable with the supplied $key.

If the supplied key is xs:untypedAtomic, it is converted to xs:string. If the supplied key is the xs:float or xs:double value NaN, the function returns false.

Examples

let $week := map{0:="Sonntag", 1:="Montag", 2:="Dienstag", 3:="Mittwoch", 4:="Donnerstag", 5:="Freitag", 6:="Samstag"}

The expression map:contains($week, 2) returns true().

The expression map:contains($week, 9) returns false().

The expression map:contains(map{}, "xyz") returns false().

The expression map:contains(map{"xyz":=23}, "xyz") returns true().

The expression map:contains(map{"abc":=23, "xyz":=()}, "xyz") returns true().

21.1.2.5 map:get
Summary

Returns the value associated with a supplied key in a given map.

Signature

get( $map  as map(*),
$key  as xs:anyAtomicType) as item()*
Properties

This function is deterministicFO30, context-independentFO30, and focus-independentFO30.

Rules

The function map:get attempts to find an entry within the map supplied as $input that has a key equal to the supplied value of $key. If there is such an entry, it returns the associated value; otherwise it returns an empty sequence. The equality comparison uses the map's collation; no error occurs if the map contains keys that are not comparable with the supplied $key.

If the supplied key is xs:untypedAtomic, it is converted to xs:string. If the supplied key is the xs:float or xs:double value NaN, the function returns an empty sequence.

Notes

A return value of () from map:get could indicate that the key is present in the map with an associated value of (), or it could indicate that the key is not present in the map. The two cases can be distinguished by calling map:contains.

Invoking the map as a function item has the same effect as calling get: that is, when $map is a map, the expression $map($K) is equivalent to get($map, $K). Similarly, the expression get(get(get($map, 'employee'), 'name'), 'first') can be written as $map('employee')('name')('first').

Examples

let $week := map{0:="Sonntag", 1:="Montag", 2:="Dienstag", 3:="Mittwoch", 4:="Donnerstag", 5:="Freitag", 6:="Samstag"}

The expression map:get($week, 4) returns "Donnerstag".

The expression map:get($week, 9) returns (). (When the key is not present, the function returns an empty sequence.).

The expression map:get(map:entry(7,()), 7) returns (). (An empty sequence as the result can also signify that the key is present and the associated value is an empty sequence.).

21.1.2.6 map:entry
Summary

Creates a map that contains a single entry (a key-value pair).

Signature

entry( $key  as xs:anyAtomicType,
$value  as item()*) as map(*)
Properties

This function is deterministicFO30, context-independentFO30, and focus-independentFO30.

Rules

The function map:entry returns a new map which normally contains a single entry. The collation of the new map is the default collation from the static context. The key of the entry in the new map is $key, and its associated value is $value.

If the supplied key is the xs:float or xs:double value NaN, the supplied $map is empty (that is, it contains no entries).

If the supplied key is xs:untypedAtomic, it is converted to xs:string.

Notes

The function map:entry is intended primarily for use in conjunction with the function map:new. For example, a map containing seven entries may be constructed like this:

map:new((
   map:entry("Su", "Sunday"),
   map:entry("Mo", "Monday"),
   map:entry("Tu", "Tuesday"),
   map:entry("We", "Wednesday"),
   map:entry("Th", "Thursday"),
   map:entry("Fr", "Friday"),
   map:entry("Sa", "Saturday")
   ))

Unlike the map{...} expression, this technique can be used to construct a map with a variable number of entries, for example:

map:new(for $b in //book return map:entry($b/isbn, $b))
Examples

The expression map:entry("M", "Monday") returns map{"M":="Monday"}.

21.1.2.7 map:remove
Summary

Constructs a new map by removing an entry from an existing map

Signature

remove( $map  as map(*),
$key  as xs:anyAtomicType) as map(*)
Properties

This function is deterministicFO30, context-independentFO30, and focus-independentFO30.

Rules

The function map:remove returns a new map. The collation of the new map is the same as the collation of the map supplied as $map. The entries in the new map correspond to the entries of $map, excluding any entry whose key is equal to $key.

No failure occurs if the input map contains no entry with the supplied key; the input map is returned unchanged

Examples

let $week := map{0:="Sonntag", 1:="Montag", 2:="Dienstag", 3:="Mittwoch", 4:="Donnerstag", 5:="Freitag", 6:="Samstag"}

The expression map:remove($week, 4) returns map{0:="Sonntag", 1:="Montag", 2:="Dienstag", 3:="Mittwoch", 5:="Freitag", 6:="Samstag"}.

The expression map:remove($week, 23) returns map{0:="Sonntag", 1:="Montag", 2:="Dienstag", 3:="Mittwoch", 4:="Donnerstag", 5:="Freitag", 6:="Samstag"}.

21.1.2.8 fn:deep-equal2
Summary

This function assesses whether two sequences are deep-equal to each other. This is a variant of deep-equalFO30 extended to handle maps; it is intended to replace the existing deep-equalFO30 function at some stage in the future, but for the moment is specified here under a temporary name.

Signatures

deep-equal2( $parameter1  as item()*,
$parameter2  as item()*) as xs:boolean
deep-equal2( $parameter1  as item()*,
$parameter2  as item()*,
$collation  as xs:string) as xs:boolean
Properties

This function is deterministicFO30, context-dependentFO30, and focus-independentFO30. It depends on collations.

Rules

The function delivers the same result as deep-equalFO30 except when (at some level of recursion) it is necessary to compare two function items. In the case of deep-equalFO30, comparing two function items raises a dynamic error. In the case of this function, two function items that are both maps are compared as follows.

If two items $i1 and $i2 to be compared are both maps, the result is true if and only if all the following conditions apply:

  1. Both maps have the same number of entries.

  2. Both maps have the same collation.

  3. For every entry in the first map, there is an entry in the second map that:

    1. has the same key (compared using the eq operator under the maps' collation), and

    2. has the same associated value (compared using the fn:deep-equal2 function, under the collation supplied in the original call to fn:deep-equal2).

Error Conditions

An error is raised [ERR FOTY0015] FO30 if either input sequence contains a function item that is not a map.

Examples

The expression fn:deep-equal2(map{}, map{}) returns true().

The expression fn:deep-equal2(map{"a":=1, "b":=2}, map{"b":=2, "a":=1.0}) returns true().

The expression fn:deep-equal2(map{"a":=xs:double('NaN')}, map{"a":=xs:float('NaN')}) returns true().

let $at :=

<attendees>
  <name last='Parker' first='Peter'/>
  <name last='Barker' first='Bob'/>
  <name first='Peter' last='Parker'/>
</attendees>

The expression fn:deep-equal2($at, $at/*) returns false().

The expression fn:deep-equal2($at/name[1], $at/name[2]) returns false().

The expression fn:deep-equal2($at/name[1], $at/name[3]) returns true().

The expression fn:deep-equal2($at/name[1], 'Peter Parker') returns false().

21.1.3 Map Expressions

A new kind of expression is added to the syntax of XPath.

The syntax of PrimaryExprXP30 is extended to permit MapExpr as an additional alternative.

MapExpr := "map" "{" (KeyExpr ":=" ValueExpr ("," KeyExpr ":=" ValueExpr )*)? "}"

KeyExpr := ExprSingle

ValueExpr := ExprSingle

Note:

Two variations on this syntax are under consideration: removing the leading keyword "map", and using the token ":" in place of ":=". This would bring the syntax closer to JavaScript and JSON notation. However, special lexical rules would be needed to disambiguate this use of ":" from other uses. Feedback is invited.

The value of the expression is a map whose entries correspond to the key-value pairs obtained by evaluating the successive KeyExpr and ValueExpr expressions.

Each KeyExpr expression is evaluated and atomized; a dynamic error occurs if the result is not a single atomic value. If the key value is of type xs:untypedAtomic it is converted to xs:string. The associated value is the result of evaluating the corresponding ValueExpr. The collation of the new map is the default collation from the static context. If the key value is NaN then the key/value pair is not added to the map. If two or more keys are equal under the collation of the map then the last occurrence is added to the map and the others are ignored.

For example, the following expression constructs a map with seven entries:

map {
  "Su" := "Sunday",
  "Mo" := "Monday",
  "Tu" := "Tuesday",
  "We" := "Wednesday",
  "Th" := "Thursday",
  "Fr" := "Friday",
  "Sa" := "Saturday
}

Note:

Unlike the map:new, the number of entries in a map that is constructed using a map expression is known statically, except where duplicate keys or NaN values cause some entries to be ignored.

Note:

An alternative syntax for map expressions is also under consideration: an example would be {"Su" : "Sunday", "Mo" : "Monday"}. Feedback is welcome.

21.1.4 Examples using Maps

This section gives some examples of where maps can be useful.

Example: Using maps with xsl:iterate

This example uses maps in conjunction with the xsl:iterate instruction to find the highest-earning employee in each department, in a single streaming pass of an input document containing employee records.

<xsl:stream href="employees.xml">
  <xsl:iterate select="*/employee">
    <xsl:param name="highest-earners" 
               as="map(xs:string, element(employee))" 
               select="map:new()"/>
    <xsl:variable name="this" select="copy-of(.)" as="element(employee)"/> 
    <xsl:next-iteration>
      <xsl:with-param name="highest-earners"
          select="let $existing := $highest-earners($this/department)
                  return if ($existing/salary gt $this/salary)
                         then $highest-earners
                         else map:new($highest-earners, 
                                      map:entry($this/department, $this))"/>
    </xsl:next-iteration>
    <xsl:on-completion>
      <xsl:for-each select="map:keys($highest-earners)">
        <department name="{.}">
          <xsl:copy-of select="$highest-earners(.)"/>
        </department>
      </xsl:for-each>
    </xsl:on-completion>
  </xsl:iterate>
</xsl:stream>

 

Example: Using Maps to implement Complex Numbers

A complex number might be represented as a map with two entries, the keys being the xs:boolean value true for the real part, and the xs:boolean value false for the imaginary part. A library for manipulation of complex numbers might include functions such as the following:

<xsl:function name="i:complex" as="map(xs:boolean, xs:double)">
  <xsl:param name="real" as="xs:double"/>
  <xsl:param name="imaginary" as="xs:double"/>
  <xsl:sequence select="map{ true() := $real, false() := $imaginary }"/>
</xsl:function>

<xsl:function name="i:real" as="xs:double">
  <xsl:param name="complex" as="map(xs:boolean, xs:double)"/>
  <xsl:sequence select="$complex(true())"/>
</xsl:function>

<xsl:function name="i:imaginary" as="xs:double">
  <xsl:param name="complex" as="map(xs:boolean, xs:double)"/>
  <xsl:sequence select="$complex(false())"/>
</xsl:function>

<xsl:function name="i:add" as="map(xs:boolean, xs:double)">
  <xsl:param name="arg1" as="map(xs:boolean, xs:double)"/>
  <xsl:param name="arg2" as="map(xs:boolean, xs:double)"/>
  <xsl:sequence select="i:complex(i:real($arg1)+i:real($arg2), 
                                  i:imaginary($arg1)+i:imaginary($arg2)"/>
</xsl:function>

<xsl:function name="i:multiply" as="map(xs:boolean, xs:double)">
  <xsl:param name="arg1" as="map(xs:boolean, xs:double)"/>
  <xsl:param name="arg2" as="map(xs:boolean, xs:double)"/>
  <xsl:sequence select="i:complex(
      i:real($arg1)*i:real($arg2) - i:imaginary($arg1)*i:imaginary($arg2),
      i:real($arg1)*i:imaginary($arg2) + i:imaginary($arg1)*i:real($arg2))"/>
</xsl:function>

Note:

This example demonstrates how useful it would be to allow user-defined type aliases, so that callers of this function library could write code that treats the value simply as a complex-number, not as a map. A proposal to introduce such type aliases is under consideration.

 

Example: Using a Map as an Index

Given a set of book elements, it is possible to construct an index in the form of a map allowing the books to be retrieved by ISBN number.

Assume the book elements have the form:

<book>
  <isbn>0470192747</isbn>
  <author>Michael H. Kay</author>
  <publisher>Wiley</publisher>
  <title>XSLT 2.0 and XPath 2.0 Programmer's Reference</title>
</book>

An index may be constructed as follows:

<xsl:variable name="isbn-index" as="map(xs:string, element(book))"
    select="map:new(for $b in //book return map{$b/isbn := $b})"/>

This index may then be used to retrieve the book for a given ISBN using either of the expressions map:get($isbn-index, "0470192747") or $isbn-index("0470192747").

In this simple form, this replicates the functionality available using xsl:key and the key function. However, it also provides capabilities not directly available using the key function: for example, the index can include book elements in multiple source documents. It also allows processing of all the books using a construct such as <xsl:for-each select="map:keys($isbn-index)">

 

Example: A Map containing named Functions

As in JavaScript, a map whose keys are strings and whose associated values are function items can be used in a similar way to a class in object-oriented programming languages.

Suppose an application needs to handle customer order information that may arrive in three different formats, with different hierarchic arrangement:

  1. Flat structure:

    <customer id="c123">...</customer>
    <product id="p789">...</product>
    <order customer="c123" product="p789">...</order>
    
  2. Orders within customer elements:

    <customer id="c123">
       <order product="p789">...</order>
    </customer>
    <product id="p789">...</product>
    
  3. Orders within product elements:

    <customer id="c123">...</customer>
    <product id="p789">
      <order customer="c123">...</order>
    </product>
    

An application can isolate itself from these differences by defining a set of functions to navigate the relationships between customers, orders, and products: orders-for-customer, orders-for-product, customer-for-order, product-for-order. These functions can be implemented in different ways for the three different input formats. For example, with the first format the implementation might be:

<xsl:variable name="flat-input-functions" as="map(xs:string, function(*))*"
  select="map {
            'orders-for-customer' := 
                 function($c as element(customer)) as element(order)* 
                    {$c/../order[@customer=$c/@id]},
            'orders-for-product' := 
                 function($p as element(product)) as element(order)* 
                    {$p/../order[@product=$p/@id]},
            'customer-for-order' := 
                 function($o as element(order)) as element(customer) 
                    {$o/../customer[@id=$o/@customer]},
            'product-for-order' := 
                 function($o as element(order)) as element(product) 
                    {$o/../product[@id=$o/@product]} }                    
         "/>

Having established which input format is in use, the application can bind the appropriate implementation of these functions to a variable such as $input-navigator, and can then process the input using XPath expressions such as the following, which selects all products for which there is no order: //product[empty($input-navigator("orders-for-product")(.))]

21.2 Processing JSON Data

JSON is a popular format for exchange of structured data on the web: it is specified in [JSON]. This section describes facilities allowing JSON data to be processed using XSLT.

21.2.1 fn:parse-json

Summary

Parses a string supplied in the form of a JSON text, returning the results in the form of a map.

Signatures

parse-json($json-text as xs:string) as item()?
parse-json( $json-text  as xs:string,
$options  as map(*)) as item()?
Properties

This function is deterministicFO30, context-independentFO30, and focus-independentFO30.

Rules

The effect of the one-argument form of this function is the same as calling the two-argument form with an empty map as the value of the $options argument.

The first argument is a JSON-text (see below) in the form of a string. The function parses this string to return an XPath value.

The $options argument can be used to control the way in which the parsing takes place. The value of the argument is a map. The options defined in this specification have keys that are strings. The effect of any map entries whose keys are not defined in this specification is implementation-defined; implementation-defined options should use QNames as keys. Implementations must ignore any entries in the map whose keys are not defined in this specification, unless the key has a specific implementation-defined meaning.

If the $options map contains an entry whose key is the xs:string value "spec", the value determines the specification of JSON that is to be used. The value must be a string; the effect of supplying any value other than "RFC4627", "ECMA-262", or "liberal" is implementation-defined.

  • The value "RFC4627" denotes [], with no deviations from the grammar permitted.

  • The value "ECMA-262" denotes the specification in [] (section 15.12 in the 5th Edition).

  • The value "liberal" indicates any implementation-defined superset of RFC4627 (or equivalently, an implementation that recovers from some or all errors in the input).

The default is "RFC4627".

If the $options map contains an entry with the key "unescape", the value determines whether escape sequences (marked by a backslash) in the input are expanded. The value is a boolean: true indicates that escape sequences are expanded into the characters they represent, while false indicates that they remain as escape sequences. The default is true. If the value is true and the input contains escape sequences representing characters or codepoints that are not valid characters in the version of XML supported by the implementation, a dynamic error occurs.

The various structures that can occur in JSON are transformed recursively to XDM values as follows:

  1. A JSON object is converted to a map. The collation of the map is the Unicode codepoint collation. The entries in the map correspond to the key/value pairs in the JSON object. The key is always of type xs:string; the associated value may be of any type, and is the result of converting the JSON value by recursive application of these rules. For example, the JSON text {"x":2, "y":5} is transformed to the value map{"x":=2, "y":=5}.

  2. A JSON array is transformed to a map whose keys are consecutive integers starting at one, and whose associated values are the result of converting the corresponding member of the array by recursive application of these rules. For example, the JSON text ["a", "b", null] is transformed to the value map{1:="a", 2:="b", 3:=()}.

    The collation of the map is a special collation with the URI http://www.w3.org/2005/xpath-functions/collation/integer-map, which is intended to be used only for a map having integer keys. The use of this collation distinguishes an map representing an empty JSON array from a map representing an empty JSON object. This collation is not intended to be used when comparing strings; if it ever is so used, the result of string comparisons is implementation-dependent.

  3. A JSON string is converted to an xs:string value. If the unescape option is set to true (or omitted), then escaped characters are expanded (for example, \n becomes a single x0A character, while \u20AC becomes the character ), provided that the expansion is a valid XML character. A character that is not valid in the version of XML used by the processor is then a dynamic error. If the unescape option is set to false, escaped characters are retained in their escaped form, and no error can then occur.

  4. A JSON number is converted to an xs:double value using the rules for casting from xs:string to xs:double.

  5. The JSON boolean values true and false are converted to the corresponding xs:boolean values.

  6. The JSON value null is converted to the empty sequence.

Error Conditions

[ERR XTDE3240] It is a non-recoverable dynamic error if the value of $input does not conform to the JSON grammar, as selected using the explicit or implicit spec option.

[ERR XTDE3250] It is a non-recoverable dynamic error if the value of $input contains an escaped representation of a character (or codepoint) that is not a valid character in the version of XML supported by the implementation, unless the unescape option is set to false.

[ERR XTDE3260] It is a non-recoverable dynamic error if the value of $options includes an entry whose key is "spec" and whose value is not a single xs:string, or an entry whose key is "unescape" and whose value is not a single xs:boolean.

Notes

To read a JSON file, this function can be used in conjunction with the unparsed-textFO30 function.

ECMA-262 differs from RFC 4627 in two respects: it does not allow the input to depart from the JSON grammar, but it does allow the top-level construct in the input to be a string, boolean, number, or null, rather than requiring an object or array.

Many JSON implementations allow commas to be used after the last item in an object or array, although the specification does not permit it. The option spec="liberal" is provided to allow such deviations from the specification to be accepted. Some JSON implementations also allow constructors such as new Date("2000-12-13") to appear as values: specifying spec="liberal" allows such extensions to be accepted, but does not guarantee it. If such extensions are accepted, the resulting XDM value is implementation-defined.

The result of the function will be an instance of one of the following types. An instance of test (or in XQuery, typeswitch) can in most cases be used to distinguish them:

  • map(xs:string, xs:anyAtomicType) for a JSON object

  • map(xs:integer, xs:anyAtomicType) for a JSON array

  • xs:string for a JSON string

  • xs:double for a JSON number

  • xs:boolean for a JSON boolean

  • empty-sequence() for a JSON null

The only exception is that an empty map might represent either an empty JSON object or an empty JSON array. These can be distinguished if need be by the special collation used to represent an empty array.

Examples

The expression parse-json('{"x":1, "y":[3,4,5]}') returns map{"x":=1e0,"y":=map{1:=3e0,2:=4e0,3:=5e0}}.

The expression parse-json('"abcd"', map{'spec':='RFC4627'}) raises error FOJS0001.

The expression parse-json('"abcd"', map{'spec':='ECMA-262'}) returns "abcd".

The expression parse-json('{"x":"\\", "y":"\u0025"}') returns map{"x":="\","y":="%"}.

The expression parse-json('{"x":"\\", "y":"\u0025"}', map{'unescape':=false()}) returns map{"x":="\\","y":="\u0025"}.

21.2.2 fn:serialize-json

Summary

Serializes an XDM value in the as a string conforming to the JSON grammar.

Signatures

serialize-json($input as item()?) as xs:string
serialize-json( $input  as item()?,
$options  as map(*)) as xs:string
Properties

This function is deterministicFO30, context-independentFO30, and focus-independentFO30.

Rules

The effect of the one-argument form of this function is the same as calling the two-argument form with an empty map as the value of the $options argument.

The $options argument can be used to control the way in which the serialization takes place. The value of the argument is a map. The options defined in this specification have keys that are strings. The effect of any map entries whose keys are not defined in this specification is implementation-defined; implementation-defined options should use QNames as keys. Implementations must ignore any entries in the map whose keys are not defined in this specification, unless the key has a specific implementation-defined meaning.

In the absence of options specifying otherwise, the function applies the following rules to achieve the conversion, recursively.

A value is JSON-serializable if it satisfies one of the following rules; it is serialized according to the first rule which applies:

  1. An empty map is JSON-serializable. It is serialized as an empty JSON object unless it has a collation of http://www.w3.org/2005/xpath-functions/collation/integer-map, in which case it is serialized as an empty JSON array.

  2. An instance of map(xs:string, item()?) is JSON-serializable if the value associated with every entry in the map is JSON-serializable. Such a value is serialized as a JSON object. The JSON object contains one member for each entry in the map (in implementation-dependent order). The name of the member is the key of the entry (a string), and its value is the JSON-serialization of the value in the map that is associated with that key.

  3. An instance of map(xs:integer, item()?) is JSON-serializable if the keys are all positive integers and the value associated with every key is JSON-serializable. The map is serialized as a JSON array of size N where N is the maximum key value in the map; the J'th member of the array is the serialization of the value associated with the key J if present, or the JSON value null if the map contains no entry with key value J.

  4. A sequence containing two or more items is JSON-serializable if each of its items is JSON-serializable. Such a value is serialized as a JSON array.

  5. An atomic value of type xs:string or xs:untypedAtomic is JSON-serializable; it is serialized as a JSON string, after escaping any special characters using the JSON backslash convention as described below.

  6. An atomic value of any numeric type is JSON-serializable. An ordinary value is serialized as a JSON number, formatted by applying the rules in this specification for casting a numeric value to a string. The special values positive and negative infinity and NaN are serialized as JSON strings "INF", "-INF" or "NaN" respectively.

  7. An atomic value of type xs:boolean is JSON-serializable; it is serialized as the JSON boolean value true or false.

  8. An empty sequence is JSON-serializable; it is serialized as the JSON value null.

If the option indent is present it must have the boolean value true or false. The default is false. The value true indicates that whitespace should be added to the output with the aim of improving human legibility; the value false indicates that no optional whitespace should be added.

If the option escape is present it must have the boolean value true or false. The default is true. The value true indicates that special characters may be escaped using the JSON backslash notation, and where the JSON syntax requires it, they must be escaped. The value false indicates that strings are already in escaped form and no further escaping is permitted; in this case a dynamic error [TBA] occurs if the resulting string is not valid according to the JSON grammar.

If the option fallback is present its value must be a function of arity 1 (one). The supplied function is called when a value that is not JSON-serializable is encountered in a map. The function must return a value that is JSON-serializable, or a map that can be made JSON-serializable by recursive application of the function to the values in the entries of the map, and the serialization of this value will be inserted in the output as the serialization of the original value. For example, supplying the function string#1 will convert all non-serializable values to strings, provided that the fn:string function is applicable to the value.

If the option spec is present, its permitted values are the same as the values recognized by the implementation for the corresponding option in the parse-json function, and the same rules apply. The input supplied to the serialize-json must be one that can be serialized to generate a string that the implementation will accept as valid input to the parse-json function with the same value of the "spec" option.

Error Conditions

[ERR XTDE3006] It is a non-recoverable dynamic error if the supplied value cannot be serialized as a JSON text conforming to the rules of the specification selected by the explicit or implicit spec option.

[ERR XTDE3007] It is a non-recoverable dynamic error if the value of $options includes an entry whose key is "spec" and whose value is not a single xs:string, or an entry whose key is "indent" or "escape" and whose value is not a single xs:boolean, or an entry whose key is "fallback" and whose value is not a single function item of arity 1 (one).

Notes

The fallback function can be used to customize what is serializable, and how it is serialized. For example, supplying the function fn:string#1 will ensure that values such as dates and times are converted to strings. Supplying the function fn:serialize-xml#1 will cause nodes to be serialized as strings containing lexical XML. More elaborate conversions can be achieved by specifying a user-defined function, for example one which converts an element node to a map.

Although the value returned by the fallback function must be JSON-serializable, the fallback function will be called recursively if the value is a map that contains values that are not JSON-serializable.

Examples

The expression fn:serialize-json(map{"a":=1, "b":=(3 to 5)}) returns one of the following: '{"a":1,"b":[3,4,5]}' or '{"b":[3,4,5],"a":1}'.

The expression fn:serialize-json(("a", "b", "c", "d")) returns '["a","b","c","d"]'.

The expression fn:serialize-json(xs:date('2010-12-31'), map{'spec':='ECMA-262','fallback':=fn:string#1}) returns '"2010-12-31"'.

21.2.3 Example: Converting JSON to Custom XML

The following example shows JSON data being converted to a user-defined XML format.

Example: Processing JSON Data

This example shows how XSLT can be used to convert a JSON data file to XML.

We assume the following input file:

{ "accounting" : [ 
      { "firstName" : "John", 
        "lastName"  : "Doe",
        "age"       : 23 },
      
      { "firstName" : "Mary", 
        "lastName"  : "Smith",
        "age"       : 32 }
                 ],                                 
  "sales"     : [ 
      { "firstName" : "Sally", 
        "lastName"  : "Green",
        "age"       : 27 },
      
      { "firstName" : "Jim",  
        "lastName"  : "Galley",
        "age"       : 41 }
                  ]
}                  

This can be processed as follows:

<xsl:template name="main">
  <xsl:variable name="input" 
                as="map(xs:string, map(xs:string, xs:anyAtomicType)*)"
                select="parse-json(unparsed-text($inputfile))"/>
  <xsl:for-each select="map:keys($input)">
    <department name="{.}">
      <xsl:for-each select="$input(.)">
        <employee>
          <firstName><xsl:value-of select=".('firstName')"/></firstName>
          <lastName><xsl:value-of select=".('lastName')"/></lastName>
          <age><xsl:value-of select=".('age')"/></age>
        </employee>
      </xsl:for-each>
    </department>
  </xsl:for-each>
</xsl:template>
                  

22 Diagnostics

22.1 Messages

<!-- Category: instruction -->
<xsl:message
  select? = expression
  terminate? = { "yes" | "no" }
  error-code? = { eqname } >
  <!-- Content: sequence-constructor -->
</xsl:message>

The xsl:message instruction sends a message in an implementation-defined way. The xsl:message instruction causes the creation of a new document, which is typically serialized and output to an implementation-defined destination. The result of the xsl:message instruction is an empty sequence.

The content of the message may be specified by using either or both of the optional select attribute and the sequence constructor that forms the content of the xsl:message instruction.

If the xsl:message instruction contains a sequence constructor, then the sequence obtained by evaluating this sequence constructor is used to construct the content of the new document node, as described in 5.7.1 Constructing Complex Content.

If the xsl:message instruction has a select attribute, then the value of the attribute must be an XPath expression. The effect of the xsl:message instruction is then the same as if a single xsl:copy-of instruction with this select attribute were added to the start of the sequence constructor.

If the xsl:message instruction has no content and no select attribute, then an empty message is produced.

The tree produced by the xsl:message instruction is not technically a final result tree. The tree has no URI and processors are not required to make the tree accessible to applications.

Note:

In many cases, the XML document produced using xsl:message will consist of a document node owning a single text node. However, it may contain a more complex structure.

Note:

An implementation might implement xsl:message by popping up an alert box or by writing to a log file. Because the order of execution of instructions is implementation-defined, the order in which such messages appear is not predictable.

The terminate attribute is interpreted as an attribute value template.

If the effective value of the terminate attribute is yes, then the processor must signal a non-recoverable dynamic error after sending the message. This error may be caught in the same way as any other dynamic error using xsl:catch. The default value is no. Note that because the order of evaluation of instructions is implementation-dependent, this gives no guarantee that any particular instruction will or will not be evaluated before processing terminates.

The optional error-code attribute may be used to indicate the error code associated with the message. This may be used irrespective of the value of terminate. The error code is an EQName. If no error code is specified, or if the value is not a valid EQName, the error code will have local part XTMM9000 and namespace URI http://www.w3.org/2005/xqt-errors. User-defined error codes should be in a namespace other than http://www.w3.org/2005/xqt-errors. When the value of terminate is yes, the error code may be matched in an xsl:catch element to catch the error and cause processing to continue normally.

[ERR XTMM9000] When a transformation is terminated by use of xsl:message terminate="yes", the effect is the same as when a non-recoverable dynamic error occurs during the transformation. The default error code is XTMM9000; this may be overridden using the error-code attribute of the xsl:message instruction.

Example: Localizing Messages

One convenient way to do localization is to put the localized information (message text, etc.) in an XML document, which becomes an additional input file to the stylesheet. For example, suppose messages for a language L are stored in an XML file resources/L.xml in the form:

<messages>
  <message name="problem">A problem was detected.</message>
  <message name="error">An error was detected.</message>
</messages>

Then a stylesheet could use the following approach to localize messages:

<xsl:param name="lang" select="'en'"/>
<xsl:variable name="messages"
  select="document(concat('resources/', $lang, '.xml'))/messages"/>

<xsl:template name="localized-message">
  <xsl:param name="name"/>
  <xsl:message select="string($messages/message[@name=$name])"/>
</xsl:template>

<xsl:template name="problem">
  <xsl:call-template name="localized-message">
    <xsl:with-param name="name">problem</xsl:with-param>
  </xsl:call-template>
</xsl:template>

Any dynamic error that occurs while evaluating the select expression or the contained sequence constructor, and any serialization error that occurs while processing the result, is treated as a recoverable error even if the error would not be recoverable under other circumstances. The optional recovery action is implementation-dependent.

Note:

An example of such an error is the serialization error that occurs when processing the instruction <xsl:message select="@code"/> (on the grounds that free-standing attributes cannot be serialized). Making such errors recoverable means that it is implementation-defined whether or not they are signaled to the user and whether they cause termination of the transformation. If the processor chooses to recover from the error, the content of any resulting message is implementation-dependent.

One possible recovery action is to include a description of the error in the generated message text.

22.2 Assertions

The xsl:assert instruction is used to assert that the value of a particular expression is true; if the value of the expression is false, and assertions are enabled, then a dynamic error occurs.

<!-- Category: instruction -->
<xsl:assert
  enabled? = expression
  test = expression
  select? = expression
  error-code? = { eqname } >
  <!-- Content: sequence-constructor -->
</xsl:assert>

By default, assertions are enabled. Checking of assertions may be disabled in several ways:

  1. The optional enabled attribute contains an expression which is evaluated to determine whether assertion checking is enabled. Checking is disabled if the attribute is present and the effective boolean value of the expression is false. This mechanism can be used, for example, to enable or disable a group of assertions by the setting of a stylesheet parameter.

  2. As with any other instruction, assertions may be disabled by use of the use-when attribute: see 3.14 Conditional Element Inclusion.

  3. An implementation should provide an external mechanism to disable assertion checking for the stylesheet as a whole (either statically or dynamically). The detail of such mechanisms is implementation-defined.

If assertion checking is enabled, the instruction is evaluated as follows:

  1. The expression in the test attribute is evaluated. If the effective boolean value of the result is true, the assertion succeeds, and no further action is taken. If the effective boolean value is false, or if a dynamic error occurs during evaluation of the expression, then the assertion fails.

  2. If the assertion fails, then the effect of the instruction is governed by the rules for evaluation of an xsl:message instruction with the same select attribute, error-code attribute, and contained sequence constructor, and with the value terminate="yes". However, the default error code if the error-code attribute is omitted is XTMM9001 rather than XTMM9000.

    Note:

    To the extent that the behavior of xsl:message is implementation-defined, this rule does not prevent an implementation treating xsl:assert and xsl:message differently.

[ERR XTMM9001] When a transformation is terminated by use of xsl:assert, the effect is the same as when a non-recoverable dynamic error occurs during the transformation. The default error code is XTMM9001; this may be overridden using the error-code attribute of the xsl:assert instruction.

As with any other dynamic error, an error caused by an assertion failing may be trapped using xsl:try: see 8.3 Try/Catch.

The result of the xsl:assert instruction is an empty sequence.

Note:

Implementations should avoid optimizing xsl:assert instructions away. As a guideline, if the result of a sequence constructor is required by the transformation, the implementation should ensure that all xsl:assert instructions in that sequence constructor are evaluated. Conversely, if the result of a sequence constructor is not required by the transformation, its xsl:assert instructions should not be evaluated.

This recommendation is not intended to prevent optimizations such as lazy evaluation, where evaluation of a sequence constructor may finish early, as soon as enough information is available to evaluate the containing instruction.

An implementation may provide a user option allowing a processor to treat assertions as being true without explicit checking. This option must not be enabled by default. If such an option is in force, the effect of any assertion not being true is implementation-dependent.

Note:

For example, given the assertion <xsl:assert test="count(//title)=1"/>, a processor might generate code for the expression <xsl:value-of select="//title"/> that stops searching for title elements after finding the first one. In the event that the source document contains more than one title, execution of the stylesheet may fail in arbitrary ways, or it may produce incorrect output.

Issue 11 (assuming-assertions-true):

The idea that assertions can be used as optimization hints, and assumed true without checking, requires further thought and discussion. Feedback is welcome.

23 Extensibility and Fallback

XSLT allows two kinds of extension, extension instructions and extension functions.

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

[Definition: An extension function is a function that is available for use within an XPath expression, other than a core function defined in [Functions and Operators], an additional function defined in this XSLT specification, a constructor function named after an atomic type, or a stylesheet function defined using an xsl:function declaration.].

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

23.1 Extension Functions

The set of functions that can be called from a FunctionCallXP30 within an XPath expression may include one or more extension functions. The expanded QName of an extension function always has a non-null namespace URI.

23.1.1 fn:function-available

Summary

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

Signatures

function-available($function-name as xs:string) as xs:boolean
function-available( $function-name  as xs:string,
$arity  as xs:integer) as xs:boolean
Properties

This function is deterministicFO30, context-dependentFO30, and focus-independentFO30. It depends on namespaces, and known function signatures.

Rules

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

The value of the $function-name argument must be a string containing a EQName. The lexical QName is expanded into an expanded QName using the namespace declarations in scope for the expression. If the value is an unprefixed lexical QName, then the standard function namespace is used in the expanded QName.

The two-argument version of the function-available function returns true if and only if there is an available function whose name matches the value of the $function-name argument and whose arity matches the value of the $arity argument.

The single-argument version of the function-available function returns true if and only if there is at least one available function (with some arity) whose name matches the value of the $function-name argument.

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

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

[ERR XTDE1400] It is a non-recoverable dynamic error if the argument does not evaluate to a string that is a valid EQName, or if the value is a lexical QName with a prefix for which no namespace declaration is present in the static context. If the processor is able to detect the error statically (for example, when the argument is supplied as a string literal), then the processor may optionally signal this as a static error.

Notes

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

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

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

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

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

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

 

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

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

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

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

23.1.2 Calling Extension Functions

If the function name used in a FunctionCallXP30 within an XPath expression identifies an extension function, then to evaluate the FunctionCallXP30, the processor will first evaluate each of the arguments in the FunctionCallXP30. If the processor has information about the datatypes expected by the extension function, then it may perform any necessary type conversions between the XPath datatypes and those defined by the implementation language. If multiple extension functions are available with the same name, the processor may decide which one to invoke based on the number of arguments, the types of the arguments, or any other criteria. The result returned by the implementation is returned as the result of the function call, again after any necessary conversions between the datatypes of the implementation language and those of XPath. The details of such type conversions are outside the scope of this specification.

[ERR XTDE1420] It is a non-recoverable dynamic error if the arguments supplied to a call on an extension function do not satisfy the rules defined for that particular extension function, or if the extension function reports an error, or if the result of the extension function cannot be converted to an XPath value.

Note:

Implementations may also provide mechanisms allowing extension functions to report recoverable dynamic errors, or to execute within an environment that treats some or all of the errors listed above as recoverable.

[ERR XTDE1425] When the containing element is processed with XSLT 1.0 behavior, it is a non-recoverable dynamic error to evaluate an extension function call if no implementation of the extension function is available.

Note:

When XSLT 1.0 behavior is not enabled, this is a static error [ERR XPST0017] XP30.

Note:

There is no prohibition on calling extension functions that have side-effects (for example, an extension function that writes data to a file). However, the order of execution of XSLT instructions is not defined in this specification, so the effects of such functions are unpredictable.

Implementations are not required to perform full validation of values returned by extension functions. It is an error for an extension function to return a string containing characters that are not permitted in XML, but the consequences of this error are implementation-defined. The implementation may raise an error, may convert the string to a string containing valid characters only, or may treat the invalid characters as if they were permitted characters.

Note:

The ability to execute extension functions represents a potential security weakness, since untrusted stylesheets may invoke code that has privileged access to resources on the machine where the processor executes. Implementations may therefore provide mechanisms that restrict the use of extension functions by untrusted stylesheets.

All observations in this section regarding the errors that can occur when invoking extension functions apply equally when invoking extension instructions.

23.1.3 External Objects

An implementation may allow an extension function to return an object that does not have any natural representation in the XDM data model, whether as an atomic value, a node, or a function item. For example, an extension function sql:connect might return an object that represents a connection to a relational database; the resulting connection object might be passed as an argument to calls on other extension functions such as sql:insert and sql:select.

The way in which such objects are represented in the type system is implementation-defined. They might be represented by a completely new datatype, or they might be mapped to existing datatypes such as integer, string, or anyURI.

23.1.4 fn:type-available

Summary

Used to control how a stylesheet behaves if a particular schema type is or is not available in the static context.

Signature

type-available($type-name as xs:string) as xs:boolean
Properties

This function is deterministicFO30, context-dependentFO30, and focus-independentFO30. It depends on namespaces, and schema definitions.

Rules

A schema type (that is, a simple type or a complex type) is said to be available within an XPath expression if it is a type definition that is present in the in-scope schema typesXP30 for that expression (see 5.4.1 Initializing the Static Context). This includes built-in types, types imported using xsl:import-schema, and extension types defined by the implementation.

The value of the $type-name argument must be a string containing a EQName. The EQName is expanded into an expanded QName using the namespace declarations in scope for the expression. If the value is an unprefixed lexical QName, then the default namespace is used in the expanded QName.

The function returns true if and only if there is an available type whose name matches the value of the $type-name argument.

Error Conditions

[ERR XTDE1428] It is a non-recoverable dynamic error if the argument does not evaluate to a string that is a valid EQName, or if the value is a lexical QName with a prefix for which no namespace declaration is present in the static context. If the processor is able to detect the error statically (for example, when the argument is supplied as a string literal), then the processor may optionally signal this as a static error.

Notes

The type-available function is of limited use within an [xsl:]use-when expression, because the static context for the expression does not include any user-defined types.

23.2 Extension Instructions

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

Note:

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

23.2.1 Designating an Extension Namespace

A namespace is designated as an extension namespace by using an [xsl:]extension-element-prefixes attribute on an element in the stylesheet (see 3.5 Standard Attributes). The attribute must be in the XSLT namespace only if its parent element is not in the XSLT namespace. The value of the attribute is a whitespace-separated list of namespace prefixes. The namespace bound to each of the prefixes is designated as an extension namespace.

The default namespace (as declared by xmlns) may be designated as an extension namespace by including #default in the list of namespace prefixes.

[ERR XTSE1430] It is a static error if there is no namespace bound to the prefix on the element bearing the [xsl:]extension-element-prefixes attribute or, when #default is specified, if there is no default namespace.

The designation of a namespace as an extension namespace is effective for the element bearing the [xsl:]extension-element-prefixes attribute and for all descendants of that element within the same stylesheet module.

23.2.2 fn:element-available

Summary

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

Signature

element-available($element-name as xs:string) as xs:boolean
Properties

This function is deterministicFO30, context-dependentFO30, and focus-independentFO30. It depends on namespaces.

Rules

The value of the $element-name argument must be a string containing an EQName. If it is a lexical QName with a prefix, the it is expanded into an expanded QName using the namespace declarations in the static context of the expression. If there is a default namespace in scope, then it is used to expand an unprefixed lexical QName. The element-available function returns true if and only if the expanded QName is the name of an instruction. If the expanded QName has a namespace URI equal to the XSLT namespace URI, then it refers to an element defined by XSLT. Otherwise, it refers to an extension instruction. If the expanded QName has a null namespace URI, the element-available function will return false.

If the expanded QName is in the XSLT namespace, the function returns true if and only if the expanded QName is the name of an XSLT instruction, that is, an XSLT element whose syntax summary in this specification classifies it as an instruction.

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

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

Error Conditions

[ERR XTDE1440] It is a non-recoverable dynamic error if the argument does not evaluate to a string that is a valid EQName, or if the value is a lexical QName with a prefix for which no namespace declaration is present in the static context. If the processor is able to detect the error statically (for example, when the argument is supplied as a string literal), then the processor may optionally signal this as a static error.

Notes

Although the result of applying this function to a name in the XSLT namespace when using a conformant XSLT 3.0 processor is entirely predictable, the function is useful in cases where the stylesheet might be executing under a processor that implements some other version of XSLT with different rules.

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

23.2.3 Fallback

<!-- Category: instruction -->
<xsl:fallback>
  <!-- Content: sequence-constructor -->
</xsl:fallback>

The content of an xsl:fallback element is a sequence constructor, and when performing fallback, the value returned by the xsl:fallback element is the result of evaluating this sequence constructor.

When not performing fallback, evaluating an xsl:fallback element returns an empty sequence: the content of the xsl:fallback element is ignored.

There are two situations where a processor performs fallback: when an extension instruction that is not available is evaluated, and when an instruction in the XSLT namespace, that is not defined in XSLT 3.0, is evaluated within a region of the stylesheet for which forwards compatible behavior is enabled.

Note:

Fallback processing is not invoked in other situations, for example it is not invoked when an XPath expression uses unrecognized syntax or contains a call to an unknown function. To handle such situations dynamically, the stylesheet should call functions such as system-property and function-available to decide what capabilities are available.

[ERR XTDE1450] When a processor performs fallback for an extension instruction that is not recognized, if the instruction element has one or more xsl:fallback children, then the content of each of the xsl:fallback children must be evaluated; it is a non-recoverable dynamic error if it has no xsl:fallback children.

Note:

This is different from the situation with unrecognized XSLT elements. As explained in 3.11 Forwards Compatible Processing, an unrecognized XSLT element appearing within a sequence constructor is a static error unless (a) forwards compatible behavior is enabled, and (b) the instruction has an xsl:fallback child.

24 Final Result Trees

The output of a transformation is a set of one or more final result trees.

A final result tree can be created explicitly, by evaluating an xsl:result-document instruction. As explained in 2.4 Executing a Transformation, a final result tree is also created implicitly if no xsl:result-document instruction is evaluated, or if the result of evaluating the initial template is a non-empty sequence.

The way in which a final result tree is delivered to an application is implementation-defined.

Serialization of final result trees is described further in 25 Serialization

24.1 Creating Final Result Trees

<!-- Category: instruction -->
<xsl:result-document
  format? = { eqname }
  href? = { uri }
  validation? = "strict" | "lax" | "preserve" | "strip"
  type? = eqname
  method? = { "xml" | "html" | "xhtml" | "text" | eqname }
  byte-order-mark? = { "yes" | "no" }
  cdata-section-elements? = { eqnames }
  doctype-public? = { string }
  doctype-system? = { string }
  encoding? = { string }
  escape-uri-attributes? = { "yes" | "no" }
  include-content-type? = { "yes" | "no" }
  indent? = { "yes" | "no" }
  media-type? = { string }
  normalization-form? = { "NFC" | "NFD" | "NFKC" | "NFKD" | "fully-normalized" | "none" | nmtoken }
  omit-xml-declaration? = { "yes" | "no" }
  standalone? = { "yes" | "no" | "omit" }
  suppress-indentation? = { eqnames }
  undeclare-prefixes? = { "yes" | "no" }
  use-character-maps? = eqnames
  output-version? = { nmtoken } >
  <!-- Content: sequence-constructor -->
</xsl:result-document>

The xsl:result-document instruction is used to create a final result tree. The content of the xsl:result-document element is a sequence constructor for the children of the document node of the tree. A document node is created, and the sequence obtained by evaluating the sequence constructor is used to construct the content of the document, as described in 5.7.1 Constructing Complex Content. The tree rooted at this document node forms the final result tree.

The xsl:result-document instruction defines the URI of the result tree, and may optionally specify the output format to be used for serializing this tree.

The effective value of the format attribute, if specified, must be a EQName. The value is expanded using the namespace declarations in scope for the xsl:result-document element. The resulting expanded QName must match the expanded QName of a named output definition in the stylesheet. This identifies the xsl:output declaration that will control the serialization of the final result tree (see 25 Serialization), if the result tree is serialized. If the format attribute is omitted, the unnamed output definition is used to control serialization of the result tree.

[ERR XTDE1460] It is a non-recoverable dynamic error if the effective value of the format attribute is not a valid EQName, or if it does not match the expanded QName of an output definition in the stylesheet. If the processor is able to detect the error statically (for example, when the format attribute contains no curly brackets), then the processor may optionally signal this as a static error.

Note:

The only way to select the unnamed output definition is to omit the format attribute.

The attributes method, byte-order-mark cdata-section-elements, doctype-public, doctype-system, encoding, escape-uri-attributes, indent, media-type, normalization-form, omit-xml-declaration, standalone, suppress-indentation, undeclare-prefixes, use-character-maps, and output-version may be used to override attributes defined in the selected output definition.

With the exception of use-character-maps, these attributes are all defined as attribute value templates, so their values may be set dynamically. For any of these attributes that is present on the xsl:result-document instruction, the effective value of the attribute overrides or supplements the corresponding value from the output definition. This works in the same way as when one xsl:output declaration overrides another:

  • In the case of cdata-section-elements and suppress-indentation, the value of the serialization parameter is the union of the expanded names of the elements named in this instruction and the elements named in the selected output definition;

  • In the case of use-character-maps, the character maps referenced in this instruction supplement and take precedence over those defined in the selected output definition;

  • In all other cases, the effective value of an attribute actually present on this instruction takes precedence over the value defined in the selected output definition.

Note:

In the case of the attributes method, cdata-section-elements, suppress-indentation, and use-character-maps, the effective value of the attribute contains a space-separated list of EQNames. If any of these is a lexical QName with a prefix, the prefix is expanded using the in-scope namespaces for the xsl:result-document element. In the case of cdata-section-elements and suppress-indentation, an unprefixed element name is expanded using the default namespace. In the case of the method attribute, if the method is not one of the system-defined methods (xml, html, xhtml, text) then the expanded name must have a non-absent namespace.

The output-version attribute on the xsl:result-document instruction overrides the version attribute on xsl:output (it has been renamed because version is available with a different meaning as a standard attribute: see 3.5 Standard Attributes). In all other cases, attributes correspond if they have the same name.

There are some serialization parameters that apply to some output methods but not to others. For example, the indent attribute has no effect on the text output method. If a value is supplied for an attribute that is inapplicable to the output method, its value is not passed to the serializer. The processor may validate the value of such an attribute, but is not required to do so.

The href attribute is optional. The default value is the zero-length string. The effective value of the attribute must be a URI Reference, which may be absolute or relative. There may be implementation-defined restrictions on the form of absolute URI that may be used, but the implementation is not required to enforce any restrictions. Any valid relative URI reference must be accepted. Note that the zero-length string is a valid relative URI reference.

The base URI of the document node at the root of the final result tree is based on the effective value of the href attribute. If the effective value is a relative URI reference, then it is resolved relative to the base output URI. If the implementation provides an API to access final result trees, then it must allow a final result tree to be identified by means of this base URI.

Note:

The base URI of the final result tree is not necessarily the same thing as the URI of its serialized representation on disk, if any. For example, a server (or browser client) might store final result trees only in memory, or in an internal disk cache. As long as the processor satisfies requests for those URIs, it is irrelevant where they are actually written on disk, if at all.

Note:

It will often be the case that one final result tree contains links to another final result tree produced during the same transformation, in the form of a relative URI reference. The mechanism of associating a URI with a final result tree has been chosen to allow the integrity of such links to be preserved when the trees are serialized.

As well as being potentially significant in any API that provides access to final result trees, the base URI of the new document node is relevant if the final result tree, rather than being serialized, is supplied as input to a further transformation.

The optional attributes type and validation may be used on the xsl:result-document instruction to validate the contents of the new document, and to determine the type annotation that elements and attributes within the final result tree will carry. The permitted values and their semantics are described in 24.2.2 Validating Document Nodes.

A processor may allow a final result tree to be serialized. Serialization is described in 25 Serialization. However, an implementation (for example, a processor running in an environment with no access to writable filestore) is not required to support the serialization of final result trees. An implementation that does not support the serialization of final result trees may ignore the format attribute and the serialization attributes. Such an implementation must provide the application with some means of access to the (un-serialized) result tree, using its URI to identify it.

Implementations may provide additional mechanisms, outside the scope of this specification, for defining the way in which final result trees are processed. Such mechanisms may make use of the XSLT-defined attributes on the xsl:result-document and/or xsl:output elements, or they may use additional elements or attributes in an implementation-defined namespace.

Example: Multiple Result Documents

The following example takes an XHTML document as input, and breaks it up so that the text following each <h1> element is included in a separate document. A new document toc.html is constructed to act as an index:

<xsl:stylesheet
        version="3.0"
        xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
        xmlns:xhtml="http://www.w3.org/1999/xhtml">
        
<xsl:output name="toc-format" method="xhtml" indent="yes"
     doctype-system="http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"
     doctype-public="-//W3C//DTD XHTML 1.0 Strict//EN"/>
            
<xsl:output name="section-format" method="xhtml" indent="no"
     doctype-system="http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"
     doctype-public="-//W3C//DTD XHTML 1.0 Transitional//EN"/>       
         
<xsl:template match="/">
  <xsl:result-document href="toc.html" 
                       format="toc-format" 
                       validation="strict">
    <html xmlns="http://www.w3.org/1999/xhtml">
      <head><title>Table of Contents</title></head>
      <body>
        <h1>Table of Contents</h1>
        <xsl:for-each select="/*/xhtml:body/(*[1] | xhtml:h1)">
          <p>
            <a href="section{position()}.html">
              <xsl:value-of select="."/>
            </a>
          </p>
        </xsl:for-each>
      </body>
    </html>
  </xsl:result-document>
  <xsl:for-each-group select="/*/xhtml:body/*" group-starting-with="xhtml:h1">
    <xsl:result-document href="section{position()}.html" 
                         format="section-format" validation="strip">         
      <html xmlns="http://www.w3.org/1999/xhtml">
        <head><title><xsl:value-of select="."/></title></head>
        <body>
          <xsl:copy-of select="current-group()"/>
        </body>
      </html>
    </xsl:result-document>
  </xsl:for-each-group>
</xsl:template>

</xsl:stylesheet>

There are restrictions on the use of the xsl:result-document instruction, designed to ensure that the results are fully interoperable even when processors optimize the sequence in which instructions are evaluated. Informally, the restriction is that the xsl:result-document instruction can only be used while writing a final result tree, not while writing to a temporary tree or a sequence. This restriction is defined formally as follows.

[Definition: Each instruction in the stylesheet is evaluated in one of two possible output states: final output state or temporary output state ].

[Definition: The first of the two output states is called final output state. This state applies when instructions are writing to a final result tree.]

[Definition: The second of the two output states is called temporary output state. This state applies when instructions are writing to a temporary tree or any other non-final destination.]

The instructions in the initial template are evaluated in final output state. An instruction is evaluated in the same output state as its calling instruction, except that xsl:variable, xsl:param, xsl:with-param, xsl:attribute, xsl:comment, xsl:processing-instruction, xsl:namespace, xsl:value-of, xsl:function, xsl:key, xsl:sort, xsl:message, and xsl:assert always evaluate the instructions in their contained sequence constructor in temporary output state.

[ERR XTDE1480] It is a non-recoverable dynamic error to evaluate the xsl:result-document instruction in temporary output state.

[ERR XTDE1490] It is a non-recoverable dynamic error for a transformation to generate two or more final result trees with the same URI.

Note:

Note, this means that it is an error to evaluate more than one xsl:result-document instruction that omits the href attribute, or to evaluate any xsl:result-document instruction that omits the href attribute if an initial final result tree is created implicitly.

Technically, the result of evaluating the xsl:result-document instruction is an empty sequence. This means it does not contribute any nodes to the result of the sequence constructor it is part of.

[ERR XTRE1495] It is a recoverable dynamic error for a transformation to generate two or more final result trees with URIs that identify the same physical resource. The optional recovery action is implementation-dependent, since it may be impossible for the processor to detect the error.

[ERR XTRE1500] It is a recoverable dynamic error for a stylesheet to write to an external resource and read from the same resource during a single transformation, whether or not the same URI is used to access the resource in both cases. The optional recovery action is implementation-dependent: implementations are not required to detect the error condition. Note that if the error is not detected, it is implementation-dependent whether the document that is read from the resource reflects its state before or after the result tree is written.

24.2 Validation

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

The [xsl:]type attribute is used to request validation of an element or attribute against a specific simple or complex type defined in a schema. The [xsl:]validation attribute is used to request validation against the global element or attribute declaration whose name matches the name of the element or attribute being validated.

The [xsl:]type and [xsl:]validation attributes are mutually exclusive. Both are optional, but if one is present then the other must be omitted. If both attributes are omitted, the effect is the same as specifying the validation attribute with the value specified in the default-validation attribute of the containing xsl:stylesheet element; if this is not specified, the effect is the same as specifying validation="strip".

[ERR XTSE1505] It is a static error if both the [xsl:]type and [xsl:]validation attributes are present on the xsl:element, xsl:attribute, xsl:copy, xsl:copy-of, xsl:document, or xsl:result-document instructions, or on a literal result element.

The detailed rules for validation vary depending on the kind of node being validated. The rules for element and attribute nodes are given in 24.2.1 Validating Constructed Elements and Attributes, while those for document nodes are given in 24.2.2 Validating Document Nodes.

24.2.1 Validating Constructed Elements and Attributes

24.2.1.1 Validation using the [xsl:]validation Attribute

The [xsl:]validation attribute defines the validation action to be taken. It determines not only the type annotation of the node that is constructed by the relevant instruction itself, but also the type annotations of all element and attribute nodes that have the constructed node as an ancestor. Conceptually, the validation requested for a child element or attribute node is applied before the validation requested for its parent element. For example, if the instruction that constructs a child element specifies validation="strict", this will cause the child element to be checked against an element declaration, but if the instruction that constructs its parent element specifies validation="strip", then the final effect will be that the child node is annotated as xs:untyped.

In the paragraphs below, the term contained nodes means the elements and attributes that have the newly constructed node as an ancestor.

  • The value strip indicates that the new node and each of the contained nodes will have the type annotation xs:untyped if it is an element, or xs:untypedAtomic if it is an attribute. Any previous type annotation present on a contained element or attribute node (for example, a type annotation that is present on an element copied from a source document) is also replaced by xs:untyped or xs:untypedAtomic as appropriate. The typed value of the node is changed to be the same as its string value, as an instance of xs:untypedAtomic. In the case of elements the nilled property is set to false. The values of the is-id and is-idrefs properties are unchanged. Schema validation is not invoked.

  • The value preserve indicates that nodes that are copied will retain their type annotations, but nodes whose content is newly constructed will be annotated as xs:anyType in the case of elements, or xs:untypedAtomic in the case of attributes. Schema validation is not invoked. The detailed effect depends on the instruction:

    • In the case of xsl:element and literal result elements, the new element has a type annotation of xs:anyType, and the type annotations of contained nodes are retained unchanged.

    • In the case of xsl:attribute, the effect is exactly the same as specifying validation="strip": that is, the new attribute will have the type annotation xs:untypedAtomic.

    • In the case of xsl:copy-of, all the nodes that are copied will retain their type annotations unchanged.

    • In the case of xsl:copy, the effect depends on the kind of node being copied.

      1. Where the node being copied is an attribute, the copied attribute will retain its type annotation.

      2. Where the node being copied is an element, the copied element will have a type annotation of xs:anyType (because this instruction does not copy the content of the element, it would be wrong to assume that the type is unchanged); but any contained nodes will have their type annotations retained in the same way as with xsl:element.

  • The value strict indicates that type annotations are established by performing strict schema validity assessment on the element or attribute node created by this instruction as follows:

    • In the case of an element, a top-level element declaration is identified whose local name and namespace (if any) match the name of the element, and schema-validity assessment is carried out according to the rules defined in [XML Schema Part 1] (section 3.3.4 "Element Declaration Validation Rules", validation rule "Schema-Validity Assessment (Element)", clauses 1.1 and 2, using the top-level element declaration as the "declaration stipulated by the processor", which is mentioned in clause 1.1.1.1). The element is considered valid if the result of the schema validity assessment is a PSVI in which the relevant element node has a validity property whose value is valid. If there is no matching element declaration, or if the element is not considered valid, the transformation fails [see ERR XTTE1510], [see ERR XTTE1512]. In effect this means that the element being validated must be declared using a top-level declaration in the schema, and must conform to its declaration. The process of validation applies recursively to contained elements and attributes to the extent required by the schema definition.

      Note:

      It is not an error if the identified type definition is a simple type, although [XML Schema Part 1] does not define explicitly that this case is permitted.

    • In the case of an attribute, a top-level attribute declaration is identified whose local name and namespace (if any) match the name of the attribute, and schema-validity assessment is carried out according to the rules defined in [XML Schema Part 1] (section 3.2.4 "Attribute Declaration Validation Rules", validation rule "Schema-Validity Assessment (Attribute)"). The attribute is considered valid if the result of the schema validity assessment is a PSVI in which the relevant attribute node has a validity property whose value is valid. If the attribute is not considered valid, the transformation fails [see ERR XTTE1510]. In effect this means that the attribute being validated must be declared using a top-level declaration in the schema, and must conform to its declaration.

    • The schema components used to validate an element or attribute may be located in any way described by [XML Schema Part 1] (see section 4.3.2, How schema documents are located on the Web). The components in the schema constructed from the synthetic schema document (see 3.16 Importing Schema Components) will always be available for validating constructed nodes; if additional schema components are needed, they may be located in other ways, for example implicitly from knowledge of the namespace in which the elements and attributes appear, or using the xsi:schemaLocation attribute of elements within the tree being validated.

    • If no validation is performed for a node, which can happen when the schema specifies lax or skip validation for that node or for a subtree, then the node is annotated as xs:anyType in the case of an element, and xs:untypedAtomic in the case of an attribute.

  • The value lax has the same effect as the value strict, except that whereas strict validation fails if there is no matching top-level element declaration or if the outcome of validity assessment is a validity property of invalid or notKnown, lax validation fails only if the outcome of validity assessment is a validity property of invalid. That is, lax validation does not cause a type error when the outcome is notKnown.

    In practice this means that the element or attribute being validated must conform to its declaration if a top-level declaration is available. If no such declaration is available, then the element or attribute is not validated, but its attributes and children are validated, again with lax validation. Any nodes whose validation outcome is a validity property of notKnown are annotated as xs:anyType in the case of an element, and xs:untypedAtomic in the case of an attribute.

    Note:

    When the parent element lacks a declaration, the XML Schema specification defines the recursive checking of children and attributes as optional. For this specification, this recursive checking is required.

    Note:

    If an element that is being validated has an xsi:type attribute, then the value of the xsi:type attribute will be taken into account when performing the validation. However, the presence of an xsi:type attribute will not of itself cause an element to be validated: if validation against a named type is required, as distinct from validation against a top-level element declaration, then it must be requested using the XSLT [xsl:]type attribute on the instruction that invokes the validation, as described in section 24.2.1.2 Validation using the [xsl:]type Attribute

[ERR XTTE1510] If the validation attribute of an xsl:element, xsl:attribute, xsl:copy, xsl:copy-of, or xsl:result-document instruction, or the xsl:validation attribute of a literal result element, has the effective value strict, and schema validity assessment concludes that the validity of the element or attribute is invalid or unknown, a type error occurs. As with other type errors, the error may be signaled statically if it can be detected statically.

[ERR XTTE1512] If the validation attribute of an xsl:element, xsl:attribute, xsl:copy, xsl:copy-of, or xsl:result-document instruction, or the xsl:validation attribute of a literal result element, has the effective value strict, and there is no matching top-level declaration in the schema, then a type error occurs. As with other type errors, the error may be signaled statically if it can be detected statically.

[ERR XTTE1515] If the validation attribute of an xsl:element, xsl:attribute, xsl:copy, xsl:copy-of, or xsl:result-document instruction, or the xsl:validation attribute of a literal result element, has the effective value lax, and schema validity assessment concludes that the element or attribute is invalid, a type error occurs. As with other type errors, the error may be signaled statically if it can be detected statically.

Note:

No mechanism is provided to validate an element or attribute against a local declaration in a schema. Such validation can usually be achieved by applying validation to a containing element for which a top-level element declaration exists.

24.2.1.2 Validation using the [xsl:]type Attribute

The [xsl:]type attribute takes as its value a QName. This must be the name of a type definition included in the in-scope schema components for the stylesheet. If the QName has no prefix, it is expanded using the default namespace established using the effective [xsl:]xpath-default-namespace attribute if there is one; otherwise, it is taken as being a name in no namespace.

If the [xsl:]type attribute is present, then the newly constructed element or attribute is validated against the type definition identified by this attribute.

  • In the case of an element, schema-validity assessment is carried out according to the rules defined in [XML Schema Part 1] (section 3.3.4 "Element Declaration Validation Rules", validation rule "Schema-Validity Assessment (Element)", clauses 1.2 and 2), using this type definition as the "processor-stipulated type definition". The element is considered valid if the result of the schema validity assessment is a PSVI in which the relevant element node has a validity property whose value is valid.

  • In the case of an attribute, the attribute is considered valid if (in the terminology of XML Schema) the attribute's normalized value is locally valid with respect to that type definition according to the rules for "String Valid" ([XML Schema Part 1], section 3.14.4). (Normalization here refers to the process of normalizing whitespace according to the rules of the whiteSpace facet for the datatype).

  • If the element or attribute is not considered valid, as defined above, the transformation fails [see ERR XTTE1540].

[ERR XTSE1520] It is a static error if the value of the type attribute of an xsl:element, xsl:attribute, xsl:copy, xsl:copy-of, xsl:document, or xsl:result-document instruction, or the xsl:type attribute of a literal result element, is not a valid QName, or if it uses a prefix that is not defined in an in-scope namespace declaration, or if the QName is not the name of a type definition included in the in-scope schema components for the stylesheet.

[ERR XTSE1530] It is a static error if the value of the type attribute of an xsl:attribute instruction refers to a complex type definition.

[ERR XTTE1535] It is a type error if the value of the type attribute of an xsl:copy or xsl:copy-of instruction refers to a complex type definition and one or more of the items being copied is an attribute node..

[ERR XTTE1540] It is a type error if an [xsl:]type attribute is defined for a constructed element or attribute, and the outcome of schema validity assessment against that type is that the validity property of that element or attribute information item is other than valid.

Note:

Like other type errors, this error may be signaled statically if it can be detected statically. For example, the instruction <xsl:attribute name="dob" type="xs:date">1999-02-29</xsl:attribute> may result in a static error being signaled. If the error is not signaled statically, it will be signaled when the instruction is evaluated.

24.2.1.3 The Validation Process

As well as checking for validity against the schema, the validity assessment process causes type annotations to be associated with element and attribute nodes. If default values for elements or attributes are defined in the schema, the validation process will where necessary create new nodes containing these default values.

Validation of an element or attribute node only takes into account constraints on the content of the element or attribute. Validation rules affecting the document as a whole are not applied. Specifically, this means:

  • The validation rule "Validation Root Valid (ID/IDREF)" is not applied. This means that validation will not fail if there are non-unique ID values or dangling IDREF values in the subtree being validated.

  • The validation rule "Validation Rule: Identity-constraint Satisfied" should be applied.

  • There is no check that the document contains unparsed entities whose names match the values of nodes of type xs:ENTITY or xs:ENTITIES. (XSLT 3.0 provides no facility to construct unparsed entities within a tree.)

  • There is no check that the document contains notations whose names match the values of nodes of type xs:NOTATION. (The XDM data model makes no provision for notations to be represented in the tree.)

With these caveats, validating a newly constructed element, using strict or lax validation, is equivalent to the following steps:

  1. The element is serialized to textual XML form, according to the rules defined in [XSLT and XQuery Serialization] using the XML output method, with all parameters defaulted. Note that this process discards any existing type annotations.

  2. The resulting XML document is parsed to create an XML Information Set (see [XML Information Set].)

  3. The Information Set produced in the previous step is validated according to the rules in [XML Schema Part 1]. The result of this step is a Post-Schema Validation Infoset (PSVI). If the validation process is not successful (as defined above), a type error is raised.

  4. The PSVI produced in the previous step is converted back into the XDM data model by the mapping described in [Data Model] (Section 3.3.1 Mapping PSVI Additions to Node Properties DM30). This process creates nodes with simple or complex type annotations based on the types established during schema validation.

Validating an attribute using strict or lax validation requires a modified version of this procedure. A copy of the attribute is first added to an element node that is created for the purpose, and namespace fixup (see 5.7.3 Namespace Fixup) is performed on this element node. The name of this element is of no consequence, but it must be the same as the name of a synthesized element declaration of the form:

<xs:element name="E">
  <xs:complexType>
    <xs:sequence/>
    <xs:attribute ref="A"/>
  </xs:complexType>
</xs:element>

where A is the name of the attribute being validated.

This synthetic element is then validated using the procedure given above for validating elements, and if it is found to be valid, a copy of the validated attribute is made, retaining its type annotation, but detaching it from the containing element (and thus, from any namespace nodes).

The XDM data model does not permit an attribute node with no parent to have a typed value that includes a namespace-qualified name, that is, a value whose type is derived from xs:QName or xs:NOTATION. This restriction is imposed because these types rely on the namespace nodes of a containing element to resolve namespace prefixes. Therefore, it is an error to validate a parentless attribute against such a type. This affects the instructions xsl:attribute, xsl:copy, and xsl:copy-of.

[ERR XTTE1545] A type error occurs if a type or validation attribute is defined (explicitly or implicitly) for an instruction that constructs a new attribute node, if the effect of this is to cause the attribute value to be validated against a type that is derived from, or constructed by list or union from, the primitive types xs:QName or xs:NOTATION.

24.2.2 Validating Document Nodes

It is possible to apply validation to a document node. This happens when a new document node is constructed by one of the instructions xsl:document, xsl:result-document, xsl:copy, or xsl:copy-of, and this instruction has a type attribute, or a validation attribute with the value strict or lax.

Document-level validation is not applied to the document node that is created implicitly when a variable-binding element has no select attribute and no as attribute (see 9.4 Creating implicit document nodes). This is equivalent to using validation="preserve" on xsl:document: nodes within such trees retain their type annotation. Similarly, validation is not applied to document nodes created using xsl:message or xsl:assert.

The values validation="preserve" and validation="strip" do not request validation. In the first case, all element and attribute nodes within the tree rooted at the new document node retain their type annotations. In the second case, elements within the tree have their type annotation set to xs:untyped, while attributes have their type annotation set to xs:untypedAtomic.

When validation is requested for a document node (that is, when validation is set to strict or lax, or when a type attribute is present), the following processing takes place:

  • [ERR XTTE1550] A type error occurs unless the children of the document node comprise exactly one element node, no text nodes, and zero or more comment and processing instruction nodes, in any order.

  • The single element node child is validated, using the supplied values of the validation and type attributes, as described in 24.2.1 Validating Constructed Elements and Attributes.

    Note:

    The type attribute on xsl:document and xsl:result-document, and on xsl:copy and xsl:copy-of when copying a document node, thus refers to the required type of the element node that is the only element child of the document node. It does not refer to the type of the document node itself.

  • The validation rule "Validation Root Valid (ID/IDREF)" is applied to the single element node child of the document node. This means that validation will fail if there are non-unique ID values or dangling IDREF values in the document tree.

  • Identity constraints, as defined in section 3.11 of [XML Schema Part 1], are checked. (This refers to constraints defined using xs:unique, xs:key, and xs:keyref.)

  • There is no check that the tree contains unparsed entities whose names match the values of nodes of type xs:ENTITY or xs:ENTITIES. This is because there is no facility in XSLT 3.0 to create unparsed entities in a result tree. It is possible to add unparsed entity declarations to the result document by referencing a suitable DOCTYPE during serialization.

  • There is no check that the document contains notations whose names match the values of nodes of type xs:NOTATION. This is because notations are not part of the XDM data model. It is possible to add notations to the result document by referencing a suitable DOCTYPE during serialization.

  • All other children of the document node (comments and processing instructions) are copied unchanged.

[ERR XTTE1555] It is a type error if, when validating a document node, document-level constraints are not satisfied. These constraints include identity constraints (xs:unique, xs:key, and xs:keyref) and ID/IDREF constraints.

25 Serialization

A processor may output a final result tree as a sequence of octets, although it is not required to be able to do so (see 26 Conformance). Stylesheet authors can use xsl:output declarations to specify how they wish result trees to be serialized. If a processor serializes a final result tree, it must do so as specified by these declarations.

The rules governing the output of the serializer are defined in [XSLT and XQuery Serialization]. The serialization is controlled using a number of serialization parameters. The values of these serialization parameters may be set within the stylesheet, using the xsl:output, xsl:result-document, and xsl:character-map declarations.

<!-- Category: declaration -->
<xsl:output
  name? = eqname
  method? = "xml" | "html" | "xhtml" | "text" | eqname
  byte-order-mark? = "yes" | "no"
  cdata-section-elements? = eqnames
  doctype-public? = string
  doctype-system? = string
  encoding? = string
  escape-uri-attributes? = "yes" | "no"
  include-content-type? = "yes" | "no"
  indent? = "yes" | "no"
  media-type? = string
  normalization-form? = "NFC" | "NFD" | "NFKC" | "NFKD" | "fully-normalized" | "none" | nmtoken
  omit-xml-declaration? = "yes" | "no"
  standalone? = "yes" | "no" | "omit"
  suppress-indentation? = eqnames
  undeclare-prefixes? = "yes" | "no"
  use-character-maps? = eqnames
  version? = nmtoken />

The xsl:output declaration is optional; if used, it must always appear as a top-level element within a stylesheet module.

A stylesheet may contain multiple xsl:output declarations and may include or import stylesheet modules that also contain xsl:output declarations. The name of an xsl:output declaration is the value of its name attribute, if any.

[Definition: All the xsl:output declarations within a package that share the same name are grouped into a named output definition; those that have no name are grouped into a single unnamed output definition.]

An output definition is scoped to a package. If this is a library package the output definition applies only to xsl:result-document instructions within the same package. If it is the top-level package, the output definition applies to xsl:result-document instructions within the same package and also to the implicit final result tree.

A stylesheet always includes an unnamed output definition; in the absence of an unnamed xsl:output declaration, the unnamed output definition is equivalent to the one that would be used if the stylesheet contained an xsl:output declaration having no attributes.

A named output definition is used when its name matches the format attribute used in an xsl:result-document element. The unnamed output definition is used when an xsl:result-document element omits the format attribute. It is also used when serializing the final result tree that is created implicitly in the absence of an xsl:result-document element.

All the xsl:output elements making up an output definition are effectively merged. For those attributes whose values are namespace-sensitive, the merging is done after lexical QNames have been converted into expanded QNames. For the cdata-section-elements and suppress-indentation attributes, the output definition uses the union of the values from all the constituent xsl:output declarations. For the use-character-maps attribute, the output definition uses the concatenation of the sequences of expanded QNames values from all the constituent xsl:output declarations, taking them in order of increasing import precedence, or where several have the same import precedence, in declaration order. For other attributes, the output definition uses the value of that attribute from the xsl:output declaration with the highest import precedence.

[ERR XTSE1560] It is a static error if two xsl:output declarations within an output definition specify explicit values for the same attribute (other than cdata-section-elements and use-character-maps), with the values of the attributes being not equal, unless there is another xsl:output declaration within the same output definition that has higher import precedence and that specifies an explicit value for the same attribute.

If none of the xsl:output declarations within an output definition specifies a value for a particular attribute, then the corresponding serialization parameter takes a default value. The default value depends on the chosen output method.

There are some serialization parameters that apply to some output methods but not to others. For example, the indent attribute has no effect on the text output method. If a value is supplied for an attribute that is inapplicable to the output method, its value is not passed to the serializer. The processor may validate the value of such an attribute, but is not required to do so.

An implementation may allow the attributes of the xsl:output declaration to be overridden, or the default values to be changed, using the API that controls the transformation.

The location to which final result trees are serialized (whether in filestore or elsewhere) is implementation-defined (which in practice may mean that it is controlled using an implementation-defined API). However, these locations must satisfy the constraint that when two final result trees are both created (implicitly or explicitly) using relative URI references in the href attribute of the xsl:result-document instruction, then these relative URI references may be used to construct references from one tree to the other, and such references must remain valid when both result trees are serialized.

The method attribute on the xsl:output element identifies the overall method that is to be used for outputting the final result tree.

[ERR XTSE1570] The value must (if present) be a valid EQName. If it is a lexical QName with no a prefix, then it identifies a method specified in [XSLT and XQuery Serialization] and must be one of xml, html, xhtml, or text. If it is a lexical QName with a prefix, then the lexical QName is expanded into an expanded QName as described in 5.1 Qualified Names; the expanded QName identifies the output method; the behavior in this case is not specified by this document.

The default for the method attribute depends on the contents of the tree being serialized, and is chosen as follows. If the document node of the final result tree has an element child, and any text nodes preceding the first element child of the document node of the result tree contain only whitespace characters, then:

In all other cases, the default output method is xml.

The default output method is used if the selected output definition does not include a method attribute.

The other attributes on xsl:output provide parameters for the output method. The following attributes are allowed:

If the processor performs serialization, then it must signal any non-recoverable serialization errors that occur. These have the same effect as non-recoverable dynamic errors: that is, the processor must signal the error and must not finish as if the transformation had been successful.

25.1 Character Maps

[Definition: A character map allows a specific character appearing in a text or attribute node in the final result tree to be substituted by a specified string of characters during serialization.] The effect of character maps is defined in [XSLT and XQuery Serialization].

The character map that is supplied as a parameter to the serializer is determined from the xsl:character-map elements referenced from the xsl:output declaration for the selected output definition.

The xsl:character-map element is a declaration that may appear as a child of the xsl:stylesheet element.

<!-- Category: declaration -->
<xsl:character-map
  name = eqname
  use-character-maps? = eqnames >
  <!-- Content: (xsl:output-character*) -->
</xsl:character-map>

The xsl:character-map declaration declares a character map with a name and a set of character mappings. The character mappings are specified by means of xsl:output-character elements contained either directly within the xsl:character-map element, or in further character maps referenced in the use-character-maps attribute.

The required name attribute provides a name for the character map. When a character map is used by an output definition or another character map, the character map with the highest import precedence is used.

The name of a character map is local to the package in which its declaration appears; it may be referenced only from within the same package.

[ERR XTSE1580] It is a static error if the stylesheet contains two or more character maps with the same name and the same import precedence, unless it also contains another character map with the same name and higher import precedence.

The optional use-character-maps attribute lists the names of further character maps that are included into this character map.

[ERR XTSE1590] It is a static error if a name in the use-character-maps attribute of the xsl:output or xsl:character-map elements does not match the name attribute of any xsl:character-map in the stylesheet.

[ERR XTSE1600] It is a static error if a character map references itself, directly or indirectly, via a name in the use-character-maps attribute.

It is not an error if the same character map is referenced more than once, directly or indirectly.

An output definition, after recursive expansion of character maps referenced via its use-character-maps attribute, may contain several mappings for the same character. In this situation, the last character mapping takes precedence. To establish the ordering, the following rules are used:

  • Within a single xsl:character-map element, the characters defined in character maps referenced in the use-character-maps attribute are considered before the characters defined in the child xsl:output-character elements.

  • The character maps referenced in a single use-character-maps attribute are considered in the order in which they are listed in that attribute. The expansion is depth-first: each referenced character map is fully expanded before the next one is considered.

  • Two xsl:output-character elements appearing as children of the same xsl:character-map element are considered in document order.

The xsl:output-character element is defined as follows:

<xsl:output-character
  character = char
  string = string />

The character map that is passed as a parameter to the serializer contains a mapping for the character specified in the character attribute to the string specified in the string attribute.

Character mapping is not applied to characters for which output escaping has been disabled as described in 25.2 Disabling Output Escaping.

If a character is mapped, then it is not subjected to XML or HTML escaping.

Example: Using Character Maps to Generate Non-XML Output

Character maps can be useful when producing serialized output in a format that resembles, but is not strictly conformant to, HTML or XML. For example, when the output is a JSP page, there might be a need to generate the output:

<jsp:setProperty name="user" property="id" value='<%= "id" + idValue %>'/>

Although this output is not well-formed XML or HTML, it is valid in Java Server Pages. This can be achieved by allocating three Unicode characters (which are not needed for any other purpose) to represent the strings <%, %>, and ", for example:

<xsl:character-map name="jsp">
  <xsl:output-character character="«" string="&lt;%"/>   
  <xsl:output-character character="»" string="%&gt;"/>
  <xsl:output-character character="§" string='"'/>
</xsl:character-map>

When this character map is referenced in the xsl:output declaration, the required output can be produced by writing the following in the stylesheet:

<jsp:setProperty name="user" property="id" value='«= §id§ + idValue »'/>

This works on the assumption that when an apostrophe or quotation mark is generated as part of an attribute value by the use of character maps, the serializer will (where possible) use the other choice of delimiter around the attribute value.

 

Example: Constructing a Composite Character Map

The following example illustrates a composite character map constructed in a modular fashion:

<xsl:output name="htmlDoc" use-character-maps="htmlDoc" />

<xsl:character-map name="htmlDoc"
  use-character-maps="html-chars doc-entities windows-format" />
  
<xsl:character-map name="html-chars"
  use-character-maps="latin1 ..." />

<xsl:character-map name="latin1">
  <xsl:output-character character="&#160;" string="&amp;nbsp;" />
  <xsl:output-character character="&#161;" string="&amp;iexcl;" />
  ...
</xsl:character-map>

<xsl:character-map name="doc-entities">
  <xsl:output-character character="&#xE400;" string="&amp;t-and-c;" />
  <xsl:output-character character="&#xE401;" string="&amp;chap1;" />
  <xsl:output-character character="&#xE402;" string="&amp;chap2;" />
  ...
</xsl:character-map>

<xsl:character-map name="windows-format">
  <!-- newlines as CRLF -->
  <xsl:output-character character="&#xA;" string="&#xD;&#xA;" />

  <!-- tabs as three spaces -->
  <xsl:output-character character="&#x9;" string="   " />

  <!-- images for special characters -->
  <xsl:output-character character="&#xF001;"
    string="&lt;img src='special1.gif' /&gt;" />
  <xsl:output-character character="&#xF002;"
    string="&lt;img src='special2.gif' /&gt;" />
  ...
</xsl:character-map>

25.2 Disabling Output Escaping

Normally, when using the XML, HTML, or XHTML output method, the serializer will escape special characters such as & and < when outputting text nodes. This ensures that the output is well-formed. However, it is sometimes convenient to be able to produce output that is almost, but not quite well-formed XML; for example, the output may include ill-formed sections which are intended to be transformed into well-formed XML by a subsequent non-XML-aware process. For this reason, XSLT defines a mechanism for disabling output escaping.

This feature is deprecated.

This is an optional feature: it is not required that a XSLT processor that implements the serialization option should offer the ability to disable output escaping, and there is no conformance level that requires this feature.

This feature requires an extension to the serializer described in [XSLT and XQuery Serialization]. Conceptually, the final result tree provides an additional boolean property disable-escaping associated with every character in a text node. When this property is set, the normal action of the serializer to escape special characters such as & and < is suppressed.

An xsl:value-of or xsl:text element may have a disable-output-escaping attribute; the allowed values are yes or no. The default is no; if the value is yes, then every character in the text node generated by evaluating the xsl:value-of or xsl:text element should have the disable-output property set.

Example: Disable Output Escaping

For example,

<xsl:text disable-output-escaping="yes">&lt;</xsl:text>

should generate the single character <.

If output escaping is disabled for an xsl:value-of or xsl:text instruction evaluated when temporary output state is in effect, the request to disable output escaping is ignored.

If output escaping is disabled for text within an element that would normally be output using a CDATA section, because the element is listed in the cdata-section-elements, then the relevant text will not be included in a CDATA section. In effect, CDATA is treated as an alternative escaping mechanism, which is disabled by the disable-output-escaping option.

Example: Interaction of Output Escaping and CDATA

For example, if <xsl:output cdata-section-elements="title"/> is specified, then the following instructions:

<title>
  <xsl:text disable-output-escaping="yes">This is not &lt;hr/&gt; 
                                          good coding practice</xsl:text>
</title>

should generate the output:

<title><![CDATA[This is not ]]><hr/><![CDATA[ good coding practice]]></title>

The disable-output-escaping attribute may be used with the html output method as well as with the xml output method. The text output method ignores the disable-output-escaping attribute, since it does not perform any output escaping.

A processor will only be able to disable output escaping if it controls how the final result tree is output. This might not always be the case. For example, the result tree might be used as a source tree for another XSLT transformation instead of being output. It is implementation-defined whether (and under what circumstances) disabling output escaping is supported.

[ERR XTRE1620] It is a recoverable dynamic error if an xsl:value-of or xsl:text instruction specifies that output escaping is to be disabled and the implementation does not support this. The optional recovery action is to ignore the disable-output-escaping attribute.

[ERR XTRE1630] It is a recoverable dynamic error if an xsl:value-of or xsl:text instruction specifies that output escaping is to be disabled when writing to a final result tree that is not being serialized. The optional recovery action is to ignore the disable-output-escaping attribute.

If output escaping is disabled for a character that is not representable in the encoding that the processor is using for output, the request to disable output escaping is ignored in respect of that character.

Since disabling output escaping might not work with all implementations and can result in XML that is not well-formed, it should be used only when there is no alternative.

Note:

The facility to define character maps for use during serialization, as described in 25.1 Character Maps, has been produced as an alternative mechanism that can be used in many situations where disabling of output escaping was previously necessary, without the same difficulties.

26 Conformance

A processor that claims conformance with this specification must claim conformance either as a basic XSLT processor or as a schema-aware XSLT processor. The rules for these two conformance levels are defined in the following sections.

A processor that claims conformance at either of these two levels may additionally claim conformance with either or both of the following optional features: the serialization feature, defined in 26.3 Serialization Feature, and the backwards compatibility feature, defined in 26.4 Compatibility Features.

Note:

There is no conformance level or feature defined in this specification that requires implementation of the static typing features described in [XPath 3.0]. An XSLT processor may provide a user option to invoke static typing, but to be conformant with this specification it must allow a stylesheet to be processed with static typing disabled. The interaction of XSLT stylesheets with the static typing feature of XPath 3.0 has not been specified, so the results of using static typing, if available, are implementation-defined.

An XSLT processor takes as its inputs a stylesheet and one or more XDM trees conforming to the data model defined in [Data Model]. It is not required that the processor supports any particular method of constructing XDM trees, but conformance can only be tested if it provides a mechanism that enables XDM trees representing the stylesheet and primary source document to be constructed and supplied as input to the processor.

The output of the XSLT processor consists of zero or more final result trees. It is not required that the processor supports any particular method of accessing a final result tree, but if it does not support the serialization module, conformance can only be tested if it provides some alternative mechanism that enables access to the results of the transformation.

Certain facilities in this specification are described as producing implementation-defined results. A claim that asserts conformance with this specification must be accompanied by documentation stating the effect of each implementation-defined feature. For convenience, a non-normative checklist of implementation-defined features is provided at E Checklist of Implementation-Defined Features.

A conforming processor must signal any static error occurring in the stylesheet, or in any XPath expression, except where specified otherwise either for individual error conditions or under the general provisions for forwards compatible behavior (see 3.11 Forwards Compatible Processing). After signaling such an error, the processor may continue for the purpose of signaling additional errors, but must terminate abnormally without performing any transformation.

When a dynamic error occurs during the course of a transformation, the action depends on whether the error is classified as a recoverable error. If a non-recoverable error occurs, the processor must signal it and must eventually terminate abnormally. If a recoverable error occurs, the processor must either signal it and terminate abnormally, or it must take the defined recovery action and continue processing.

Some errors, notably type errors, may be treated as static errors or dynamic errors at the discretion of the processor.

A conforming processor may impose limits on the processing resources consumed by the processing of a stylesheet.

26.1 Basic XSLT Processor

[Definition: A basic XSLT processor is an XSLT processor that implements all the mandatory requirements of this specification with the exception of certain explicitly identified constructs related to schema processing.] These constructs are listed below.

The mandatory requirements of this specification are taken to include the mandatory requirements of XPath 3.0, as described in [XPath 3.0]. A requirement is mandatory unless the specification includes wording (such as the use of the words should or may) that clearly indicates that it is optional.

A basic XSLT processor must enforce the following restrictions. It must signal a static or dynamic error when the restriction is violated, as described below.

[ERR XTSE1650] A basic XSLT processor must signal a static error if the stylesheet includes an xsl:import-schema declaration.

Note:

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

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

Note:

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

[ERR XTSE1660] A basic XSLT processor must signal a static error if the stylesheet includes an [xsl:]type attribute, or an [xsl:]validation or default-validation attribute with a value other than strip, preserve, or lax.

A basic XSLT processor constrains the data model as follows:

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

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

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

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

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

[ERR XTDE1665] A basic XSLT processor must raise a non-recoverable dynamic error if the input to the processor includes a node with a type annotation other than xs:untyped or xs:untypedAtomic, or an atomic value of a type other than those which a basic XSLT processor supports. This error will not arise if the input-type-annotations attribute is set to strip.

Note:

Although this is expressed in terms of a requirement to detect invalid input, an alternative approach is for a basic XSLT processor to prevent this error condition occurring, by not providing any interfaces that would allow the situation to arise. A processor might, for example, implement a mapping from the PSVI to the data model that loses all non-trivial type annotations; or it might not accept input from a PSVI at all.

The phrase input to the processor is deliberately wide: it includes the tree containing the initial context item, trees passed as stylesheet parameters, trees accessed using the document, docFO30, and collectionFO30 functions, and trees returned by extension functions and extension instructions.

26.2 Schema-Aware XSLT Processor

[Definition: A schema-aware XSLT processor is an XSLT processor that implements all the mandatory requirements of this specification, including those features that a basic XSLT processor signals as an error. The mandatory requirements of this specification are taken to include the mandatory requirements of XPath 3.0, as described in [XPath 3.0]. A requirement is mandatory unless the specification includes wording (such as the use of the words should or may) that clearly indicates that it is optional.]

26.3 Serialization Feature

[Definition: A processor that claims conformance with the serialization feature must support the conversion of a final result tree to a sequence of octets following the rules defined in 25 Serialization.] It must respect all the attributes of the xsl:output and xsl:character-map declarations, and must provide all four output methods, xml, xhtml, html, and text. Where the specification uses words such as must and required, then it must serialize the result tree in precisely the way described; in other cases it may use an alternative, equivalent representation.

A processor may claim conformance with the serialization feature whether or not it supports the setting disable-output-escaping="yes" on xsl:text, or xsl:value-of.

A processor that does not claim conformance with the serialization feature must not signal an error merely because the stylesheet contains xsl:output or xsl:character-map declarations, or serialization attributes on the xsl:result-document instruction. Such a processor may check that these declarations and attributes have valid values, but is not required to do so. Apart from optional validation, these declarations should be ignored.

26.4 Compatibility Features

[Definition: A processor that claims conformance with the XSLT 1.0 compatibility feature must support the processing of stylesheet instructions and XPath expressions with XSLT 1.0 behavior, as defined in 3.10 Backwards Compatible Processing.]

[Definition: A processor that claims conformance with the XSLT 2.0 compatibility feature must support the processing of stylesheet instructions and XPath expressions with XSLT 2.0 behavior, as defined in 3.10 Backwards Compatible Processing.]

Note that a processor that does not claim conformance with the XSLT 1.0 compatibility feature must raise a non-recoverable dynamic error if an instruction is evaluated whose effective version is 1.0; and similarly, a processor that does not claim conformance with the XSLT 2.0 compatibility feature must raise a non-recoverable dynamic error if an instruction is evaluated whose effective version is 2.0. [see ERR XTDE0160].

Note:

The reason this is a dynamic error rather than a static error is to allow stylesheets to contain conditional logic, following different paths depending on whether the XSLT processor implements XSLT 1.0, 2.0, or 3.0. The selection of which path to use can be controlled by using the system-property function to test the xsl:version system property.

A processor that claims conformance with the XSLT 1.0 compatibility feature must permit the use of the namespace axis in XPath expressions when backwards compatible behavior is enabled. In all other circumstances, support for the namespace axis is optional.

Note:

Currently, there are no incompatibilities between 3.0 and 2.0 that justify this machinery. This will be reviewed at a later stage of development of the specification.

26.5 Streaming Feature

[Definition: A processor that claims conformance with the streaming feature must ....]

Issue 12 (streaming-conformance):

We need to define the conformance rules for streaming processors.

A References

A.1 Normative References

Data Model
XQuery and XPath Data Model (XDM) 3.0, Norman Walsh, John Snelson, Editors. World Wide Web Consortium, 13 December 2011. This version is http://www.w3.org/TR/2011/WD-xpath-datamodel-30-20111213/. The latest version is available at http://www.w3.org/TR/xpath-datamodel-30/.
Functions and Operators
XQuery and XPath Functions and Operators 3.0, Michael Kay, Editor. World Wide Web Consortium, 13 December 2011. This version is http://www.w3.org/TR/2011/WD-xpath-functions-30-20111213/. The latest version is available at http://www.w3.org/TR/xpath-functions-30/.
XML Information Set
XML Information Set (Second Edition), Richard Tobin and John Cowan, Editors. World Wide Web Consortium, 04 Feb 2004. This version is http://www.w3.org/TR/2004/REC-xml-infoset-20040204/. The latest version is available at http://www.w3.org/TR/xml-infoset/.
ISO 3166-1
ISO (International Organization for Standardization) Codes for the representation of names of countries and their subdivisions - Part 1: Country codes ISO 3166-1:1997. Second edition, 2006-11-20.
ISO 8601
ISO (International Organization for Standardization) Data elements and interchange formats - Information interchange - Representation of dates and times. ISO 8601:2004, Third edition, 2004-12-03.
XSLT and XQuery Serialization
XSLT and XQuery Serialization 3.0, Henry Zongaro, Editor. World Wide Web Consortium, 13 December 2011. This version is http://www.w3.org/TR/2011/WD-xslt-xquery-serialization-30-20111213/. The latest version is available at http://www.w3.org/TR/xslt-xquery-serialization-30/.
RFC 4627
IETF. The application/json Media Type for JavaScript Object Notation (JSON). July 2006. See http://www.ietf.org/rfc/rfc4627.txt
ECMA-262
ECMA International. ECMAScript Language Specification June 2011. See http://www.ecma-international.org/publications/files/ECMA-ST/Ecma-262.pdf.
XML 1.0
World Wide Web Consortium. Extensible Markup Language (XML) 1.0. W3C Recommendation. See http://www.w3.org/TR/REC-xml/. The edition of XML 1.0 must be no earlier than the Third Edition; the edition used is implementation-defined, but we recommend that implementations use the latest version.
XML 1.1
Extensible Markup Language (XML) 1.1 (Second Edition), Eve Maler, Jean Paoli, John Cowan, et. al., Editors. World Wide Web Consortium, 16 Aug 2006. This version is http://www.w3.org/TR/2006/REC-xml11-20060816. The latest version is available at http://www.w3.org/TR/xml11/.
XML Base
XML Base (Second Edition), Jonathan Marsh and Richard Tobin, Editors. World Wide Web Consortium, 28 Jan 2009. This version is http://www.w3.org/TR/2009/REC-xmlbase-20090128/. The latest version is available at http://www.w3.org/TR/xmlbase/.
xml:id
xml:id Version 1.0, Norman Walsh, Daniel Veillard, and Jonathan Marsh, Editors. World Wide Web Consortium, 09 Sep 2005. This version is http://www.w3.org/TR/2005/REC-xml-id-20050909/. The latest version is available at http://www.w3.org/TR/xml-id/.
Namespaces in XML
Namespaces in XML 1.0 (Third Edition), Dave Hollander, Richard Tobin, Tim Bray, et. al., Editors. World Wide Web Consortium, 08 Dec 2009. This version is http://www.w3.org/TR/2009/REC-xml-names-20091208/. The latest version is available at http://www.w3.org/TR/xml-names/.
Namespaces in XML 1.1
Namespaces in XML 1.1 (Second Edition), Dave Hollander, Tim Bray, Andrew Layman, and Richard Tobin, Editors. World Wide Web Consortium, 16 Aug 2006. This version is http://www.w3.org/TR/2006/REC-xml-names11-20060816. The latest version is available at http://www.w3.org/TR/xml-names11/.
XML Schema Part 1
XML Schema Part 1: Structures Second Edition, David Beech, Henry S. Thompson, Murray Maloney, and Noah Mendelsohn, Editors. World Wide Web Consortium, 28 Oct 2004. This version is http://www.w3.org/TR/2004/REC-xmlschema-1-20041028/. The latest version is available at http://www.w3.org/TR/xmlschema-1/.
XML Schema Part 2
XML Schema Part 2: Datatypes Second Edition, Ashok Malhotra and Paul V. Biron, Editors. World Wide Web Consortium, 28 Oct 2004. This version is http://www.w3.org/TR/2004/REC-xmlschema-2-20041028/. The latest version is available at http://www.w3.org/TR/xmlschema-2/.
XML Schema
World Wide Web Consortium. XML Schema Definition Language (XSD) 1.1 Part 1: Structures. W3C Working Draft 3 December 2009. See http://www.w3.org/TR/xmlschema11-1/
XPath 3.0
XML Path Language (XPath) 3.0, Jonathan Robie, Don Chamberlin, Michael Dyck, John Snelson, Editors. World Wide Web Consortium, 13 December 2011. This version is http://www.w3.org/TR/2011/WD-xpath-30-20111213/. The latest version is available at http://www.w3.org/TR/xpath-30/.
XSLT Media Type
World Wide Web Consortium. Registration of MIME Media Type application/xslt+xml. In Appendix B.1 of the XSLT 2.0 specification.

A.2 Other References

Calendrical Calculations
Edward M. Reingold and Nachum Dershowitz. Calendrical Calculations Millennium edition (2nd Edition). Cambridge University Press, ISBN 0 521 77752 6
DOM Level 2
Document Object Model (DOM) Level 2 Core Specification, Philippe Le Hégaret, Steve Byrne, Gavin Nicol, et. al., Editors. World Wide Web Consortium, 13 Nov 2000. This version is http://www.w3.org/TR/2000/REC-DOM-Level-2-Core-20001113. The latest version is available at http://www.w3.org/TR/DOM-Level-2-Core/.
rfc2119
S. Bradner. Key words for use in RFCs to Indicate Requirement Levels. IETF RFC 2119. See http://www.ietf.org/rfc/rfc2119.txt.
RFC2376
E. Whitehead, M. Murata. XML Media Types. IETF RFC 2376. See http://www.ietf.org/rfc/rfc2376.txt.
RFC3023
M. Murata, S. St.Laurent, and D. Cohn. XML Media Types. IETF RFC 3023. See http://www.ietf.org/rfc/rfc3023.txt. References to RFC 3023 should be taken to refer to any document that supersedes RFC 3023.
RFC3986
T. Berners-Lee, R. Fielding, and L. Masinter. Uniform Resource Identifiers (URI): Generic Syntax. IETF RFC 3986. See http://www.ietf.org/rfc/rfc3986.txt.
RFC3987
M. Duerst, M. Suignard. Internationalized Resource Identifiers (IRIs). IETF RFC 3987. See http://www.ietf.org/rfc/rfc3987.txt.
Marian & Siméon
Amélie Marian and Jérôme Siméon. Projecting XML Documents. VLDB'2003, Berlin, Germany, September 2003. See http://portal.acm.org/citation.cfm?id=1315471
STX
Petr Cimprich et al, Streaming Transformations for XML (STX) Version 1.0. Working Draft 27 April 2007. See http://stx.sourceforge.net/documents/spec-stx-20070427.html
UNICODE TR10
Unicode Consortium. Unicode Technical Standard #10. Unicode Collation Algorithm. Unicode Technical Report. See http://www.unicode.org/reports/tr10/.
XInclude
XML Inclusions (XInclude) Version 1.0 (Second Edition), Daniel Veillard, David Orchard, and Jonathan Marsh, Editors. World Wide Web Consortium, 15 Nov 2006. This version is http://www.w3.org/TR/2006/REC-xinclude-20061115/. The latest version is available at http://www.w3.org/TR/xinclude/.
XLink
XML Linking Language (XLink) Version 1.0, Eve Maler, Steven DeRose, and David Orchard, Editors. World Wide Web Consortium, 27 Jun 2001. This version is http://www.w3.org/TR/2001/REC-xlink-20010627/. The latest version is available at http://www.w3.org/TR/xlink/.
XML Schema 1.0 and XML 1.1
World Wide Web Consortium. Processing XML 1.1 documents with XML Schema 1.0 processors. W3C Working Group Note 11 May 2005. See http://www.w3.org/TR/2005/NOTE-xml11schema10-20050511/
XML Stylesheet
Associating Style Sheets with XML documents, James Clark, Editor. World Wide Web Consortium, 29 Jun 1999. This version is http://www.w3.org/1999/06/REC-xml-stylesheet-19990629. The latest version is available at http://www.w3.org/TR/xml-stylesheet.
XPointer Framework
XPointer Framework, Jonathan Marsh, Paul Grosso, Eve Maler, and Norman Walsh, Editors. World Wide Web Consortium, 25 Mar 2003. This version is http://www.w3.org/TR/2003/REC-xptr-framework-20030325/. The latest version is available at http://www.w3.org/TR/xptr-framework/.
XSL-FO
Extensible Stylesheet Language (XSL) Version 1.1, Anders Berglund, Editor. World Wide Web Consortium, 05 Dec 2006. This version is http://www.w3.org/TR/2006/REC-xsl11-20061205/. The latest version is available at http://www.w3.org/TR/xsl11/.
XSLT 1.0
XSL Transformations (XSLT) Version 1.0, James Clark, Editor. World Wide Web Consortium, 16 Nov 1999. This version is http://www.w3.org/TR/1999/REC-xslt-19991116. The latest version is available at http://www.w3.org/TR/xslt.
XSLT 2.0
XSL Transformations (XSLT) Version 2.0 (Second Edition), Michael Kay, Editor. World Wide Web Consortium, 23 January 2007. This version is http://www.w3.org/TR/2007/REC-xslt20-20070123/. The latest version is available at http://www.w3.org/TR/xslt20/.

B Glossary (Non-Normative)

absent

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

accumulator function

The functions declared in an xsl:accumulator declaration are referred to as accumulator functions.

alias

A stylesheet can use the xsl:namespace-alias element to declare that a literal namespace URI is being used as an alias for a target namespace URI.

arity

The arity of a stylesheet function is the number of xsl:param elements in the function definition.

atomize

The term atomization is defined in Section 2.4.2 Atomization XP30. 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].

attribute set

The xsl:attribute-set element defines a named attribute set: that is, a collection of attribute definitions that can be used repeatedly on different constructed elements.

attribute value template

In an attribute that is designated as an attribute value template, such as an attribute of a literal result element, an expression can be used by surrounding the expression with curly brackets ({})

backwards compatible behavior

An element is processed with backwards compatible behavior if its effective version is less than 3.0.

base output URI

The base output URI is a URI to be used as the base URI when resolving a relative URI reference allocated to a final result tree. If the transformation generates more than one final result tree, then typically each one will be allocated a URI relative to this base URI.

basic XSLT processor

A basic XSLT processor is an XSLT processor that implements all the mandatory requirements of this specification with the exception of certain explicitly identified constructs related to schema processing.

character map

A character map allows a specific character appearing in a text or attribute node in the final result tree to be substituted by a specified string of characters during serialization.

child selection expression

An expression is a child-selection expression if it is any of the following:

circularity

A circularity is said to exist if a construct such as a global variable, an attribute set, or a key, is defined in terms of itself. For example, if the expression or sequence constructor specifying the value of a global variable X references a global variable Y, then the value for Y must be computed before the value of X. A circularity exists if it is impossible to do this for all global variable definitions.

collation

Facilities in XSLT 3.0 and XPath 3.0 that require strings to be ordered rely on the concept of a named collation. A collation is a set of rules that determine whether two strings are equal, and if not, which of them is to be sorted before the other.

compatible

The signatures of two components are compatible if they present the same interface to the user of the component. The rules depend on the kind of component.

component

The term component is used to refer to any of the following: a stylesheet function, a named template, a mode, a attribute set, a global variable, or a mode.

composite merge key value

The ordered collection of merge key values computed for one item in a merge input sequence (one for each merge key component within the merge key specification) is referred to as a composite merge key value.

construct

The term construct refers to the union of the following: a sequence constructor, an instruction, an attribute set, an attribute value template, an expression, or a pattern.

consuming

A consuming construct is any construct deemed consuming by the rules in this section (19.3 Streamability Analysis).

context item

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.

context node

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.

context position

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

context size

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

core function

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

current captured substrings

While the xsl:matching-substring instruction is active, a set of current captured substrings is available, corresponding to the parenthesized sub-expressions of the regular expression.

current group

The evaluation context for XPath expressions includes a component called the current group, which is a sequence.

current grouping key

The evaluation context for XPath expressions includes a component called the current grouping key, which is a sequence of atomic values. The current grouping key is the grouping key shared in common by all the items within the current group.

current mode

At any point in the processing of a stylesheet, there is a current mode. When the transformation is initiated, the current mode is the initial mode, as described in 2.3 Initiating a Transformation. Whenever an xsl:apply-templates instruction is evaluated, the current mode becomes the mode selected by this instruction.

current template rule

At any point in the processing of a stylesheet, there may be a current template rule. Whenever a template rule is chosen as a result of evaluating xsl:apply-templates, xsl:apply-imports, or xsl:next-match, the template rule becomes the current template rule for the evaluation of the rule's sequence constructor. 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.

decimal format

All the xsl:decimal-format declarations in a package that share the same name are grouped into a named decimal format; those that have no name are grouped into a single unnamed decimal format.

declaration

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

declaration order

The declarations within a stylesheet level have a total ordering known as declaration order. The order of declarations within a stylesheet level is the same as the document order that would result if each stylesheet module were inserted textually in place of the xsl:include element that references it.

declaring package

The declaring package of a component is the package that contains the declaration of the component.

default collation

In this specification the term default collation means the collation that is used by XPath operators such as eq and lt appearing in XPath expressions within the stylesheet.

default priority

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.

defining element

A string in the form of a lexical QName may occur as the value of an attribute node in a stylesheet module, or within an XPath expression contained in 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 lexical QName.

deprecated

Some constructs defined in this specification are described as being deprecated. The use of this term implies that stylesheet authors should not use the construct, and that the construct may be removed in a later version of this specification.

dynamic error

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

effective value

The result of evaluating an attribute value template is referred to as the effective value of the attribute.

effective version

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.

embedded stylesheet module

An embedded stylesheet module is a stylesheet module that is embedded within another XML document, typically the source document that is being transformed.

EQName

An EQName is a string representing a expanded QName where the string, after removing leading and trailing whitespace, is in the form defined by the EQNameXP30 production in the XPath specification.

expanded QName

An expanded QName is a value in the value space of the xs:QName datatype as defined in the XDM data model (see [Data Model]): that is, a triple containing namespace prefix (optional), namespace URI (optional), and local name. Two expanded QNames are equal if the namespace URIs are the same (or both absent) and the local names are the same. The prefix plays no part in the comparison, but is used only if the expanded QName needs to be converted back to a string.

exposed visibility

The exposed visibility of a component is established by an xsl:expose element in the package manifest.

expression

Within this specification, the term XPath expression, or simply expression, means a string that matches the production ExprXP30 defined in [XPath 3.0].

extension attribute

An element from the XSLT namespace may have any attribute not from the XSLT namespace, provided that the expanded QName (see [XPath 3.0]) of the attribute has a non-null namespace URI. These attributes are referred to as extension attributes.

extension function

An extension function is a function that is available for use within an XPath expression, other than a core function defined in [Functions and Operators], an additional function defined in this XSLT specification, a constructor function named after an atomic type, or a stylesheet function defined using an xsl:function declaration.

extension instruction

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

extension namespace

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

final output state

The first of the two output states is called final output state. This state applies when instructions are writing to a final result tree.

final result tree

A final result tree is a result tree that forms part of the final output of a transformation. Once created, the contents of a final result tree are not accessible within the stylesheet itself.

focus

When a sequence constructor is evaluated, the processor keeps track of which items are being processed by means of a set of implicit variables referred to collectively as the focus.

forwards compatible behavior

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

free-ranging

A free-ranging construct is any construct deemed free-ranging by the rules in this section (19.3 Streamability Analysis).

function conversion rules

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

function parameter

An xsl:param element may appear as a child of an xsl:function element, before any non-xsl:param children of that element. Such a parameter is known as a function parameter. A function parameter is a local variable with the additional property that its value can be set when the function is called, using a function call in an XPath expression.

global variable

A top-level variable-binding element declares a global variable that is visible everywhere (except where it is shadowed by another binding).

group

The xsl:for-each-group instruction allocates the items in an input sequence into groups of items (that is, it establishes a collection of sequences) based either on common values of a grouping key, or on a pattern that the initial or final item in a group must match.

group-consuming

A group-consuming construct is any construct deemed group-consuming by the rules in this section (19.3 Streamability Analysis).

grouping key

If either of the group-by or group-adjacent attributes is present, then for each item in the population a set of grouping keys is calculated, as follows: the expression contained in the group-by or group-adjacent attribute is evaluated; the result is atomized; and any xs:untypedAtomic values are cast to xs:string. If composite="yes" is specified, there is a single grouping key whose value is the resulting sequence; otherwise, there is a set of grouping keys, consisting of the distinct atomic values present in the result sequence.

guaranteed streamable template

If any of the modes to which a template rule is applicable is a streamable mode, then the template rule must satisfy certain rules to ensure that it can be evaluated using streaming. A template that satisfies these rules is referred to as a guaranteed-streamable template.

guaranteed-streamable

A guaranteed-streamable construct is a construct that follows the rules given in 19.3 Streamability Analysis. Every processor that claims conformance as a streaming processor must be able to process such a construct using streaming, that is, by processing the contents of the source document on the fly as it is read, without the need to buffer the entire document or any entire element in memory.

homonymous

Two components are said to be homonymous if they have the same symbolic identifier.

implementation

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

implementation-defined

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

implementation-dependent

The term implementation-dependent refers to a feature where the behavior may vary from one implementation to another, and where the vendor is not expected to provide a full specification of the behavior.

import precedence

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.

import tree

The stylesheet levels making up a stylesheet are treated as forming an import tree. In the import tree, each stylesheet level has one child for each xsl:import declaration that it contains.

in-scope schema component

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.

incrementally consuming

An expression is incrementally consuming if it satisfies any of the following conditions:

inherited attribute expression

An inherited attribute expression is an expression that satisfies all of the following conditions:

inherited context

In an inherited context, the syntactic context of an expression is the same as the syntactic context of its containing expression.

initial context item

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

initial item

For each group, the item within the group that is first in population order is known as the initial item of the group.

initial mode

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.

initial sequence

The sequence to be sorted is referred to as the initial sequence.

initial template

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.

inspection context

An inspection context has the characteristic that when the value of the expression is a node, the containing expression can be evaluated without consuming the subtree rooted at that node.

instruction

An instruction is either an XSLT instruction or an extension instruction.

key

A key is defined as a set of xsl:key declarations in the same package that share the same name.

key specifier

The expression in the use attribute and the sequence constructor within an xsl:key declaration are referred to collectively as the key specifier. The key specifier determines the values that may be used to find a node using this key.

lexical QName

A lexical QName is a string representing a expanded QName where the string, after removing leading and trailing whitespace, is within the lexical space of the xs:QName datatype as defined in XML Schema (see [XML Schema Part 2]): that is, a local name optionally preceded by a namespace prefix and a colon.

literal namespace URI

A namespace URI in the stylesheet tree that is being used to specify a namespace URI in the result tree is called a literal namespace URI.

literal result element

In a sequence constructor, an element in the stylesheet that does not belong to the XSLT namespace and that is not an extension instruction (see 23.2 Extension Instructions) is classified as a literal result element.

local variable

As well as being allowed as a declaration, the xsl:variable element is also allowed in sequence constructors. Such a variable is known as a local variable.

map

A map comprises a collation and a set of entries. Each entry comprises a key which is an arbitrary atomic value, and an arbitrary sequence called the associated value. Within a map, no two entries have the same key, when compared using the eq operator under the map's collation. It is not necessary that all the keys should be mutually comparable (for example, they can include a mixture of integers and strings). Key values will never be of type xs:untypedAtomic, and they will never be the xs:float or xs:double value NaN.

merge activation

A merge activation is a single evaluation of the sequence constructor contained within the xsl:merge-action element, which occurs once for each distinct composite merge key value.

merge input sequence

A merge input sequence is an arbitrary sequenceDM30 of items which is already sorted according to the merge key specification for the corresponding merge source definition.

merge key component

A merge key component specifies one component of a merge key specification; it corresponds to a single xsl:merge-key element in the stylesheet.

merge key specification

A merge key specification consists of one or more adjacent xsl:merge-key elements which together define how the merge input sequences selected by a merge source definition are sorted. Each xsl:merge-key element defines one merge key component.

merge key value

For each item in a merge input sequence, a value is computed for each merge key component within the merge key specification. The value computed for an item by using the Nth merge key component is referred to as the Nth merge key value of that item.

merge source definition

A merge source definition is the definition of one kind of input to the merge operation. It selects zero or more merge input sequences, and it includes a merge key specification to define how the merge key values are computed for each such merge input sequence.

mode

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 20.1 fn:document) or when processing temporary trees.

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

motionless

A motionless construct is any construct deemed motionless by the rules in this section (19.3 Streamability Analysis).

named template

Templates can be invoked by name. An xsl:template element with a name attribute defines a named template.

namespace fixup

The rules for the individual XSLT instructions that construct a result tree (see 11 Creating Nodes 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.

navigation context

In a navigation context, the containing expression potentially performs arbitrary navigation from the returned node to other nodes in the same tree, or reordering of the nodes in a supplied node sequence, which is therefore incompatible with streaming.

node value context

In a node value context, the containing expression needs access to information obtained from the subtree rooted at the returned node.

non-contextual function call

The term non-contextual function call is used to refer to function calls that do not pass the dynamic context to the called function. This includes all calls on stylesheet functions and all dynamic function invocationsXP30, (that is calls to function items as permitted by XPath 3.0). 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.

non-recoverable dynamic error

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.

optional recovery action

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.

order of first appearance

There is a total ordering among groups referred to as the order of first appearance. A group G is defined to precede a group H in order of first appearance if the initial item of G precedes the initial item of H in population order. If two groups G and H have the same initial item (because the item is in both groups) then G precedes H if the grouping key of G precedes the grouping key of H in the sequence that results from evaluating the group-by expression of this initial item.

output definition

All the xsl:output declarations within a package that share the same name are grouped into a named output definition; those that have no name are grouped into a single unnamed output definition.

output state

Each instruction in the stylesheet is evaluated in one of two possible output states: final output state or temporary output state

override

A component in a using package may override a component in a used package, provided that the visibility of the component in the used package is either abstract or public. The overriding declaration is written as a child of the xsl:override element, which in turn appears as a child of xsl:use-package.

package

A package is represented by an xsl:package element, which will generally be the outermost element of an XML document.

package manifest

The content of the xsl:package element is referred to as the package manifest

parameter

The xsl:param element declares a parameter, which may be a stylesheet parameter, a template parameter, a function parameter, or an xsl:iterate parameter. A parameter is a variable with the additional property that its value can be set by the caller.

pattern

A pattern specifies a set of conditions on an item. An item that satisfies the conditions matches the pattern; an item that does not satisfy the conditions does not match the pattern.

picture string

The picture string is the string supplied as the second argument of the format-numberFO30 function.

place marker

The xsl:number instruction performs two tasks: firstly, determining a place marker (this is a sequence of integers, to allow for hierarchic numbering schemes such as 1.12.2 or 3(c)ii), and secondly, formatting the place marker for output as a text node in the result sequence.

population

The sequence of items to be grouped, which is referred to as the population, is determined by evaluating the XPath expression contained in the select attribute.

population order

The population is treated as a sequence; the order of items in this sequence is referred to as population order

post-descent instruction

A motionless instruction having a consuming instruction as a preceding sibling is referred to as a post-descent instruction.

potential visibility

The potential visibility of a component is established when the component is declared or accepted into a package.

pre-descent instruction

A motionless instruction having no consuming instruction as a preceding sibling is referred to as a pre-descent instruction.

principal stylesheet module

For a given transformation, one stylesheet module 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.12.2 Stylesheet Inclusion and 3.12.3 Stylesheet Import.

priority

The priority of a template rule is specified by the priority attribute on the xsl:template declaration. If no priority is specified explicitly for a template rule, its default priority is used, as defined in 6.5 Default Priority for Template Rules.

processing order

There is another total ordering among groups referred to as processing order. If group R precedes group S in processing order, then in the result sequence returned by the xsl:for-each-group instruction the items generated by processing group R will precede the items generated by processing group S.

processor

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

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

reference resolution

The process of identifying the component to which a symbolic reference applies (possibly chosen from several homonymous alternatives) is called reference binding.

required type

The context within a stylesheet where an XPath expression appears may specify the required type of the expression. The required type indicates the type of the value that the expression is expected to return.

reserved namespace

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

result tree

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

schema component

Type definitions and element and attribute declarations are referred to collectively as schema components.

schema instance namespace

The schema instance namespace http://www.w3.org/2001/XMLSchema-instance is used as defined in [XML Schema Part 1]

schema namespace

The schema namespace http://www.w3.org/2001/XMLSchema is used as defined in [XML Schema Part 1]

schema-aware XSLT processor

A schema-aware XSLT processor is an XSLT processor that implements all the mandatory requirements of this specification, including those features that a basic XSLT processor signals as an error. The mandatory requirements of this specification are taken to include the mandatory requirements of XPath 3.0, as described in [XPath 3.0]. A requirement is mandatory unless the specification includes wording (such as the use of the words should or may) that clearly indicates that it is optional.

sequence constructor

A sequence constructor is a sequence of zero or more sibling nodes in the stylesheet that can be evaluated to return a sequence of nodes, atomic values, and function items. The way that the resulting sequence is used depends on the containing instruction.

serialization

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

serialization error

If a transformation has successfully produced a 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.

serialization feature

A processor that claims conformance with the serialization feature must support the conversion of a final result tree to a sequence of octets following the rules defined in 25 Serialization.

shadows

A binding shadows another binding if the binding occurs at a point where the other binding is visible, and the bindings have the same name.

simplified stylesheet module

A simplified stylesheet module is a tree, or part of a tree, consisting of a literal result element together with its descendant nodes and associated attributes and namespaces. This element is not itself in the XSLT namespace, but it must have an xsl:version attribute, which implies that it must have a namespace node that declares a binding for the XSLT namespace. For further details see 3.9 Simplified Stylesheet Modules.

singleton focus

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

snapshot

A snapshot of a node N is a deep copy of N, as produced by the xsl:copy-of instruction with copy-namespaces set to yes and validation set to preserve, with the additional property that for every ancestor of N, the copy also has a corresponding ancestor whose name, node-kind, and base URI are the same as the corresponding ancestor of N, and that has copies of the attributes and namespaces of the corresponding ancestor of N. But the ancestor has a type annotation of xs:anyType, has the properties nilled, is-ID, and is-IDREF set to false, and has no children other than the child that is a copy of N or one of its ancestors.

snapshot

A point-copy of a node N is a node that has the same node kind, name, attribute values, in-scope namespaces, and base URI as N. The point-copy has no parent or siblings. If the type annotation of N is a simple type or a complex type with simple content, then the point-copy has the same type annotation, typed value and string value as N, and unless the string value is zero-length, a child text node whose content is the same as the string value (but with no comments or processing instructions among its children). If the type annotation of N is a complex type with complex content (including xs:anyType and xs:untyped) then the point-copy will have a type annotation of xs:untyped, a string value and typed value of a zero-length string, and no child nodes.

sort key component

Within a sort key specification, each xsl:sort element defines one sort key component.

sort key specification

A sort key specification is a sequence of one or more adjacent xsl:sort elements which together define rules for sorting the items in an input sequence to form a sorted sequence.

sort key value

For each item in the initial sequence, a value is computed for each sort key component within the sort key specification. The value computed for an item by using the Nth sort key component is referred to as the Nth sort key value of that item.

sorted sequence

The sequence after sorting as defined by the xsl:sort elements is referred to as the sorted sequence.

source tree

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, docFO30, and collectionFO30, 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.

stable

A sort key specification is said to be stable if its first xsl:sort element has no stable attribute, or has a stable attribute whose effective value is yes.

standalone stylesheet module

A standalone stylesheet module is a stylesheet module that comprises the whole of an XML document.

standard attributes

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.

standard error namespace

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.

standard function namespace

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.

standard stylesheet module

A standard stylesheet module is a tree, or part of a tree, consisting of an xsl:stylesheet or xsl:transform element (see 3.8 Stylesheet Element) together with its descendant nodes and associated attributes and namespaces.

static error

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

streamable mode

A streamable mode is a mode that is declared in an xsl:mode declaration with the attribute streamable="yes".

streamed document

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

streamed node

A streamed node is a node in a streamed document.

streaming

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

streaming feature

A processor that claims conformance with the streaming feature must ....

string value

The term string value is defined in Section 5.13 string-value Accessor DM30. Every node has a string value. For example, the string value of an element is the concatenation of the string values of all its descendant text nodes.

stylesheet

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

stylesheet function

An xsl:function declaration declares the name, parameters, and implementation of a stylesheet function that can be called from any XPath expression within the stylesheet.

stylesheet level

A stylesheet level is a collection of stylesheet modules connected using xsl:include declarations: specifically, two stylesheet modules A and B are part of the same stylesheet level if one of them includes the other by means of an xsl:include declaration, or if there is a third stylesheet module C that is in the same stylesheet level as both A and B.

stylesheet module

A package consists of one or more stylesheet modules, each one forming all or part of an XML document.

stylesheet parameter

A top-level xsl:param element declares a stylesheet parameter. A stylesheet parameter is a global variable with the additional property that its value can be supplied by the caller when a transformation is initiated.

supplied value

The value of the variable is computed using the expression given in the select attribute or the contained sequence constructor, as described in 9.3 Values of Variables and Parameters. This value is referred to as the supplied value of the variable.

sweep

Every construct has a sweep, which is a measure of the extent to which the current position in the input stream moves during the evaluation of the expression. The sweep is one of: motionless, group-consuming, consuming, or free-ranging.

symbolic identifier

The symbolic identifier of a component is a composite name used to identify the component uniquely within a package. The symbolic identifier comprises the kind of component (stylesheet function, named template, attribute set, global variable, or mode), the expanded QName of the component (namespace URI plus local name), and in the case of stylesheet functions, the arity.

symbolic reference

The declaration of a component includes constructs that can be interpreted as references to other components by means of their symbolic identifiers. These constructs are generically referred to as symbolic references. Examples of constructs that give rise to symbolic references are the name attribute of xsl:call-template; the [xsl:]use-attribute-sets attribute of xsl:copy, xsl:element, and literal result elements; the mode attribute of xsl:template and xsl:apply-templates; XPath variable references referring to global variables; and XPath function calls referring to stylesheet functions.

syntactic context

The classification of a construct depends on some cases on the syntactic context in which it appears. This is determined by the kind of construct in which it is immediately contained, and its role within the containing construct.

tail position

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

target expression

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

target namespace URI

The namespace URI that is to be used in the result tree as a substitute for a literal namespace URI is called the target namespace URI.

template

An xsl:template declaration defines a template, which contains a sequence constructor ; this sequence constructor is evaluated to determine the result of the template. A template can serve either as a template rule, invoked by matching items against a pattern, or as a named template, invoked explicitly by name. It is also possible for the same template to serve in both capacities.

template parameter

An xsl:param element may appear as a child of an xsl:template element, before any non-xsl:param children of that element. Such a parameter is known as a template parameter. A template parameter is a local variable with the additional property that its value can be set when the template is called, using any of the instructions xsl:call-template, xsl:apply-templates, xsl:apply-imports, or xsl:next-match.

template rule

A stylesheet contains a set of template rules (see 6 Template Rules). A template rule has three parts: a pattern that is matched against nodes, a (possibly empty) set of template parameters, and a sequence constructor that is evaluated to produce a sequence of items.

temporary output state

The second of the two output states is called temporary output state. This state applies when instructions are writing to a temporary tree or any other non-final destination.

temporary tree

The term temporary tree means any tree that is neither a source tree nor a final result tree.

top-level

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

traversal

A traversal of a tree is a sequence of traversal events.

traversal-event

a traversal event (shortened to event in this section) is a pair comprising a phase (start or end) and a node.

tunnel parameter

A parameter passed to a template may be defined as a tunnel parameter. Tunnel parameters have the property that they are automatically passed on by the called template to any further templates that it calls, and so on recursively.

type annotation

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

type error

Certain errors are classified as type errors. A type error occurs when the value supplied as input to an operation is of the wrong type for that operation, for example when an integer is supplied to an operation that expects a node.

typed value

The term typed value is defined in Section 5.15 typed-value Accessor DM30. 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.

unnamed mode

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.

URI Reference

Within this specification, the term URI Reference, unless otherwise stated, refers to a string in the lexical space of the xs:anyURI datatype as defined in [XML Schema Part 2].

use

If a package Q contains an xsl:use-package element that references package P, then package Q is said to use package P. In this relationship package Q is referred to as the using package, package P as the used package.

user-defined data element

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

value

A variable is a binding between a name and a value. The value of a variable is any sequence (of nodes, atomic values, and/or function items), as defined in [Data Model].

variable

The xsl:variable element declares a variable, which may be a global variable or a local variable.

variable-binding element

The two elements xsl:variable and xsl:param are referred to as variable-binding elements

visibility

The visibility of a component is one of: private, public, abstract, final, or hidden.

whitespace text node

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

XML namespace

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

XPath 1.0 compatibility mode

The term XPath 1.0 compatibility mode is defined in Section 2.1.1 Static Context XP30. 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 3.0 and XPath 1.0.

XSLT 1.0 behavior

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

XSLT 1.0 compatibility feature

A processor that claims conformance with the XSLT 1.0 compatibility feature must support the processing of stylesheet instructions and XPath expressions with XSLT 1.0 behavior, as defined in 3.10 Backwards Compatible Processing.

XSLT 2.0 behavior

An element is processed with XSLT 2.0 behavior if its effective version is equal to 2.0.

XSLT 2.0 compatibility feature

A processor that claims conformance with the XSLT 2.0 compatibility feature must support the processing of stylesheet instructions and XPath expressions with XSLT 2.0 behavior, as defined in 3.10 Backwards Compatible Processing.

XSLT element

An XSLT element is an element in the XSLT namespace whose syntax and semantics are defined in this specification.

XSLT instruction

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

XSLT namespace

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

C Element Syntax Summary (Non-Normative)

The syntax of each XSLT element is summarized below, together with the context in the stylesheet where the element may appear. Some elements (specifically, instructions) are allowed as a child of any element that is allowed to contain a sequence constructor. These elements are:

xsl:accept

 

Model:

<xsl:accept
  component = "template" | "function" | "attribute-set" | "variable" | "mode"
  names = tokens
  visibility = "public" | "private" | "final" | "abstract" | "hidden" />

Permitted parent elements:

xsl:accumulator

 

Category: declaration

Model:

<xsl:accumulator
  name? = eqname
  post-descent? = eqname
  initial-value? = expression
  as? = sequence-type
  visibility? = "public" | "private" | "final" | "abstract"
  streamable? = "yes" | "no" >
  <!-- Content: xsl:accumulator-rule+ -->
</xsl:accumulator>

Permitted parent elements:

xsl:accumulator-rule

 

Model:

<xsl:accumulator-rule
  match = pattern
  phase? = "start" | "end"
  new-value = expression />

Permitted parent elements:

xsl:analyze-string

 

Category: instruction

Model:

<xsl:analyze-string
  select = expression
  regex = { string }
  flags? = { string } >
  <!-- Content: (xsl:matching-substring?, xsl:non-matching-substring?, xsl:fallback*) -->
</xsl:analyze-string>

Permitted parent elements:

  • any XSLT element whose content model is sequence constructor
  • any literal result element

xsl:apply-imports

 

Category: instruction

Model:

<xsl:apply-imports>
  <!-- Content: xsl:with-param* -->
</xsl:apply-imports>

Permitted parent elements:

  • any XSLT element whose content model is sequence constructor
  • any literal result element

xsl:apply-templates

 

Category: instruction

Model:

<xsl:apply-templates
  select? = expression
  mode? = token >
  <!-- Content: (xsl:sort | xsl:with-param)* -->
</xsl:apply-templates>

Permitted parent elements:

  • any XSLT element whose content model is sequence constructor
  • any literal result element

xsl:assert

 

Category: instruction

Model:

<xsl:assert
  enabled? = expression
  test = expression
  select? = expression
  error-code? = { eqname } >
  <!-- Content: sequence-constructor -->
</xsl:assert>

Permitted parent elements:

  • any XSLT element whose content model is sequence constructor
  • any literal result element

xsl:attribute

 

Category: instruction

Model:

<xsl:attribute
  name = { qname }
  namespace? = { uri }
  select? = expression
  separator? = { string }
  type? = eqname
  validation? = "strict" | "lax" | "preserve" | "strip"
  on-empty? = expression >
  <!-- Content: sequence-constructor -->
</xsl:attribute>

Permitted parent elements:

  • xsl:attribute-set
  • any XSLT element whose content model is sequence constructor
  • any literal result element

xsl:attribute-set

 

Category: declaration

Model:

<xsl:attribute-set
  name = eqname
  use-attribute-sets? = eqnames
  visibility? = "public" | "private" | "final" | "abstract" >
  <!-- Content: xsl:attribute* -->
</xsl:attribute-set>

Permitted parent elements:

xsl:break

 

Category: instruction

Model:

<xsl:break
  select? = expression >
  <!-- Content: (sequence-constructor) -->
</xsl:break>

Permitted parent elements:

  • any XSLT element whose content model is sequence constructor
  • any literal result element

xsl:call-template

 

Category: instruction

Model:

<xsl:call-template
  name = eqname >
  <!-- Content: xsl:with-param* -->
</xsl:call-template>

Permitted parent elements:

  • any XSLT element whose content model is sequence constructor
  • any literal result element

xsl:catch

 

Model:

<xsl:catch
  errors? = tokens
  select? = expression >
  <!-- Content: sequence-constructor -->
</xsl:catch>

Permitted parent elements:

xsl:character-map

 

Category: declaration

Model:

<xsl:character-map
  name = eqname
  use-character-maps? = eqnames >
  <!-- Content: (xsl:output-character*) -->
</xsl:character-map>

Permitted parent elements:

xsl:choose

 

Category: instruction

Model:

<xsl:choose>
  <!-- Content: (xsl:when+, xsl:otherwise?) -->
</xsl:choose>

Permitted parent elements:

  • any XSLT element whose content model is sequence constructor
  • any literal result element

xsl:comment

 

Category: instruction

Model:

<xsl:comment
  select? = expression >
  <!-- Content: sequence-constructor -->
</xsl:comment>

Permitted parent elements:

  • any XSLT element whose content model is sequence constructor
  • any literal result element

xsl:context-item

 

Model:

<xsl:context-item
  as? = sequence-type
  use? = "required" | "optional" | "prohibited" />

Permitted parent elements:

xsl:copy

 

Category: instruction

Model:

<xsl:copy
  select? = expression
  copy-namespaces? = "yes" | "no"
  inherit-namespaces? = "yes" | "no"
  use-attribute-sets? = eqnames
  type? = eqname
  validation? = "strict" | "lax" | "preserve" | "strip"
  on-empty? = expression >
  <!-- Content: sequence-constructor -->
</xsl:copy>

Permitted parent elements:

  • any XSLT element whose content model is sequence constructor
  • any literal result element

xsl:copy-of

 

Category: instruction

Model:

<xsl:copy-of
  select = expression
  copy-namespaces? = "yes" | "no"
  type? = eqname
  validation? = "strict" | "lax" | "preserve" | "strip" />

Permitted parent elements:

  • any XSLT element whose content model is sequence constructor
  • any literal result element

xsl:decimal-format

 

Category: declaration

Model:

<xsl:decimal-format
  name? = eqname
  decimal-separator? = char
  grouping-separator? = char
  infinity? = string
  minus-sign? = char
  NaN? = string
  percent? = char
  per-mille? = char
  zero-digit? = char
  digit? = char
  pattern-separator? = char />

Permitted parent elements:

xsl:document

 

Category: instruction

Model:

<xsl:document
  validation? = "strict" | "lax" | "preserve" | "strip"
  type? = eqname >
  <!-- Content: sequence-constructor -->
</xsl:document>

Permitted parent elements:

  • any XSLT element whose content model is sequence constructor
  • any literal result element

xsl:element

 

Category: instruction

Model:

<xsl:element
  name = { qname }
  namespace? = { uri }
  inherit-namespaces? = "yes" | "no"
  use-attribute-sets? = eqnames
  type? = eqname
  validation? = "strict" | "lax" | "preserve" | "strip"
  on-empty? = expression >
  <!-- Content: sequence-constructor -->
</xsl:element>

Permitted parent elements:

  • any XSLT element whose content model is sequence constructor
  • any literal result element

xsl:evaluate

 

Category: instruction

Model:

<xsl:evaluate
  xpath = expression
  as? = sequence-type
  base-uri? = { uri }
  context-item? = expression
  namespace-context? = expression
  schema-aware? = { "yes" | "no" } >
  <!-- Content: (xsl:with-param | xsl:fallback)* -->
</xsl:evaluate>

Permitted parent elements:

  • any XSLT element whose content model is sequence constructor
  • any literal result element

xsl:expose

 

Model:

<xsl:expose
  component = "template" | "function" | "attribute-set" | "variable" | "mode"
  names = tokens
  visibility = "public" | "private" | "final" | "abstract" />

Permitted parent elements:

xsl:fallback

 

Category: instruction

Model:

<xsl:fallback>
  <!-- Content: sequence-constructor -->
</xsl:fallback>

Permitted parent elements:

  • any XSLT element whose content model is sequence constructor
  • any literal result element

xsl:for-each

 

Category: instruction

Model:

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

Permitted parent elements:

  • any XSLT element whose content model is sequence constructor
  • any literal result element

xsl:for-each-group

 

Category: instruction

Model:

<xsl:for-each-group
  select = expression
  group-by? = expression
  group-adjacent? = expression
  group-starting-with? = pattern
  group-ending-with? = pattern
  bind-group? = eqname
  bind-grouping-key? = eqname
  composite? = "yes" | "no"
  collation? = { uri } >
  <!-- Content: (xsl:sort*, sequence-constructor) -->
</xsl:for-each-group>

Permitted parent elements:

  • any XSLT element whose content model is sequence constructor
  • any literal result element

xsl:fork

 

Category: instruction

Model:

<xsl:fork>
  <!-- Content: ((xsl:sequence | xsl:fallback))+ -->
</xsl:fork>

Permitted parent elements:

  • any XSLT element whose content model is sequence constructor
  • any literal result element

xsl:function

 

Category: declaration

Model:

<xsl:function
  name = eqname
  as? = sequence-type
  visibility? = "public" | "private" | "final" | "abstract"
  override? = "yes" | "no" >
  <!-- Content: (xsl:param*, sequence-constructor) -->
</xsl:function>

Permitted parent elements:

xsl:if

 

Category: instruction

Model:

<xsl:if
  test = expression >
  <!-- Content: sequence-constructor -->
</xsl:if>

Permitted parent elements:

  • any XSLT element whose content model is sequence constructor
  • any literal result element

xsl:import

 

Category: declaration

Model:

<xsl:import
  href = uri />

Permitted parent elements:

xsl:import-schema

 

Category: declaration

Model:

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

Permitted parent elements:

xsl:include

 

Category: declaration

Model:

<xsl:include
  href = uri />

Permitted parent elements:

xsl:iterate

 

Category: instruction

Model:

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

Permitted parent elements:

  • any XSLT element whose content model is sequence constructor
  • any literal result element

xsl:key

 

Category: declaration

Model:

<xsl:key
  name = eqname
  match = pattern
  use? = expression
  composite? = "yes" | "no"
  collation? = uri >
  <!-- Content: sequence-constructor -->
</xsl:key>

Permitted parent elements:

xsl:matching-substring

 

Model:

<xsl:matching-substring>
  <!-- Content: sequence-constructor -->
</xsl:matching-substring>

Permitted parent elements:

xsl:merge

 

Category: instruction

Model:

<xsl:merge
  bind-group? = eqname
  bind-key? = eqname >
  <!-- Content: (xsl:merge-source+, xsl:merge-action, xsl:fallback*) -->
</xsl:merge>

Permitted parent elements:

  • any XSLT element whose content model is sequence constructor
  • any literal result element

xsl:merge-action

 

Model:

<xsl:merge-action>
  <!-- Content: (sequence-constructor) -->
</xsl:merge-action>

Permitted parent elements:

xsl:merge-key

 

Model:

<xsl:merge-key
  select? = expression
  lang? = { language }
  order? = { "ascending" | "descending" }
  collation? = { uri }
  case-order? = { "upper-first" | "lower-first" }
  data-type? = { "text" | "number" | eqname } >
  <!-- Content: sequence-constructor -->
</xsl:merge-key>

Permitted parent elements:

xsl:merge-source

 

Model:

<xsl:merge-source
  for-each? = expression
  select = expression
  bind-source? = eqname
  streamable? = "yes" | "no"
  sort-before-merge? = "yes" | "no" >
  <!-- Content: xsl:merge-key+ -->
</xsl:merge-source>

Permitted parent elements:

xsl:message

 

Category: instruction

Model:

<xsl:message
  select? = expression
  terminate? = { "yes" | "no" }
  error-code? = { eqname } >
  <!-- Content: sequence-constructor -->
</xsl:message>

Permitted parent elements:

  • any XSLT element whose content model is sequence constructor
  • any literal result element

xsl:mode

 

Category: declaration

Model:

<xsl:mode
  name? = eqname
  streamable? = "yes" | "no"
  initial? = "yes" | "no"
  on-no-match? = "deep-copy" | "shallow-copy" | "deep-skip" | "shallow-skip" | "text-only-copy" | "fail"
  on-multiple-match? = "use-last" | "fail"
  warning-on-no-match? = "yes" | "no"
  warning-on-multiple-match? = "yes" | "no"
  typed? = "yes" | "no" | "strict" | "lax" | "unspecified"
  visibility? = "public" | "private" | "final" >
  <!-- Content: (xsl:context-item?) -->
</xsl:mode>

Permitted parent elements:

xsl:namespace

 

Category: instruction

Model:

<xsl:namespace
  name = { ncname }
  select? = expression >
  <!-- Content: sequence-constructor -->
</xsl:namespace>

Permitted parent elements:

  • any XSLT element whose content model is sequence constructor
  • any literal result element

xsl:namespace-alias

 

Category: declaration

Model:

<xsl:namespace-alias
  stylesheet-prefix = prefix | "#default"
  result-prefix = prefix | "#default" />

Permitted parent elements:

xsl:next-iteration

 

Category: instruction

Model:

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

Permitted parent elements:

  • any XSLT element whose content model is sequence constructor
  • any literal result element

xsl:next-match

 

Category: instruction

Model:

<xsl:next-match>
  <!-- Content: (xsl:with-param | xsl:fallback)* -->
</xsl:next-match>

Permitted parent elements:

  • any XSLT element whose content model is sequence constructor
  • any literal result element

xsl:non-matching-substring

 

Model:

<xsl:non-matching-substring>
  <!-- Content: sequence-constructor -->
</xsl:non-matching-substring>

Permitted parent elements:

xsl:number

 

Category: instruction

Model:

<xsl:number
  value? = expression
  select? = expression
  level? = "single" | "multiple" | "any"
  count? = pattern
  from? = pattern
  format? = { string }
  lang? = { language }
  letter-value? = { "alphabetic" | "traditional" }
  ordinal? = { string }
  start-at? = { integer }
  grouping-separator? = { char }
  grouping-size? = { integer } />

Permitted parent elements:

  • any XSLT element whose content model is sequence constructor
  • any literal result element

xsl:on-completion

 

Model:

<xsl:on-completion
  select? = expression >
  <!-- Content: (sequence-constructor) -->
</xsl:on-completion>

Permitted parent elements:

xsl:otherwise

 

Model:

<xsl:otherwise>
  <!-- Content: sequence-constructor -->
</xsl:otherwise>

Permitted parent elements:

xsl:output

 

Category: declaration

Model:

<xsl:output
  name? = eqname
  method? = "xml" | "html" | "xhtml" | "text" | eqname
  byte-order-mark? = "yes" | "no"
  cdata-section-elements? = eqnames
  doctype-public? = string
  doctype-system? = string
  encoding? = string
  escape-uri-attributes? = "yes" | "no"
  include-content-type? = "yes" | "no"
  indent? = "yes" | "no"
  media-type? = string
  normalization-form? = "NFC" | "NFD" | "NFKC" | "NFKD" | "fully-normalized" | "none" | nmtoken
  omit-xml-declaration? = "yes" | "no"
  standalone? = "yes" | "no" | "omit"
  suppress-indentation? = eqnames
  undeclare-prefixes? = "yes" | "no"
  use-character-maps? = eqnames
  version? = nmtoken />

Permitted parent elements:

xsl:output-character

 

Model:

<xsl:output-character
  character = char
  string = string />

Permitted parent elements:

xsl:override

 

Model:

<xsl:override>
  <!-- Content: (xsl:template | xsl:function | xsl:variable | xsl:param | xsl:attribute-set)* -->
</xsl:override>

Permitted parent elements:

xsl:package

 

Model:

<xsl:package
  xsl:version? = decimal
  name? = uri
  package-version? = string >
  <!-- Content: (xsl:use-package*, (xsl:stylesheet | xsl:transform), xsl:expose*) -->
</xsl:package>

Permitted parent elements:

  • None

xsl:param

 

Category: declaration

Model:

<xsl:param
  name = eqname
  select? = expression
  as? = sequence-type
  required? = "yes" | "no"
  tunnel? = "yes" | "no"
  visibility? = "public" | "private" | "final" | "abstract" >
  <!-- Content: sequence-constructor -->
</xsl:param>

Permitted parent elements:

xsl:perform-sort

 

Category: instruction

Model:

<xsl:perform-sort
  select? = expression >
  <!-- Content: (xsl:sort+, sequence-constructor) -->
</xsl:perform-sort>

Permitted parent elements:

  • any XSLT element whose content model is sequence constructor
  • any literal result element

xsl:preserve-space

 

Category: declaration

Model:

<xsl:preserve-space
  elements = tokens />

Permitted parent elements:

xsl:processing-instruction

 

Category: instruction

Model:

<xsl:processing-instruction
  name = { ncname }
  select? = expression >
  <!-- Content: sequence-constructor -->
</xsl:processing-instruction>

Permitted parent elements:

  • any XSLT element whose content model is sequence constructor
  • any literal result element

xsl:result-document

 

Category: instruction

Model:

<xsl:result-document
  format? = { eqname }
  href? = { uri }
  validation? = "strict" | "lax" | "preserve" | "strip"
  type? = eqname
  method? = { "xml" | "html" | "xhtml" | "text" | eqname }
  byte-order-mark? = { "yes" | "no" }
  cdata-section-elements? = { eqnames }
  doctype-public? = { string }
  doctype-system? = { string }
  encoding? = { string }
  escape-uri-attributes? = { "yes" | "no" }
  include-content-type? = { "yes" | "no" }
  indent? = { "yes" | "no" }
  media-type? = { string }
  normalization-form? = { "NFC" | "NFD" | "NFKC" | "NFKD" | "fully-normalized" | "none" | nmtoken }
  omit-xml-declaration? = { "yes" | "no" }
  standalone? = { "yes" | "no" | "omit" }
  suppress-indentation? = { eqnames }
  undeclare-prefixes? = { "yes" | "no" }
  use-character-maps? = eqnames
  output-version? = { nmtoken } >
  <!-- Content: sequence-constructor -->
</xsl:result-document>

Permitted parent elements:

  • any XSLT element whose content model is sequence constructor
  • any literal result element

xsl:sequence

 

Category: instruction

Model:

<xsl:sequence
  select? = expression >
  <!-- Content: sequence-constructor -->
</xsl:sequence>

Permitted parent elements:

  • any XSLT element whose content model is sequence constructor
  • any literal result element

xsl:sort

 

Model:

<xsl:sort
  select? = expression
  lang? = { language }
  order? = { "ascending" | "descending" }
  collation? = { uri }
  stable? = { "yes" | "no" }
  case-order? = { "upper-first" | "lower-first" }
  data-type? = { "text" | "number" | eqname } >
  <!-- Content: sequence-constructor -->
</xsl:sort>

Permitted parent elements:

xsl:stream

 

Category: instruction

Model:

<xsl:stream
  href = { uri } >
  <!-- Content: sequence-constructor -->
</xsl:stream>

Permitted parent elements:

  • any XSLT element whose content model is sequence constructor
  • any literal result element

xsl:strip-space

 

Category: declaration

Model:

<xsl:strip-space
  elements = tokens />

Permitted parent elements:

xsl:stylesheet

 

Model:

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

Permitted parent elements:

  • None

xsl:template

 

Category: declaration

Model:

<xsl:template
  match? = pattern
  name? = eqname
  priority? = decimal
  mode? = tokens
  as? = sequence-type
  visibility? = "public" | "private" | "final" | "abstract" >
  <!-- Content: (xsl:context-item?, xsl:param*, sequence-constructor) -->
</xsl:template>

Permitted parent elements:

xsl:text

 

Category: instruction

Model:

<xsl:text
  [disable-output-escaping]? = "yes" | "no" >
  <!-- Content: #PCDATA -->
</xsl:text>

Permitted parent elements:

  • any XSLT element whose content model is sequence constructor
  • any literal result element

xsl:transform

 

Model:

<xsl:transform
  id? = id
  extension-element-prefixes? = prefixes
  exclude-result-prefixes? = prefixes
  version = decimal
  xpath-default-namespace? = uri
  default-validation? = "preserve" | "strip"
  default-collation? = uris
  default-mode? = eqname | "#unnamed"
  input-type-annotations? = "preserve" | "strip" | "unspecified" >
  <!-- Content: (xsl:use-package*, xsl:import*, other-declarations) -->
</xsl:transform>

Permitted parent elements:

  • None

xsl:try

 

Category: instruction

Model:

<xsl:try
  select? = expression >
  <!-- Content: (sequence-constructor, xsl:catch, (xsl:catch | xsl:fallback)*) -->
</xsl:try>

Permitted parent elements:

  • any XSLT element whose content model is sequence constructor
  • any literal result element

xsl:use-package

 

Model:

<xsl:use-package
  name? = uri
  package-version? = token >
  <!-- Content: (xsl:accept | xsl:override)* -->
</xsl:use-package>

Permitted parent elements:

xsl:value-of

 

Category: instruction

Model:

<xsl:value-of
  select? = expression
  separator? = { string }
  [disable-output-escaping]? = "yes" | "no" >
  <!-- Content: sequence-constructor -->
</xsl:value-of>

Permitted parent elements:

  • any XSLT element whose content model is sequence constructor
  • any literal result element

xsl:variable

 

Category: declaration instruction

Model:

<xsl:variable
  name = eqname
  select? = expression
  as? = sequence-type
  visibility? = "public" | "private" | "final" | "abstract" >
  <!-- Content: sequence-constructor -->
</xsl:variable>

Permitted parent elements:

xsl:when

 

Model:

<xsl:when
  test = expression >
  <!-- Content: sequence-constructor -->
</xsl:when>

Permitted parent elements:

xsl:with-param

 

Model:

<xsl:with-param
  name = eqname
  select? = expression
  as? = sequence-type
  tunnel? = "yes" | "no" >
  <!-- Content: sequence-constructor -->
</xsl:with-param>

Permitted parent elements:

D Summary of Error Conditions (Non-Normative)

This appendix provides a summary of error conditions that a processor may signal. This list includes all error codes defined in this specification, but this is not an exhaustive list of all errors that can occur. Implementations must signal errors using these error codes, and applications can test for these codes; however, when more than one rule in the specification is violated, different processors will not necessarily signal the same error code. Implementations are not required to signal errors using the descriptive text used here.

Note:

The appendix is non-normative because the same information is given normatively elsewhere.

Static errors

ERR XTSE0010

It is a static error if an XSLT-defined element is used in a context where it is not permitted, if a required attribute is omitted, or if the content of the element does not correspond to the content that is allowed for the element.

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

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.

ERR XTSE0110

The value of the version attribute must be a number: specifically, it must be a valid instance of the type xs:decimal as defined in [XML Schema Part 2].

ERR XTSE0120

An xsl:stylesheet element must not have any text node children.

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.

ERR XTSE0130

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

ERR XTSE0150

A literal result element that is used as the outermost element of a simplified stylesheet module must have an xsl:version attribute.

ERR XTSE0165

It is a static error if the processor is not able to retrieve the resource identified by the URI reference [ in the href attribute of xsl:include or xsl:import ] , or if the resource that is retrieved does not contain a stylesheet module conforming to this specification.

ERR XTSE0170

An xsl:include element must be a top-level element.

ERR XTSE0180

It is a static error if a stylesheet module directly or indirectly includes itself.

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.

ERR XTSE0210

It is a static error if a stylesheet module directly or indirectly imports itself.

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.

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.

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.

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

ERR XTSE0270

It is a static error if within any package the same NameTestXP30 appears in both an xsl:strip-space and an xsl:preserve-space declaration if both have the same import precedence. Two NameTests are considered the same if they match the same set of names (which can be determined by comparing them after expanding namespace prefixes to URIs).

ERR XTSE0280

In the case of a prefixed lexical QName used as the value (or as part of the value) of an attribute in the stylesheet, or appearing within an XPath expression in the stylesheet, it is a static error if the defining element has no namespace node whose name matches the prefix of the lexical QName.

ERR XTSE0340

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

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.

ERR XTSE0370

It is a static error if an unescaped right curly bracket occurs in a fixed part of an attribute value template.

ERR XTSE0500

An xsl:template element must have either a match attribute or a name attribute, or both. An xsl:template element that has no match attribute must have no mode attribute and no priority attribute. An xsl:template element that has no name attribute must have no visibility attribute.

ERR XTSE0530

The value of the priority attribute [ of the xsl:template element] must conform to the rules for the xs:decimal type defined in [XML Schema Part 2]. Negative values are permitted.

ERR XTSE0542

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

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.

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 19.3 Streamability Analysis.

ERR XTSE0550

It is a static error if the list [of modes in the mode attribute of xsl:template ] is empty, if the same token is included more than once in the list, if the list contains an invalid token, or if the token #all appears together with any other value.

ERR XTSE0580

It is a static error if the values of the name attribute of two sibling xsl:param elements represent the same expanded QName.

ERR XTSE0620

It is a static error if a variable-binding element has a select attribute and has non-empty content.

ERR XTSE0630

It is a static error if a stylesheet contains more than one binding of a global variable with the same name and same import precedence, unless it also contains another binding with the same name and higher import precedence.

ERR XTSE0650

It is a static error if a stylesheet contains an xsl:call-template instruction whose name attribute does not match the name attribute of any named template visible in the containing package (this includes any template defined in this package, as well as templates accepted from used packages whose visibility in this package is not hidden). For more details of the process of binding the called template, see 3.6.2.6 Binding References to Components.

ERR XTSE0660

It is a static error if a package contains more than one template with the same name and the same import precedence, unless it also contains a template with the same name and higher import precedence.

ERR XTSE0670

It is a static error if two or more sibling xsl:with-param elements have name attributes that represent the same expanded QName.

ERR XTSE0680

In the case of xsl:call-template, it is a static error to pass a non-tunnel parameter named x to a template that does not have a non-tunnel template parameter named x, unless the xsl:call-template instruction is processed with XSLT 1.0 behavior.

ERR XTSE0690

It is a static error if a template that is invoked using xsl:call-template declares a template parameter specifying required="yes" and not specifying tunnel="yes", if no value for this parameter is supplied by the calling xsl:call-template instruction.

ERR XTSE0710

It is a static error if the value of the use-attribute-sets attribute of an xsl:copy, xsl:element, or xsl:attribute-set element, or the xsl:use-attribute-sets attribute of a literal result element, is not a whitespace-separated sequence of EQNames, or if it contains a QName that does not match the name attribute of any xsl:attribute-set declaration in the stylesheet.

ERR XTSE0720

It is a static error if an xsl:attribute-set element directly or indirectly references itself via the names contained in the use-attribute-sets attribute.

ERR XTSE0740

It is a static error if a stylesheet function has a name that is in no namespace.

ERR XTSE0760

Because arguments to a stylesheet function call must all be specified, the xsl:param elements within an xsl:function element must not specify a default value: this means they must be empty, and must not have a select attribute.

ERR XTSE0770

It is a static error for a stylesheet to contain two or more functions with the same expanded QName, the same arity, and the same import precedence, unless there is another function with the same expanded QName and arity, and a higher import precedence.

ERR XTSE0805

It is a static error if an attribute on a literal result element is in the XSLT namespace, unless it is one of the attributes explicitly defined in this specification.

ERR XTSE0808

It is a static error if a namespace prefix is used within the [xsl:]exclude-result-prefixes attribute and there is no namespace binding in scope for that prefix.

ERR XTSE0809

It is a static error if the value #default is used within the [xsl:]exclude-result-prefixes attribute and the parent element of the [xsl:]exclude-result-prefixes attribute has no default namespace.

ERR XTSE0810

It is a static error if within a package there is more than one such declaration [more than one xsl:namespace-alias declaration] with the same literal namespace URI and the same import precedence and different values for the target namespace URI, unless there is also an xsl:namespace-alias declaration with the same literal namespace URI and a higher import precedence.

ERR XTSE0812

It is a static error if a value other than #default is specified for either the stylesheet-prefix or the result-prefix attributes of the xsl:namespace-alias element when there is no in-scope binding for that namespace prefix.

ERR XTSE0840

It is a static error if the select attribute of the xsl:attribute element is present unless the element has empty content.

ERR XTSE0870

It is a static error if the select attribute of the xsl:value-of element is present when the content of the element is non-empty, or if the select attribute is absent when the content is empty.

ERR XTSE0880

It is a static error if the select attribute of the xsl:processing-instruction element is present unless the element has empty content.

ERR XTSE0910

It is a static error if the select attribute of the xsl:namespace element is present when the element has content other than one or more xsl:fallback instructions, or if the select attribute is absent when the element has empty content.

ERR XTSE0940

It is a static error if the select attribute of the xsl:comment element is present unless the element has empty content.

ERR XTSE0975

It is a static error if the value attribute of xsl:number is present unless the select, level, count, and from attributes are all absent.

ERR XTSE1015

It is a static error if an xsl:sort element with a select attribute has non-empty content.

ERR XTSE1017

It is a static error if an xsl:sort element other than the first in a sequence of sibling xsl:sort elements has a stable attribute.

ERR XTSE1040

It is a static error if an xsl:perform-sort instruction with a select attribute has any content other than xsl:sort and xsl:fallback instructions.

ERR XTSE1060

It is a static error if the current-group function is used within a pattern.

ERR XTSE1070

It is a static error if the current-grouping-key function is used within a pattern.

ERR XTSE1080

These four attributes [the group-by, group-adjacent, group-starting-with, and group-ending-with attributes of xsl:for-each-group ] are mutually exclusive: it is a static error if none of these four attributes is present or if more than one of them is present.

ERR XTSE1090

It is a static error to specify the collation attribute or the composite attribute if neither the group-by attribute nor group-adjacent attribute is specified.

ERR XTSE1130

It is a static error if the xsl:analyze-string instruction contains neither an xsl:matching-substring nor an xsl:non-matching-substring element.

ERR XTSE1205

It is a static error if an xsl:key declaration has a use attribute and has non-empty content, or if it has empty content and no use attribute.

ERR XTSE1210

It is a static error if the xsl:key declaration has a collation attribute whose value (after resolving against the base URI) is not a URI recognized by the implementation as referring to a collation.

ERR XTSE1220

It is a static error if there are several xsl:key declarations in the same package with the same key name and different effective collations. Two collations are the same if their URIs are equal under the rules for comparing xs:anyURI values, or if the implementation can determine that they are different URIs referring to the same collation.

ERR XTSE1222

It is a static error if there are several xsl:key declarations in the stylesheet with the same key name and different effective values for the composite attribute.

ERR XTSE1290

It is a static error if a named or unnamed decimal format contains two conflicting values for the same attribute in different xsl:decimal-format declarations having the same import precedence, unless there is another definition of the same attribute with higher import precedence.

ERR XTSE1295

It is a static error if the character specified in the zero-digit attribute is not a digit or is a digit that does not have the numeric value zero.

ERR XTSE1300

It is a static error if, for any named or unnamed decimal format, the variables representing characters used in a picture string do not each have distinct values. These variables are decimal-separator-sign, grouping-sign, percent-sign, per-mille-sign, digit-zero-sign, digit-sign, and pattern-separator-sign.

ERR XTSE1430

It is a static error if there is no namespace bound to the prefix on the element bearing the [xsl:]extension-element-prefixes attribute or, when #default is specified, if there is no default namespace.

ERR XTSE1505

It is a static error if both the [xsl:]type and [xsl:]validation attributes are present on the xsl:element, xsl:attribute, xsl:copy, xsl:copy-of, xsl:document, or xsl:result-document instructions, or on a literal result element.

ERR XTSE1520

It is a static error if the value of the type attribute of an xsl:element, xsl:attribute, xsl:copy, xsl:copy-of, xsl:document, or xsl:result-document instruction, or the xsl:type attribute of a literal result element, is not a valid QName, or if it uses a prefix that is not defined in an in-scope namespace declaration, or if the QName is not the name of a type definition included in the in-scope schema components for the stylesheet.

ERR XTSE1530

It is a static error if the value of the type attribute of an xsl:attribute instruction refers to a complex type definition

ERR XTSE1560

It is a static error if two xsl:output declarations within an output definition specify explicit values for the same attribute (other than cdata-section-elements and use-character-maps), with the values of the attributes being not equal, unless there is another xsl:output declaration within the same output definition that has higher import precedence and that specifies an explicit value for the same attribute.

ERR XTSE1570

The value [of the method attribute on xsl:output ] must (if present) be a valid EQName. If it is a lexical QName with no a prefix, then it identifies a method specified in [XSLT and XQuery Serialization] and must be one of xml, html, xhtml, or text.

ERR XTSE1580

It is a static error if the stylesheet contains two or more character maps with the same name and the same import precedence, unless it also contains another character map with the same name and higher import precedence.

ERR XTSE1590

It is a static error if a name in the use-character-maps attribute of the xsl:output or xsl:character-map elements does not match the name attribute of any xsl:character-map in the stylesheet.

ERR XTSE1600

It is a static error if a character map references itself, directly or indirectly, via a name in the use-character-maps attribute.

ERR XTSE1650

A basic XSLT processor must signal a static error if the stylesheet includes an xsl:import-schema declaration.

ERR XTSE1660

A basic XSLT processor must signal a static error if the stylesheet includes an [xsl:]type attribute, or an [xsl:]validation or default-validation attribute with a value other than strip, preserve, or lax.

ERR XTSE2200

It is a static error if the number of xsl:merge-key children of a xsl:merge-source element is not equal to the number of xsl:merge-key children of another xsl:merge-source child of the same xsl:merge instruction.

ERR XTSE3010

It is a static error if the exposed visibility of a component is inconsistent with its potential visibility, as defined in the above table, unless the token that matches the component is a wildcard, in which case it is treated as not matching that component.

ERR XTSE3020

It is a static error if an xsl:expose element matches no components in the containing package, unless the tokens in the names attribute are all wildcards.

ERR XTSE3030

It is a static error if an xsl:accept element matches no components in the used package, unless the tokens in its names attribute are all wildcards.

ERR XTSE3040

It is a static error if the visibility assigned to a component by an xsl:accept element is incompatible with the visibility of the corresponding component in the used package, as defined by the above table, unless the token that matches the component name is a wildcard, in which case the xsl:accept element is treated as not matching that component.

ERR XTSE3050

It is a static error if the xsl:use-package elements in a package manifest cause two or more homonymous components to be accepted with a visibility other than hidden.

ERR XTSE3060

It is a static error if the component referenced by an xsl:override declaration has visibility other than public or abstract

ERR XTSE3070

It is a static error if the signature of an overriding component is not compatible with the signature of the component that it is overriding.

ERR XTSE3080

It is a static error if a top-level package intended for execution (as distinct from a library package) contains symbolic references referring to components whose visibility is abstract.

ERR XTSE3120

It is a static error if an xsl:break or xsl:next-iteration element appears other than in a tail position within the sequence constructor forming the body of an xsl:iterate instruction.

ERR XTSE3130

It is a static error if the name attribute of an xsl:with-param child of an xsl:next-iteration element does not match the name attribute of an xsl:param child of the innermost containing xsl:iterate instruction.

ERR XTSE3140

It is a static error if the select attribute of the xsl:try element is present and the element has children other than xsl:catch and xsl:fallback elements.

ERR XTSE3150

It is a static error if the select attribute of the xsl:catch element is present unless the element has empty content.

ERR XTSE3190

It is a static error if two sibling xsl:merge-source elements have the same name, whether explicit or implicit.

ERR XTSE3200

It is a static error if an xsl:merge-key element with a select attribute has non-empty content.

ERR XTSE3220

It is a static error if a variable bound in the bind-group or bind-grouping-key attribute of an xsl:for-each-group instruction is referenced within an expression in the lang, order, collation, stable, case-order, or data-type attributes of an xsl:sort child of that xsl:for-each-group instruction.

ERR XTSE3230

It is a static error if the bind-grouping-key attribute is present on an xsl:for-each-group instruction unless either the group-by or group-adjacent attribute is present.

ERR XTSE3270

It is a static error if the set of variable names declared using the bind-group and bind-key attributes of an xsl:merge instruction and the bind-source attributes of its xsl:merge-source children contains any duplicates.

Type errors

ERR XTTE0505

It is a type error if the result of evaluating the sequence constructor cannot be converted to the required type.

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.

ERR XTTE0570

It is a type error if the supplied value of a variable cannot be converted to the required type.

ERR XTTE0590

It is a type error if the conversion of the supplied value of a parameter to its required type fails.

ERR XTTE0600

If a default value is given explicitly, that is, if there is either a select attribute or a non-empty sequence constructor, then it is a type error if the default value cannot be converted to the required type, using the function conversion rules.

ERR XTTE0780

If the as attribute [of xsl:function ] is specified, then the result evaluated by the sequence constructor (see 5.7 Sequence Constructors) is converted to the required type, using the function conversion rules. It is a type error if this conversion fails.

ERR XTTE0790

If the value of a parameter to a stylesheet function cannot be converted to the required type, a type error is signaled.

ERR XTTE0950

It is a type error to use the xsl:copy or xsl:copy-of instruction to copy a node that has namespace-sensitive content if the copy-namespaces attribute has the value no and its explicit or implicit validation attribute has the value preserve. It is also a type error if either of these instructions (with validation="preserve") is used to copy an attribute having namespace-sensitive content, unless the parent element is also copied. A node has namespace-sensitive content if its typed value contains an item of type xs:QName or xs:NOTATION or a type derived therefrom. The reason this is an error is because the validity of the content depends on the namespace context being preserved.

ERR XTTE0990

It is a type error if the xsl:number instruction is evaluated, with no value or select attribute, when the context item is not a node.

ERR XTTE1000

It is a type error if the result of evaluating the select attribute of the xsl:number instruction is anything other than a single node.

ERR XTTE1020

If any sort key value, after atomization and any type conversion required by the data-type attribute, is a sequence containing more than one item, then the effect depends on whether the xsl:sort element is processed with XSLT 1.0 behavior. With XSLT 1.0 behavior, the effective sort key value is the first item in the sequence. In other cases, this is a type error.

ERR XTTE1100

It is a type error if the result of evaluating the group-adjacent expression is an empty sequence or a sequence containing more than one item, unless composite="yes" is specified.

ERR XTTE1510

If the validation attribute of an xsl:element, xsl:attribute, xsl:copy, xsl:copy-of, or xsl:result-document instruction, or the xsl:validation attribute of a literal result element, has the effective value strict, and schema validity assessment concludes that the validity of the element or attribute is invalid or unknown, a type error occurs. As with other type errors, the error may be signaled statically if it can be detected statically.

ERR XTTE1512

If the validation attribute of an xsl:element, xsl:attribute, xsl:copy, xsl:copy-of, or xsl:result-document instruction, or the xsl:validation attribute of a literal result element, has the effective value strict, and there is no matching top-level declaration in the schema, then a type error occurs. As with other type errors, the error may be signaled statically if it can be detected statically.

ERR XTTE1515

If the validation attribute of an xsl:element, xsl:attribute, xsl:copy, xsl:copy-of, or xsl:result-document instruction, or the xsl:validation attribute of a literal result element, has the effective value lax, and schema validity assessment concludes that the element or attribute is invalid, a type error occurs. As with other type errors, the error may be signaled statically if it can be detected statically.

ERR XTTE1535

It is a type error if the value of the type attribute of an xsl:copy or xsl:copy-of instruction refers to a complex type definition and one or more of the items being copied is an attribute node.

ERR XTTE1540

It is a type error if an [xsl:]type attribute is defined for a constructed element or attribute, and the outcome of schema validity assessment against that type is that the validity property of that element or attribute information item is other than valid.

ERR XTTE1545

A type error occurs if a type or validation attribute is defined (explicitly or implicitly) for an instruction that constructs a new attribute node, if the effect of this is to cause the attribute value to be validated against a type that is derived from, or constructed by list or union from, the primitive types xs:QName or xs:NOTATION.

ERR XTTE1550

A type error occurs [when a document node is validated] unless the children of the document node comprise exactly one element node, no text nodes, and zero or more comment and processing instruction nodes, in any order.

ERR XTTE1555

It is a type error if, when validating a document node, document-level constraints are not satisfied. These constraints include identity constraints (xs:unique, xs:key, and xs:keyref) and ID/IDREF constraints.

ERR XTTE2230

It is a type error if some item selected by a particular merge key in one input sequence is not comparable using the XPath le operator with some item selected by the corresponding sort key in another input sequence.

ERR XTTE3090

It is a type error if the xsl:context-item child of xsl:template specifies that a context item is required and none is supplied by the caller, that is, if the context item is absent at the point where xsl:call-template is evaluated.

ERR XTTE3100

It is a type error if an xsl:apply-templates instruction in a particular mode selects an element or attribute whose type is xs:untyped or xs:untypedAtomic when the typed attribute of that mode specifies the value yes, strict, or lax.

ERR XTTE3110

It is a type error if an xsl:apply-templates instruction in a particular mode selects an element or attribute whose type is anything other than xs:untyped or xs:untypedAtomic when the typed attribute of that mode specifies the value no.

ERR XTTE3170

It is a type error if the result of evaluating the namespace-context attribute of the xsl:evaluate instruction is anything other than a single node.

ERR XTTE3180

It is a type error if the result of evaluating the select expression [of the xsl:copy element] is a sequence of more than one item.

ERR XTTE3210

If the result of evaluating the context-item expression [of an xsl:evaluate instruction] is a sequence containing more than one item, then a type error is signaled.

Dynamic errors

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.

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.

ERR XTDE0060

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

ERR XTDE0160

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

ERR XTDE0290

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

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.

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 an on-multiple-match attribute with the value fail.

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.

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.

ERR XTDE0610

If an optional parameter has no select attribute and has an empty sequence constructor, and if there is an as attribute, then the default value of the parameter is an empty sequence. If the empty sequence is not a valid instance of the required type defined in the as attribute, then the parameter is treated as a required parameter, which means that it is a non-recoverable dynamic error if the caller supplies no value for the parameter.

ERR XTDE0640

In general, a circularity in a stylesheet is a non-recoverable dynamic error.

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.

ERR XTRE0795

It is a recoverable dynamic error if the name of a constructed attribute is xml:space and the value is not either default or preserve.
    Action: The optional recovery action is to construct the attribute with the value as requested.

ERR XTDE0820

It is a non-recoverable dynamic error if the effective value of the name attribute [of the xsl:element instruction] is not a lexical QName.

ERR XTDE0830

In the case of an xsl:element instruction with no namespace attribute, it is a non-recoverable dynamic error if the effective value of the name attribute is a lexical QName whose prefix is not declared in an in-scope namespace declaration for the xsl:element instruction.

ERR XTDE0835

It is a non-recoverable dynamic error if the effective value of the namespace attribute [of the xsl:element instruction] is not in the lexical space of the xs:anyURI datatype or if it is the string http://www.w3.org/2000/xmlns/.

ERR XTDE0850

It is a non-recoverable dynamic error if the effective value of the name attribute [of an xsl:attribute instruction] is not a lexical QName.

ERR XTDE0855

In the case of an xsl:attribute instruction with no namespace attribute, it is a non-recoverable dynamic error if the effective value of the name attribute is the string xmlns.

ERR XTDE0860

In the case of an xsl:attribute instruction with no namespace attribute, it is a non-recoverable dynamic error if the effective value of the name attribute is a lexical QName whose prefix is not declared in an in-scope namespace declaration for the xsl:attribute instruction.

ERR XTDE0865

It is a non-recoverable dynamic error if the effective value of the namespace attribute [of the xsl:attribute instruction] is not in the lexical space of the xs:anyURI datatype or if it is the string http://www.w3.org/2000/xmlns/.

ERR XTDE0890

It is a non-recoverable dynamic error if the effective value of the name attribute [of the xsl:processing-instruction instruction] is not both an NCNameNames and a PITargetXML.

ERR XTDE0905

It is a non-recoverable dynamic error if the string value of the new namespace node is not valid in the lexical space of the datatype xs:anyURI, or if it is the string http://www.w3.org/2000/xmlns/.

ERR XTDE0920

It is a non-recoverable dynamic error if the effective value of the name attribute [of the xsl:namespace instruction] is neither a zero-length string nor an NCNameNames, or if it is xmlns.

ERR XTDE0925

It is a non-recoverable dynamic error if the xsl:namespace instruction generates a namespace node whose name is xml and whose string value is not http://www.w3.org/XML/1998/namespace, or a namespace node whose string value is http://www.w3.org/XML/1998/namespace and whose name is not xml.

ERR XTDE0930

It is a non-recoverable dynamic error if evaluating the select attribute or the contained sequence constructor of an xsl:namespace instruction results in a zero-length string.

ERR XTDE0980

It is a non-recoverable dynamic error if any undiscarded item in the atomized sequence supplied as the value of the value attribute of xsl:number cannot be converted to an integer, or if the resulting integer is less than 0 (zero).

ERR XTDE1001

It is a dynamic error if the effective value of the start-at attribute of the xsl:number instruction is not in the lexical space of xs:integer. The error may be signaled statically if it can be detected statically.

ERR XTDE1030

It is a non-recoverable dynamic error if, for any sort key component, the set of sort key values evaluated for all the items in the initial sequence, after any type conversion requested, contains a pair of ordinary values for which the result of the XPath lt operator is an error.

ERR XTDE1035

It is a non-recoverable dynamic error if the collation attribute of xsl:sort (after resolving against the base URI) is not a URI that is recognized by the implementation as referring to a collation.

ERR XTDE1061

It is a dynamic error if the current-group function is used when the current group is absent. The error may be reported statically if it can be detected statically.

ERR XTDE1071

It is a dynamic error if the current-grouping-key function is used when the current grouping key is absent. The error may be reported statically if it can be detected statically.

ERR XTDE1110

It is a non-recoverable dynamic error if the collation URI specified to xsl:for-each-group (after resolving against the base URI) is a collation that is not recognized by the implementation. (For notes, [see ERR XTDE1035].)

ERR XTDE1140

It is a non-recoverable dynamic error if the effective value of the regex attribute [of the xsl:analyze-string instruction] does not conform to the required syntax for regular expressions, as specified in [Functions and Operators]. If the regular expression is known statically (for example, if the attribute does not contain any expressions enclosed in curly brackets) then the processor may signal the error as a static error.

ERR XTDE1145

It is a non-recoverable dynamic error if the effective value of the flags attribute [of the xsl:analyze-string instruction] has a value other than the values defined in [Functions and Operators]. If the value of the attribute is known statically (for example, if the attribute does not contain any expressions enclosed in curly brackets) then the processor may signal the error as a static error.

ERR XTDE1150

It is a non-recoverable dynamic error if the effective value of the regex attribute [of the xsl:analyze-string instruction] is a regular expression that matches a zero-length string: or more specifically, if the regular expression $r and flags $f are such that matches("", $r, $f) returns true. If the regular expression is known statically (for example, if the attribute does not contain any expressions enclosed in curly brackets) then the processor may signal the error as a static error.

ERR XTRE1160

When a URI reference [supplied to the document function] contains a fragment identifier, it is a recoverable dynamic error if the media type is not one that is recognized by the processor, or if the fragment identifier does not conform to the rules for fragment identifiers for that media type, or if the fragment identifier selects something other than a sequence of nodes (for example, if it selects a range of characters within a text node).
    Action: The optional recovery action is to ignore the fragment identifier and return the document node.

ERR XTDE1162

When a URI reference [supplied to the document function] is a relative reference, it is a dynamic error if no base URI is available to resolve the relative reference. This can arise for example when the URI is contained in a node that has no base URI (for example a parentless text node), or when the second argument to the function is a node that has no base URI, or when the base URI from the static context is undefined.

ERR XTDE1260

It is a non-recoverable dynamic error if the value [of the first argument to the key function] is not a valid QName, or if there is no namespace declaration in scope for the prefix of the QName, or if the name obtained by expanding the QName is not the same as the expanded name of any xsl:key declaration in the containing package. If the processor is able to detect the error statically (for example, when the argument is supplied as a string literal), then the processor may optionally signal this as a static error.

ERR XTDE1270

It is a non-recoverable dynamic error to call the key function with two arguments if there is no context node, or if the root of the tree containing the context node is not a document node; or to call the function with three arguments if the root of the tree containing the node supplied in the third argument is not a document node.

ERR XTDE1360

If the current function is evaluated within an expression that is evaluated when the context item is absent, a non-recoverable dynamic error occurs.

ERR XTDE1370

It is a non-recoverable dynamic error if the unparsed-entity-uri function is called when there is no context node, or when the root of the tree containing the context node is not a document node.

ERR XTDE1380

It is a non-recoverable dynamic error if the unparsed-entity-public-id function is called when there is no context node, or when the root of the tree containing the context node is not a document node.

ERR XTDE1400

It is a non-recoverable dynamic error if the argument [passed to the function-available function] does not evaluate to a string that is a valid EQName, or if the value is a lexical QName with a prefix for which no namespace declaration is present in the static context. If the processor is able to detect the error statically (for example, when the argument is supplied as a string literal), then the processor may optionally signal this as a static error.

ERR XTDE1420

It is a non-recoverable dynamic error if the arguments supplied to a call on an extension function do not satisfy the rules defined for that particular extension function, or if the extension function reports an error, or if the result of the extension function cannot be converted to an XPath value.

ERR XTDE1425

When the containing element is processed with XSLT 1.0 behavior, it is a non-recoverable dynamic error to evaluate an extension function call if no implementation of the extension function is available.

ERR XTDE1428

It is a non-recoverable dynamic error if the argument [passed to the type-available function] does not evaluate to a string that is a valid EQName, or if the value is a lexical QName with a prefix for which no namespace declaration is present in the static context. If the processor is able to detect the error statically (for example, when the argument is supplied as a string literal), then the processor may optionally signal this as a static error.

ERR XTDE1440

It is a non-recoverable dynamic error if the argument [passed to the element-available function] does not evaluate to a string that is a valid EQName, or if the value is a lexical QName with a prefix for which no namespace declaration is present in the static context. If the processor is able to detect the error statically (for example, when the argument is supplied as a string literal), then the processor may optionally signal this as a static error.

ERR XTDE1450

When a processor performs fallback for an extension instruction that is not recognized, if the instruction element has one or more xsl:fallback children, then the content of each of the xsl:fallback children must be evaluated; it is a non-recoverable dynamic error if it has no xsl:fallback children.

ERR XTDE1460

It is a non-recoverable dynamic error if the effective value of the format attribute [of an xsl:result-document element] is not a valid EQName, or if it does not match the expanded QName of an output definition in the stylesheet. If the processor is able to detect the error statically (for example, when the format attribute contains no curly brackets), then the processor may optionally signal this as a static error.

ERR XTDE1480

It is a non-recoverable dynamic error to evaluate the xsl:result-document instruction in temporary output state.

ERR XTDE1490

It is a non-recoverable dynamic error for a transformation to generate two or more final result trees with the same URI.

ERR XTRE1495

It is a recoverable dynamic error for a transformation to generate two or more final result trees with URIs that identify the same physical resource. The optional recovery action is implementation-dependent, since it may be impossible for the processor to detect the error.

ERR XTRE1500

It is a recoverable dynamic error for a stylesheet to write to an external resource and read from the same resource during a single transformation, whether or not the same URI is used to access the resource in both cases.
    Action: The optional recovery action is implementation-dependent: implementations are not required to detect the error condition. Note that if the error is not detected, it is implementation-dependent whether the document that is read from the resource reflects its state before or after the result tree is written.

ERR XTRE1620

It is a recoverable dynamic error if an xsl:value-of or xsl:text instruction specifies that output escaping is to be disabled and the implementation does not support this.
    Action: The optional recovery action is to ignore the disable-output-escaping attribute.

ERR XTRE1630

It is a recoverable dynamic error if an xsl:value-of or xsl:text instruction specifies that output escaping is to be disabled when writing to a final result tree that is not being serialized.
    Action: The optional recovery action is to ignore the disable-output-escaping attribute.

ERR XTDE1665

A basic XSLT processor must raise a non-recoverable dynamic error if the input to the processor includes a node with a type annotation other than xs:untyped or xs:untypedAtomic, or an atomic value of a type other than those which a basic XSLT processor supports.

ERR XTDE2210

It is a dynamic error if there are two xsl:merge-key elements that occupy corresponding positions among the xsl:merge-key children of two different xsl:merge-source elements and that have differing effective values for any of the attributes lang, order, collation, case-order, or data-type. Values are considered to differ if the attribute is present on one element and not on the other, or if it is present on both elements with effective values that are not equal to each other. In the case of the collation attribute, the values are compared as absolute URIs after resolving against the base URI.The error may be reported statically if it is detected statically.

ERR XTDE2220

It is a dynamic error if any input sequence to an xsl:merge instruction contains two items that are not correctly sorted according to the merge key values defined on the xsl:merge-key children of the corresponding xsl:merge-source element, when compared using the collation rules defined by the attributes of the corresponding xsl:merge-key children of the xsl:merge instruction, unless the attribute sort-before-merge is present with the value yes.

ERR XTDE3006

It is a non-recoverable dynamic error if the supplied value cannot be serialized as a JSON text conforming to the rules of the specification selected by the explicit or implicit spec option.

ERR XTDE3007

It is a non-recoverable dynamic error if the value of $options includes an entry whose key is "spec" and whose value is not a single xs:string, or an entry whose key is "indent" or "escape" and whose value is not a single xs:boolean, or an entry whose key is "fallback" and whose value is not a single function item of arity 1 (one).

ERR XTDE3160

It is a non-recoverable dynamic error if the target expression [of an xsl:evaluate instruction] is not a valid XPath 3.0 expression (that is, if a static error occurs when analyzing the string according to the rules of the XPath 3.0 specification).

ERR XTDE3240

It is a non-recoverable dynamic error if the value of $input does not conform to the JSON grammar, as selected using the explicit or implicit spec option.

ERR XTDE3250

It is a non-recoverable dynamic error if the value of $input contains an escaped representation of a character (or codepoint) that is not a valid character in the version of XML supported by the implementation, unless the unescape option is set to false.

ERR XTDE3260

It is a non-recoverable dynamic error if the value of $options includes an entry whose key is "spec" and whose value is not a single xs:string, or an entry whose key is "unescape" and whose value is not a single xs:boolean.

ERR XTMM9000

When a transformation is terminated by use of xsl:message terminate="yes", the effect is the same as when a non-recoverable dynamic error occurs during the transformation. The default error code is XTMM9000; this may be overridden using the error-code attribute of the xsl:message instruction.

ERR XTMM9001

When a transformation is terminated by use of xsl:assert, the effect is the same as when a non-recoverable dynamic error occurs during the transformation. The default error code is XTMM9001; this may be overridden using the error-code attribute of the xsl:assert instruction.

E Checklist of Implementation-Defined Features (Non-Normative)

This appendix provides a summary of XSLT language features whose effect is explicitly implementation-defined. The conformance rules (see 26 Conformance) require vendors to provide documentation that explains how these choices have been exercised.

  1. The way in which a base output URI is established is implementation-defined (See 2.3 Initiating a Transformation)

  2. The way in which an XSLT processor is invoked, and the way in which values are supplied for the source document, starting node, stylesheet parameters, and base output URI, are implementation-defined. (See 2.3 Initiating a Transformation)

  3. The mechanisms for creating new extension instructions and extension functions are implementation-defined. (See 2.8 Extensibility)

  4. Where the specification provides a choice between signaling a dynamic error or recovering, the decision that is made (but not the recovery action itself) is implementation-defined. (See 2.11 Error Handling)

  5. It is implementation-defined whether type errors are signaled statically. (See 2.11 Error Handling)

  6. Mechanisms to locate the source or executable code of a package are implementation-defined. (See 3.6.1 Dependencies between Packages)

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

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

  9. If the effective version of any element in the stylesheet is not 1.0 or 2.0 but is less than 3.0, the recommended action is to report a static error; however, processors may recognize such values and process the element in an implementation-defined way. (See 3.10 Backwards Compatible Processing)

  10. It is implementation-defined whether an XSLT 3.0 processor supports backwards compatible behavior for any XSLT version earlier than XSLT 3.0. (See 3.10 Backwards Compatible Processing)

  11. It is implementation-defined what forms of URI reference are acceptable in the href attribute of the xsl:include and xsl:import elements, for example, the URI schemes that may be used, the forms of fragment identifier that may be used, and the media types that are supported. (See 3.12.1 Locating Stylesheet Modules)

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

  13. It is implementation-defined which versions of XML and XML Namespaces (1.0 and/or 1.1) are supported. (See 4.1 XML Versions)

  14. Limits on the value space of primitive datatypes, where not fixed by [XML Schema Part 2], are implementation-defined. (See 4.7 Limits)

  15. The set of statically known documentsXP30 is implementation-defined. (See 5.4.1 Initializing the Static Context)

  16. The set of statically known collectionsXP30 is implementation-defined. (See 5.4.1 Initializing the Static Context)

  17. The statically known default collection typeXP30 is implementation-defined. (See 5.4.1 Initializing the Static Context)

  18. Implementations may provide user options that relax the requirement for the docFO30 and collectionFO30 functions (and therefore, by implication, the document function) to return stable results. The manner in which such user options are provided, if at all, is implementation-defined. (See 5.4.3 Initializing the Dynamic Context)

  19. The implicit timezone for a transformation is implementation-defined. (See 5.4.3.2 Other components of the XPath Dynamic Context)

  20. The default collectionXP30 is implementation-defined. (See 5.4.3.2 Other components of the XPath Dynamic Context)

  21. It is implementation-defined whether, and under what circumstances, calls to extension functions are non-contextual. (See 5.4.4 Additional Dynamic Context Components used by XSLT)

  22. The default values for the warning-on-no-match and warning-on-multiple-match attributes of xsl:mode are implementation-defined. (See 6.6.1 Declaring Modes)

  23. The form of any warnings output when there is no matching template rule or when there are multiple matching template rules is implementation-defined. (See 6.6.1 Declaring Modes)

  24. The mechanism by which the caller supplies a value for a stylesheet parameter is implementation-defined. (See 9.5 Global Variables and Parameters)

  25. The set of extension functions available in the static context for the target expression of xsl:evaluate is implementation-defined. (See 10.4 Dynamic XPath Evaluation)

  26. If an xml:id attribute that has not been subjected to attribute value normalization is copied from a source tree to a result tree, it is implementation-defined whether attribute value normalization will be applied during the copy process. (See 11.9.1 Shallow Copy)

  27. The numbering sequences supported by the xsl:number instructions, beyond those defined in this specification, are implementation-defined. (See 12.3 Number to String Conversion Attributes)

  28. There may be implementation-defined upper bounds on the numbers that can be formatted by xsl:number using any particular numbering sequence. (See 12.3 Number to String Conversion Attributes)

  29. The set of languages for which numbering is supported by xsl:number, and the method of choosing a default language, are implementation-defined. (See 12.3 Number to String Conversion Attributes)

  30. With xsl:number, it is implementation-defined what combinations of values of the format token, the language, and the ordinal attribute are supported. (See 12.3 Number to String Conversion Attributes)

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

  32. The facilities for defining collations and allocating URIs to identify them are implementation-defined. (See 13.1.3 Sorting Using Collations)

  33. The algorithm used by xsl:sort to locate a collation, given the values of the lang and case-order attributes, is implementation-defined. (See 13.1.3 Sorting Using Collations)

  34. The set of media types recognized by the processor, for the purpose of interpreting fragment identifiers in URI references passed to the document function, is implementation-defined. (See 20.1 fn:document)

  35. The destination and formatting of messages written using the xsl:message instruction are implementation-defined. (See 22.1 Messages)

  36. The detail of any external mechanism allowing a processor to disable checking of assertions is implementation-defined. (See 22.2 Assertions)

  37. This specification does not define any mechanism for creating or binding implementations of extension instructions or extension functions, and it is not required that implementations support any such mechanism. Such mechanisms, if they exist, are implementation-defined. (See 23 Extensibility and Fallback)

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

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

  40. The way in which a final result tree is delivered to an application is implementation-defined. (See 24 Final Result Trees)

  41. There may be implementation-defined restrictions on the form of absolute URI that may be used in the href attribute of the xsl:result-document instruction. (See 24.1 Creating Final Result Trees)

  42. Implementations may provide additional mechanisms allowing users to define the way in which final result trees are processed. (See 24.1 Creating Final Result Trees)

  43. If serialization is supported, then the location to which a final result tree is serialized is implementation-defined, subject to the constraint that relative URI references used to reference one tree from another remain valid. (See 25 Serialization)

  44. The default value of the encoding attribute of the xsl:output element is implementation-defined. (See 25 Serialization)

  45. It is implementation-defined which versions of XML, HTML, and XHTML are supported in the version attribute of the xsl:output declaration. (See 25 Serialization)

  46. The default value of the byte-order-mark serialization parameter is implementation-defined in the case of UTF-8 encoding. (See 25 Serialization)

  47. It is implementation-defined whether, and under what circumstances, disabling output escaping is supported. (See 25.2 Disabling Output Escaping)

F List of XSLT-defined functions (Non-Normative)

This appendix acts as an index of functions defined in this specification, to augment the set of functions defined in [Functions and Operators].

attributes
See 19.7 fn:attributes
copy-of
See 19.4 fn:copy-of
current
See 20.4.1 fn:current
current-group
See 14.2.1 fn:current-group
current-grouping-key
See 14.2.2 fn:current-grouping-key
deep-equal2
See 21.1.2.8 fn:deep-equal2
document
See 20.1 fn:document
element-available
See 23.2.2 fn:element-available
function-available
See 23.1.1 fn:function-available
key
See 20.2.2 fn:key
look-ahead
See 19.8 fn:look-ahead
map:collation
See 21.1.2.2 map:collation
map:contains
See 21.1.2.4 map:contains
map:entry
See 21.1.2.6 map:entry
map:get
See 21.1.2.5 map:get
map:keys
See 21.1.2.3 map:keys
map:new
See 21.1.2.1 map:new
map:remove
See 21.1.2.7 map:remove
parse-json
See 21.2.1 fn:parse-json
point-copy
See 19.6 fn:point-copy
regex-group
See 17.2 fn:regex-group
serialize-json
See 21.2.2 fn:serialize-json
snapshot
See 19.5 fn:snapshot
type-available
See 23.1.4 fn:type-available
unparsed-entity-public-id
See 20.4.3 fn:unparsed-entity-public-id
unparsed-entity-uri
See 20.4.2 fn:unparsed-entity-uri

G Schema for XSLT Stylesheets (Non-Normative)

The following XSD 1.1 schema describes the structure of an XSLT stylesheet module. It does not define all the constraints that apply to a stylesheet (for example, it does not attempt to define a datatype that precisely represents attributes containing XPath expressions). However, every valid stylesheet module conforms to this schema, unless it contains elements that invoke forwards compatible behavior.

A copy of this schema is available at http://www.w3.org/2012/07/schema-for-xslt30.xsd

Note:

The schema as written uses a lax wildcard to permit literal result elements to appear in a sequence constructor. This assumes that the schema used for validation will not contain any global element declaration that matches the element name of a literal result element. The content model for an element such as invoice appearing within a stylesheet is not the same as the content model for the same element appearing within a source document (it is likely to contain XSLT instructions rather than other elements from the target vocabulary): therefore, including such declarations in the schema used for validating a stylesheet is inappropriate.

The reason that lax validation rather than skip validation is used is so that XSLT instructions appearing as children of the literal result element will themselves be validated, using the appropriate global element declaration.

Note:

The schema uses XSD 1.1 assertions to represent some of the non-grammatical constraints appearing in the specification, for example the rule that some elements can have either a select attribute or a contained sequence constructor, but not both. At this stage, no attempt has been made to represent every such constraint, even where it is not difficult to express the rule. There will always be some constraints that cannot be expressed at all, for example those that require access to multiple stylesheet modules, those that require access to the in-scope schema components, and those that involve parsing a non-regular grammar, such as the grammar for patterns.

Apart from assertions, the only other significant use of XSD 1.1 features is that the elements xsl:param and xsl:variable are in two substitution groups: one containing all instructions, and one containing all declarations. If the schema needs to be converted to an XSD 1.0 schema, removing all assertions is straightforward; the other change needed is to remove xsl:param and xsl:variable from the substitution group for declarations, and instead permit them explicitly as children of xsl:transform.

<?xml version="1.0" encoding="UTF-8"?>
<!--* <!DOCTYPE xs:schema PUBLIC "-//W3C//DTD XMLSCHEMA 200105//EN"
       "http://www.w3.org/2001/XMLSchema.dtd" [
<!ENTITY % schemaAttrs "
  xmlns:xs   CDATA #IMPLIED
  xmlns:xsl  CDATA #IMPLIED
  xmlns:xsd  CDATA #IMPLIED"
>
<!ENTITY % p "xs:">
<!ENTITY % s ":xs">
]> *-->

<?xml-stylesheet href="http://www.w3.org/2008/09/xsd.xsl" type="text/xsl"?> 
<!--* <?xml-stylesheet href="http://www.w3.org/2008/09/xsd.xsl" type="application/xslt+xml"?>  *-->
<!--* <?xml-stylesheet href="../../../www.w3.org/2008/09/xsd.xsl" type="application/xslt+xml"?> *-->

<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"
  xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
  targetNamespace="http://www.w3.org/1999/XSL/Transform" elementFormDefault="qualified">

  <!-- ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ -->
  <xs:annotation>
    <xs:documentation> This is an XSD 1.1 schema for XSLT 3.0 stylesheets, based on the schema for XSLT 2.0
      It defines all the elements that appear in the XSLT namespace; it also provides hooks that
      allow the inclusion of user-defined literal result elements, extension instructions, and
      top-level data elements. This schema is available for use under the conditions of the W3C
      Software License published at http://www.w3.org/Consortium/Legal/copyright-software-19980720
      The schema is organized as follows: PART A: definitions of complex types and model groups used
      as the basis for element definitions PART B: definitions of individual XSLT elements PART C:
      definitions for literal result elements PART D: definitions of simple types used in attribute
      definitions </xs:documentation>
  </xs:annotation>
  <!-- ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ -->

  <!--
The declaration of xml:space and xml:lang may need to be commented out because
of problems processing the schema using various tools
-->

  <xs:import namespace="http://www.w3.org/XML/1998/namespace"/>
  <!--schemaLocation="http://www.w3.org/2001/xml.xsd"-->

  <!-- 
    An XSLT stylesheet may contain an in-line schema within an xsl:import-schema element,
    so the Schema for schemas needs to be imported
-->

  <xs:import namespace="http://www.w3.org/2001/XMLSchema"
    schemaLocation="http://www.w3.org/2001/XMLSchema.xsd"/>

  <!-- ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ -->
  <xs:annotation>
    <xs:documentation> PART A: definitions of complex types and model groups used as the basis for
      element definitions </xs:documentation>
  </xs:annotation>
  <!-- ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ -->

  <xs:complexType name="generic-element-type" mixed="true">
    <xs:annotation>
        <xs:documentation>
            <p>This complex type provides a generic supertype for all XSLT elements; it contains the
                definitions of the standard attributes that may appear on any element.</p>    
        </xs:documentation>
    </xs:annotation>
    <xs:attribute name="default-collation" type="xsl:uri-list"/>
    <xs:attribute name="exclude-result-prefixes" type="xsl:prefix-list-or-all"/>
    <xs:attribute name="extension-element-prefixes" type="xsl:prefix-list"/>
    <xs:attribute name="use-when" type="xsl:expression"/>
    <xs:attribute name="xpath-default-namespace" type="xs:anyURI"/>
    <xs:anyAttribute namespace="##other" processContents="lax"/>
  </xs:complexType>

  <xs:complexType name="versioned-element-type" mixed="true">
    <xs:annotation>
        <xs:documentation>
            <p>This complex type provides a generic supertype for all XSLT elements with
                the exception of <code>xsl:output</code>; it contains the
                definitions of the <code>version</code> attribute that may appear on any element.
                </p>
             <p>The <code>xsl:output</code> does not use this definition because, although it
             has a <code>version</code> attribute, the syntax and semantics of this attribute are
             unrelated to the standard <code>version</code> attribute allowed on other elements.</p>    
        </xs:documentation>
    </xs:annotation>
    <xs:complexContent>
      <xs:extension base="xsl:generic-element-type">
        <xs:attribute name="version" type="xs:decimal" use="optional"/>
      </xs:extension>
    </xs:complexContent>
  </xs:complexType>

  <xs:complexType name="element-only-versioned-element-type" mixed="false">
    <xs:complexContent>
      <xs:restriction base="xsl:versioned-element-type">
        <xs:anyAttribute namespace="##other" processContents="lax"/>
      </xs:restriction>
    </xs:complexContent>
  </xs:complexType>

  <xs:complexType name="sequence-constructor">
    <xs:annotation>
        <xs:documentation>
            <p>This complex type provides a generic supertype for all XSLT elements that
                allow a sequence constructor as their content.
                </p>
        </xs:documentation>
    </xs:annotation>
    <xs:complexContent mixed="true">
      <xs:extension base="xsl:versioned-element-type">
        <xs:group ref="xsl:sequence-constructor-group" minOccurs="0" maxOccurs="unbounded"/>
      </xs:extension>
    </xs:complexContent>
  </xs:complexType>
  
  <xs:complexType name="sequence-constructor-and-select">
    <xs:annotation>
      <xs:documentation>
        <p>This complex type allows a sequence constructor and a select attribute.</p>
      </xs:documentation>
    </xs:annotation>
    <xs:complexContent mixed="true">
      <xs:extension base="xsl:sequence-constructor">
        <xs:attribute name="select" type="xsl:expression"/>
      </xs:extension>
    </xs:complexContent>
  </xs:complexType>
  
  <xs:complexType name="sequence-constructor-or-select">
    <xs:annotation>
      <xs:documentation>
        <p>This complex type allows a sequence constructor or a select attribute, but not both.</p>
      </xs:documentation>
    </xs:annotation>
    <xs:complexContent mixed="true">
      <xs:restriction base="xsl:sequence-constructor-and-select">
        <xs:group ref="xsl:sequence-constructor-group" minOccurs="0" maxOccurs="unbounded"/>
        <xs:assert test="not(exists(@select) and (exists(* except xsl:fallback) or exists(text()[normalize-space()])))"/>
      </xs:restriction>
    </xs:complexContent>
  </xs:complexType>

  <xs:group name="sequence-constructor-group">
    <xs:annotation>
        <xs:documentation>
            <p>This complex type provides a generic supertype for all XSLT elements that
                allow a sequence constructor as their content.
                </p>
        </xs:documentation>
    </xs:annotation>
    <xs:choice>
      <xs:element ref="xsl:instruction"/>
      <xs:group ref="xsl:result-elements"/>
    </xs:choice>
  </xs:group>

  <xs:element name="declaration" type="xsl:generic-element-type" abstract="true"/>

  <xs:element name="instruction" type="xsl:versioned-element-type" abstract="true"/>

  <!-- ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ -->
  <xs:annotation>
    <xs:documentation> PART B: definitions of individual XSLT elements Elements are listed in
      alphabetical order. </xs:documentation>
  </xs:annotation>
  <!-- ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ -->
  
  <xs:element name="accept">
    <xs:annotation>
        <xs:documentation>
            <p>This element appears as a child of <code>xsl:use-package</code> and defines 
            any variations that the containing package wishes to make to the visibility of
            components made available from a library package. For example, it may indicate that
            some of the public components in the library package are not to be made available
            to the containing package.</p>
        </xs:documentation>
    </xs:annotation>
    <xs:complexType>
      <xs:complexContent>
        <xs:extension base="xsl:element-only-versioned-element-type">
          <xs:attribute name="component" type="xsl:component-kind-type" use="required"/>
          <xs:attribute name="names" type="xsl:EQNames" use="required"/>
          <xs:attribute name="visibility" type="xsl:visibility-type" use="required"/>
        </xs:extension>
      </xs:complexContent>
    </xs:complexType>
  </xs:element>
  
  <xs:element name="accumulator" substitutionGroup="xsl:declaration">
    <xs:complexType>
      <xs:complexContent>
        <xs:extension base="xsl:element-only-versioned-element-type">
          <xs:sequence>
            <xs:element ref="xsl:accumulator-rule" minOccurs="1"  maxOccurs="unbounded"/>
          </xs:sequence>
          <xs:attribute name="name" type="xsl:EQName" />
          <xs:attribute name="post-descent" type="xsl:EQName" />
          <xs:attribute name="initial-value" type="xsl:expression"/>
          <xs:attribute name="as" type="xsl:sequence-type"/>
          <xs:attribute name="visibility" type="xsl:visibility-type"/>
          <xs:attribute name="streamable" type="xsl:yes-or-no"/>
        </xs:extension>
      </xs:complexContent>
    </xs:complexType>
  </xs:element>

  <xs:element name="accumulator-rule">
    <xs:complexType>
      <xs:complexContent>
        <xs:extension base="xsl:element-only-versioned-element-type">
          <xs:sequence/>
          <xs:attribute name="match" type="xsl:pattern" use="required"/>
          <xs:attribute name="phase">
            <xs:simpleType>
              <xs:restriction base="xs:NMTOKEN">
                <xs:enumeration value="start"/>
                <xs:enumeration value="end"/>
              </xs:restriction>           
            </xs:simpleType>
          </xs:attribute>
          <xs:attribute name="new-value" type="xsl:expression" use="required"/>
        </xs:extension>
      </xs:complexContent>
    </xs:complexType>
  </xs:element>

  <xs:element name="analyze-string" substitutionGroup="xsl:instruction">
    <xs:complexType>
      <xs:complexContent>
        <xs:extension base="xsl:element-only-versioned-element-type">
          <xs:sequence>
            <xs:element ref="xsl:matching-substring" minOccurs="0"/>
            <xs:element ref="xsl:non-matching-substring" minOccurs="0"/>
            <xs:element ref="xsl:fallback" minOccurs="0" maxOccurs="unbounded"/>
          </xs:sequence>
          <xs:attribute name="select" type="xsl:expression" use="required"/>
          <xs:attribute name="regex" type="xsl:avt" use="required"/>
          <xs:attribute name="flags" type="xsl:avt" default=""/>
        </xs:extension>
      </xs:complexContent>
    </xs:complexType>
  </xs:element>

  <xs:element name="apply-imports" substitutionGroup="xsl:instruction">
    <xs:complexType>
      <xs:complexContent>
        <xs:extension base="xsl:element-only-versioned-element-type">
          <xs:sequence>
            <xs:element ref="xsl:with-param" minOccurs="0" maxOccurs="unbounded"/>
          </xs:sequence>
        </xs:extension>
      </xs:complexContent>
    </xs:complexType>
  </xs:element>

  <xs:element name="apply-templates" substitutionGroup="xsl:instruction">
    <xs:complexType>
      <xs:complexContent>
        <xs:extension base="xsl:element-only-versioned-element-type">
          <xs:choice minOccurs="0" maxOccurs="unbounded">
            <xs:element ref="xsl:sort"/>
            <xs:element ref="xsl:with-param"/>
          </xs:choice>
          <xs:attribute name="select" type="xsl:expression" default="child::node()"/>
          <xs:attribute name="mode" type="xsl:mode"/>
          <xs:assert test="every $e in subsequence(xsl:sort, 2) satisfies empty($e/@stable)">
            <xs:annotation>
              <xs:documentation>
                <p>It is a static error if an xsl:sort element other than the first in a 
                  sequence of sibling xsl:sort elements has a stable attribute.
                </p>
              </xs:documentation>
            </xs:annotation>
          </xs:assert>
        </xs:extension>
      </xs:complexContent>
    </xs:complexType>
  </xs:element>
  
  <xs:element name="assert" substitutionGroup="xsl:instruction">
    <xs:complexType>
      <xs:complexContent mixed="true">
        <xs:extension base="xsl:sequence-constructor">
          <xs:attribute name="enabled" type="xsl:expression"/>
          <xs:attribute name="test" type="xsl:expression" use="required"/>
          <xs:attribute name="select" type="xsl:expression"/>
          <xs:attribute name="error-code" type="xsl:avt"/>
        </xs:extension>
      </xs:complexContent>
    </xs:complexType>
  </xs:element>

  <xs:element name="attribute" substitutionGroup="xsl:instruction">
    <xs:complexType>
      <xs:complexContent mixed="true">
        <xs:extension base="xsl:sequence-constructor-or-select">
          <xs:attribute name="name" type="xsl:avt" use="required"/>
          <xs:attribute name="namespace" type="xsl:avt"/>
          <xs:attribute name="separator" type="xsl:avt"/>
          <xs:attribute name="type" type="xsl:EQName"/>
          <xs:attribute name="validation" type="xsl:validation-type"/>
          <xs:attribute name="on-empty" type="xsl:expression"/>
          <xs:assert test="not(exists(@type) and exists(@validation))">
            <xs:annotation>
              <xs:documentation>
                <p>The <code>type</code> and <code>validation</code> attributes are mutually exclusive
                (if one is present, the other must be absent).</p>
              </xs:documentation>
            </xs:annotation>
          </xs:assert>
        </xs:extension>
      </xs:complexContent>
    </xs:complexType>
  </xs:element>

  <xs:element name="attribute-set" substitutionGroup="xsl:declaration">
    <xs:complexType>
      <xs:complexContent>
        <xs:extension base="xsl:element-only-versioned-element-type">
          <xs:sequence minOccurs="0" maxOccurs="unbounded">
            <xs:element ref="xsl:attribute"/>
          </xs:sequence>
          <xs:attribute name="name" type="xsl:EQName" use="required"/>
          <xs:attribute name="use-attribute-sets" type="xsl:EQNames" default=""/>
          <xs:attribute name="visibility" type="xsl:visibility-type"/>
        </xs:extension>
      </xs:complexContent>
    </xs:complexType>
  </xs:element>

  <xs:element name="break" substitutionGroup="xsl:instruction" type="xsl:sequence-constructor-or-select"/>

  <xs:element name="call-template" substitutionGroup="xsl:instruction">
    <xs:complexType>
      <xs:complexContent>
        <xs:extension base="xsl:element-only-versioned-element-type">
          <xs:sequence>
            <xs:element ref="xsl:with-param" minOccurs="0" maxOccurs="unbounded"/>
          </xs:sequence>
          <xs:attribute name="name" type="xsl:EQName" use="required"/>
        </xs:extension>
      </xs:complexContent>
    </xs:complexType>
  </xs:element>

  <xs:element name="catch">
    <xs:complexType>
      <xs:complexContent mixed="true">
        <xs:extension base="xsl:sequence-constructor-or-select">
          <xs:attribute name="errors" type="xs:token" use="required"/>
        </xs:extension>
      </xs:complexContent>
    </xs:complexType>
  </xs:element>

  <xs:element name="character-map" substitutionGroup="xsl:declaration">
    <xs:complexType>
      <xs:complexContent>
        <xs:extension base="xsl:element-only-versioned-element-type">
          <xs:sequence>
            <xs:element ref="xsl:output-character" minOccurs="0" maxOccurs="unbounded"/>
          </xs:sequence>
          <xs:attribute name="name" type="xsl:EQName" use="required"/>
          <xs:attribute name="use-character-maps" type="xsl:EQNames" default=""/>
        </xs:extension>
      </xs:complexContent>
    </xs:complexType>
  </xs:element>

  <xs:element name="choose" substitutionGroup="xsl:instruction">
    <xs:complexType>
      <xs:complexContent>
        <xs:extension base="xsl:element-only-versioned-element-type">
          <xs:sequence>
            <xs:element ref="xsl:when" maxOccurs="unbounded"/>
            <xs:element ref="xsl:otherwise" minOccurs="0"/>
          </xs:sequence>
        </xs:extension>
      </xs:complexContent>
    </xs:complexType>
  </xs:element>

  <xs:element name="comment" substitutionGroup="xsl:instruction" type="xsl:sequence-constructor-or-select"/>

  <xs:element name="context-item">
    <xs:complexType>
      <xs:complexContent>
        <xs:extension base="xsl:element-only-versioned-element-type">
          <xs:attribute name="as" type="xsl:item-type"/>
          <xs:attribute name="use">
            <xs:simpleType>
              <xs:restriction base="xs:string">
                <xs:enumeration value="required"/>
                <xs:enumeration value="optional"/>
                <xs:enumeration value="prohibited"/>
              </xs:restriction>
            </xs:simpleType>
          </xs:attribute>
        </xs:extension>
      </xs:complexContent>
    </xs:complexType>
  </xs:element>

  <xs:element name="copy" substitutionGroup="xsl:instruction">
    <xs:complexType>
      <xs:complexContent mixed="true">
        <xs:extension base="xsl:sequence-constructor">
          <xs:attribute name="select" type="xsl:expression"/>
          <xs:attribute name="copy-namespaces" type="xsl:yes-or-no" default="yes"/>
          <xs:attribute name="inherit-namespaces" type="xsl:yes-or-no" default="yes"/>
          <xs:attribute name="use-attribute-sets" type="xsl:EQNames" default=""/>
          <xs:attribute name="type" type="xsl:EQName"/>
          <xs:attribute name="validation" type="xsl:validation-type"/>
          <xs:attribute name="on-empty" type="xsl:expression"/>
          <xs:assert test="not(exists(@type) and exists(@validation))">
            <xs:annotation>
              <xs:documentation>
                <p>The <code>type</code> and <code>validation</code> attributes are mutually exclusive
                  (if one is present, the other must be absent).</p>
              </xs:documentation>
            </xs:annotation>
          </xs:assert>
        </xs:extension>
      </xs:complexContent>
    </xs:complexType>
  </xs:element>

  <xs:element name="copy-of" substitutionGroup="xsl:instruction">
    <xs:complexType>
      <xs:complexContent mixed="true">
        <xs:extension base="xsl:versioned-element-type">
          <xs:attribute name="select" type="xsl:expression" use="required"/>
          <xs:attribute name="copy-namespaces" type="xsl:yes-or-no" default="yes"/>
          <xs:attribute name="type" type="xsl:EQName"/>
          <xs:attribute name="validation" type="xsl:validation-type"/>
          <xs:assert test="not(exists(@type) and exists(@validation))">
            <xs:annotation>
              <xs:documentation>
                <p>The <code>type</code> and <code>validation</code> attributes are mutually exclusive
                  (if one is present, the other must be absent).</p>
              </xs:documentation>
            </xs:annotation>
          </xs:assert>
        </xs:extension>
      </xs:complexContent>
    </xs:complexType>
  </xs:element>

  <xs:element name="document" substitutionGroup="xsl:instruction">
    <xs:complexType>
      <xs:complexContent mixed="true">
        <xs:extension base="xsl:sequence-constructor">
          <xs:attribute name="type" type="xsl:EQName"/>
          <xs:attribute name="validation" type="xsl:validation-type"/>
          <xs:assert test="not(exists(@type) and exists(@validation))">
            <xs:annotation>
              <xs:documentation>
                <p>The <code>type</code> and <code>validation</code> attributes are mutually exclusive
                  (if one is present, the other must be absent).</p>
              </xs:documentation>
            </xs:annotation>
          </xs:assert>
        </xs:extension>
      </xs:complexContent>
    </xs:complexType>
  </xs:element>

  <xs:element name="decimal-format" substitutionGroup="xsl:declaration">
    <xs:complexType>
      <xs:complexContent>
        <xs:extension base="xsl:element-only-versioned-element-type">
          <xs:attribute name="name" type="xsl:EQName"/>
          <xs:attribute name="decimal-separator" type="xsl:char" default="."/>
          <xs:attribute name="grouping-separator" type="xsl:char" default=","/>
          <xs:attribute name="infinity" type="xs:string" default="Infinity"/>
          <xs:attribute name="minus-sign" type="xsl:char" default="-"/>
          <xs:attribute name="NaN" type="xs:string" default="NaN"/>
          <xs:attribute name="percent" type="xsl:char" default="%"/>
          <xs:attribute name="per-mille" type="xsl:char" default="~"/>
          <xs:attribute name="zero-digit" type="xsl:char" default="0"/>
          <xs:attribute name="digit" type="xsl:char" default="#"/>
          <xs:attribute name="pattern-separator" type="xsl:char" default=";"/>
        </xs:extension>
      </xs:complexContent>
    </xs:complexType>
  </xs:element>

  <xs:element name="element" substitutionGroup="xsl:instruction">
    <xs:complexType mixed="true">
      <xs:complexContent>
        <xs:extension base="xsl:sequence-constructor">
          <xs:attribute name="name" type="xsl:avt" use="required"/>
          <xs:attribute name="namespace" type="xsl:avt"/>
          <xs:attribute name="inherit-namespaces" type="xsl:yes-or-no" default="yes"/>
          <xs:attribute name="use-attribute-sets" type="xsl:EQNames" default=""/>
          <xs:attribute name="type" type="xsl:EQName"/>
          <xs:attribute name="validation" type="xsl:validation-type"/>
          <xs:attribute name="on-empty" type="xsl:expression"/>
          <xs:assert test="not(exists(@type) and exists(@validation))">
            <xs:annotation>
              <xs:documentation>
                <p>The <code>type</code> and <code>validation</code> attributes are mutually exclusive
                  (if one is present, the other must be absent).</p>
              </xs:documentation>
            </xs:annotation>
          </xs:assert>
        </xs:extension>
      </xs:complexContent>
    </xs:complexType>
  </xs:element>

  <xs:element name="evaluate" substitutionGroup="xsl:instruction">
    <xs:complexType>
      <xs:complexContent mixed="true">
        <xs:extension base="xsl:element-only-versioned-element-type">
          <xs:choice minOccurs="0" maxOccurs="unbounded">
            <xs:element ref="xsl:with-param"/>
            <xs:element ref="xsl:fallback"/>
          </xs:choice>
          <xs:attribute name="xpath" type="xsl:expression" use="required"/>
          <xs:attribute name="as" type="xsl:sequence-type"/>
          <xs:attribute name="base-uri" type="xsl:avt"/>
          <xs:attribute name="context-item" type="xsl:expression"/>
          <xs:attribute name="namespace-context" type="xsl:expression"/>
          <xs:attribute name="schema-aware" type="xsl:yes-or-no"/>         
        </xs:extension>
      </xs:complexContent>
    </xs:complexType>
  </xs:element>
  
  <xs:element name="expose">
    <xs:annotation>
        <xs:documentation>
            <p>This element appears as a child of <code>xsl:use-package</code> and defines 
            the visibility of components that are made available (or not) by this package
            to other using packages.</p>
        </xs:documentation>
    </xs:annotation>
    <xs:complexType>
      <xs:complexContent>
        <xs:extension base="xsl:element-only-versioned-element-type">
          <xs:attribute name="component" type="xsl:component-kind-type"/>
          <xs:attribute name="names" type="xsl:EQNames"/>
          <xs:attribute name="visibility" type="xsl:visibility-not-hidden-type"/>
        </xs:extension>
      </xs:complexContent>
    </xs:complexType>
  </xs:element>

  <xs:element name="fallback" substitutionGroup="xsl:instruction" type="xsl:sequence-constructor"/>

  <xs:element name="for-each" substitutionGroup="xsl:instruction">
    <xs:complexType>
      <xs:complexContent mixed="true">
        <xs:extension base="xsl:versioned-element-type">
          <xs:sequence>
            <xs:element ref="xsl:sort" minOccurs="0" maxOccurs="unbounded"/>
            <xs:group ref="xsl:sequence-constructor-group" minOccurs="0" maxOccurs="unbounded"/>
          </xs:sequence>
          <xs:attribute name="select" type="xsl:expression" use="required"/>
          <xs:assert test="every $e in subsequence(xsl:sort, 2) satisfies empty($e/@stable)">
            <xs:annotation>
              <xs:documentation>
                <p>It is a static error if an xsl:sort element other than the first in a 
                  sequence of sibling xsl:sort elements has a stable attribute.
                </p>
              </xs:documentation>
            </xs:annotation>
          </xs:assert>
        </xs:extension>
      </xs:complexContent>
    </xs:complexType>
  </xs:element>

  <xs:element name="for-each-group" substitutionGroup="xsl:instruction">
    <xs:complexType>
      <xs:complexContent mixed="true">
        <xs:extension base="xsl:versioned-element-type">
          <xs:sequence>
            <xs:element ref="xsl:sort" minOccurs="0" maxOccurs="unbounded"/>
            <xs:group ref="xsl:sequence-constructor-group" minOccurs="0" maxOccurs="unbounded"/>
          </xs:sequence>
          <xs:attribute name="select" type="xsl:expression" use="required"/>
          <xs:attribute name="group-by" type="xsl:expression"/>
          <xs:attribute name="group-adjacent" type="xsl:expression"/>
          <xs:attribute name="group-starting-with" type="xsl:pattern"/>
          <xs:attribute name="group-ending-with" type="xsl:pattern"/>
          <xs:attribute name="bind-group" type="xsl:EQName"/>
          <xs:attribute name="bind-grouping-key" type="xsl:EQName"/>
          <xs:attribute name="composite" type="xsl:yes-or-no"/>
          <xs:attribute name="collation" type="xsl:avt"/>
          <xs:assert test="every $e in subsequence(xsl:sort, 2) satisfies empty($e/@stable)">
            <xs:annotation>
              <xs:documentation>
                <p>It is a static error if an xsl:sort element other than the first in a 
                  sequence of sibling xsl:sort elements has a stable attribute.
                </p>
              </xs:documentation>
            </xs:annotation>
          </xs:assert>
          <xs:assert test="count((@group-by, @group-adjacent, @group-starting-with, @group-ending-with)) = 1">
            <xs:annotation>
              <xs:documentation>
                <p>These four attributes are mutually exclusive: it is a static error 
                  if none of these four attributes is present or if more than one of them is present.
                </p>
              </xs:documentation>
            </xs:annotation>
          </xs:assert>
          <xs:assert test="if (exists(@collation) or exists(@composite)) then (exists(@group-by) or exists(@group-adjacent)) else true()">
            <xs:annotation>
              <xs:documentation>
                <p>It is an error to specify the collation attribute or the composite attribute 
                  if neither the group-by attribute nor group-adjacent attribute is specified.
                </p>
              </xs:documentation>
            </xs:annotation>
          </xs:assert>
          <xs:assert test="if (exists(@bind-grouping-key)) then (exists(@group-by) or exists(@group-adjacent)) else true()">
            <xs:annotation>
              <xs:documentation>
                <p>It is a static error if the bind-grouping-key attribute is present on an 
                  xsl:for-each-group instruction unless either the group-by or group-adjacent attribute is present.    
                </p>
              </xs:documentation>
            </xs:annotation>
          </xs:assert>
        </xs:extension>
      </xs:complexContent>
    </xs:complexType>
  </xs:element>

  <xs:element name="fork" substitutionGroup="xsl:instruction">
    <xs:complexType>
      <xs:complexContent mixed="true">
        <xs:extension base="xsl:versioned-element-type">
          <xs:choice minOccurs="1" maxOccurs="unbounded">
            <xs:element ref="xsl:sequence"/>
            <xs:element ref="xsl:fallback"/>
          </xs:choice>
        </xs:extension>
      </xs:complexContent>
    </xs:complexType>
  </xs:element>

  <xs:element name="function" substitutionGroup="xsl:declaration">
    <xs:complexType>
      <xs:complexContent mixed="true">
        <xs:extension base="xsl:versioned-element-type">
          <xs:sequence>
            <xs:element ref="xsl:param" minOccurs="0" maxOccurs="unbounded"/>
            <xs:group ref="xsl:sequence-constructor-group" minOccurs="0" maxOccurs="unbounded"/>
          </xs:sequence>
          <xs:attribute name="name" type="xsl:EQName" use="required"/>
          <xs:attribute name="override" type="xsl:yes-or-no" default="yes"/>
          <xs:attribute name="as" type="xsl:sequence-type" default="item()*"/>
          <xs:attribute name="visibility" type="xsl:visibility-type"/>
          <xs:assert test="every $e in xsl:param satisfies (empty($e/@select) and empty($e/child::node()))">
            <xs:annotation>
              <xs:documentation>
                <p>A parameter for a function must have no default value.</p>
              </xs:documentation>
            </xs:annotation>
          </xs:assert>
          <xs:assert test="every $e in xsl:param satisfies empty($e/@visibility)">
            <xs:annotation>
              <xs:documentation>
                <p>A parameter for a function must have no <code>visibility</code> attribute.</p>
              </xs:documentation>
            </xs:annotation>
          </xs:assert>
          <xs:assert test="every $e in xsl:param satisfies empty($e/@required)">
            <xs:annotation>
              <xs:documentation>
                <p>A parameter for a function must have no <code>required</code> attribute.</p>
              </xs:documentation>
            </xs:annotation>
          </xs:assert>
        </xs:extension>
      </xs:complexContent>
    </xs:complexType>
  </xs:element>
  
  
  
  <xs:group name="function-model">
    <xs:sequence>
      <xs:element ref="xsl:param" minOccurs="0" maxOccurs="unbounded"/>
      <xs:group ref="xsl:sequence-constructor-group" minOccurs="0" maxOccurs="unbounded"/>
    </xs:sequence>
  </xs:group>

  <xs:element name="if" substitutionGroup="xsl:instruction">
    <xs:complexType>
      <xs:complexContent mixed="true">
        <xs:extension base="xsl:sequence-constructor">
          <xs:attribute name="test" type="xsl:expression" use="required"/>
        </xs:extension>
      </xs:complexContent>
    </xs:complexType>
  </xs:element>

  <xs:element name="import">
    <xs:complexType>
      <xs:complexContent>
        <xs:extension base="xsl:element-only-versioned-element-type">
          <xs:attribute name="href" type="xs:anyURI" use="required"/>
        </xs:extension>
      </xs:complexContent>
    </xs:complexType>
  </xs:element>

  <xs:element name="import-schema" substitutionGroup="xsl:declaration">
    <xs:complexType>
      <xs:complexContent>
        <xs:extension base="xsl:element-only-versioned-element-type">
          <xs:sequence>
            <xs:element ref="xs:schema" minOccurs="0" maxOccurs="1"/>
          </xs:sequence>
          <xs:attribute name="namespace" type="xs:anyURI"/>
          <xs:attribute name="schema-location" type="xs:anyURI"/>
        </xs:extension>
      </xs:complexContent>
    </xs:complexType>
  </xs:element>

  <xs:element name="include" substitutionGroup="xsl:declaration">
    <xs:complexType>
      <xs:complexContent>
        <xs:extension base="xsl:element-only-versioned-element-type">
          <xs:attribute name="href" type="xs:anyURI" use="required"/>
        </xs:extension>
      </xs:complexContent>
    </xs:complexType>
  </xs:element>

  <xs:element name="iterate" substitutionGroup="xsl:instruction">
    <xs:complexType>
      <xs:complexContent mixed="true">
        <xs:extension base="xsl:versioned-element-type">
          <xs:sequence>
            <xs:element ref="xsl:param" minOccurs="0" maxOccurs="unbounded"/>
            <xs:group ref="xsl:sequence-constructor-group" minOccurs="0" maxOccurs="unbounded"/>
            <xs:element ref="xsl:on-completion" minOccurs="0" maxOccurs="1"/>
          </xs:sequence>
          <xs:attribute name="select" type="xsl:expression" use="required"/>
        </xs:extension>
      </xs:complexContent>
    </xs:complexType>
  </xs:element>

  <xs:element name="key" substitutionGroup="xsl:declaration">
    <xs:complexType>
      <xs:complexContent mixed="true">
        <xs:extension base="xsl:sequence-constructor">
          <xs:attribute name="name" type="xsl:EQName" use="required"/>
          <xs:attribute name="match" type="xsl:pattern" use="required"/>
          <xs:attribute name="use" type="xsl:expression"/>
          <xs:attribute name="composite" type="xsl:yes-or-no"/>
          <xs:attribute name="collation" type="xs:anyURI"/>
        </xs:extension>
      </xs:complexContent>
    </xs:complexType>
  </xs:element>

  <xs:element name="matching-substring" type="xsl:sequence-constructor"/>

  <xs:element name="merge" substitutionGroup="xsl:instruction">
    <xs:complexType>
      <xs:complexContent>
        <xs:extension base="xsl:element-only-versioned-element-type">
          <xs:sequence>
            <xs:element ref="xsl:merge-source" minOccurs="0" maxOccurs="1"/>
            <xs:element ref="xsl:merge-action" minOccurs="1" maxOccurs="1"/>
            <xs:element ref="xsl:fallback" minOccurs="0" maxOccurs="unbounded"/>
          </xs:sequence>
          <xs:attribute name="bind-group" type="xsl:EQName"/>
          <xs:attribute name="bind-key" type="xsl:EQName"/>
        </xs:extension>
      </xs:complexContent>
    </xs:complexType>
  </xs:element>

  <xs:element name="merge-action" type="xsl:sequence-constructor"/>

  <xs:element name="merge-key" substitutionGroup="xsl:instruction">
    <xs:complexType>
      <xs:complexContent mixed="true">
        <xs:extension base="xsl:versioned-element-type">
          <xs:sequence>
            <xs:group ref="xsl:sequence-constructor-group" minOccurs="0" maxOccurs="unbounded"/>
          </xs:sequence>
          <xs:attribute name="select" type="xsl:expression"/>
          <xs:attribute name="lang" type="xsl:avt"/>
          <xs:attribute name="order" type="xsl:avt"/>
          <xs:attribute name="collation" type="xs:anyURI"/>
          <xs:attribute name="case-order" type="xsl:avt"/>
          <xs:attribute name="data-type" type="xsl:avt"/>
        </xs:extension>
      </xs:complexContent>
    </xs:complexType>
  </xs:element>

  <xs:element name="merge-source">
    <xs:complexType>
      <xs:complexContent>
        <xs:extension base="xsl:element-only-versioned-element-type">
          <xs:sequence>
            <xs:element ref="xsl:merge-key" minOccurs="1" maxOccurs="unbounded"/>
          </xs:sequence>
          <xs:attribute name="for-each" type="xsl:expression"/>
          <xs:attribute name="select" type="xsl:expression" use="required"/>
          <xs:attribute name="bind-source" type="xsl:EQName"/>
          <xs:attribute name="streamable" type="xsl:yes-or-no"/>
          <xs:attribute name="sort-before-merge" type="xsl:yes-or-no"/>
        </xs:extension>
      </xs:complexContent>
    </xs:complexType>
  </xs:element>

  <xs:element name="message" substitutionGroup="xsl:instruction">
    <xs:complexType>
      <xs:complexContent mixed="true">
        <xs:extension base="xsl:sequence-constructor">
          <xs:attribute name="select" type="xsl:expression"/>
          <xs:attribute name="terminate" type="xsl:avt" default="no"/>
          <xs:attribute name="error-code" type="xsl:avt"/>
        </xs:extension>
      </xs:complexContent>
    </xs:complexType>
  </xs:element>

  <xs:element name="mode" substitutionGroup="xsl:declaration">
    <xs:complexType>
      <xs:complexContent mixed="false">
        <xs:extension base="xsl:element-only-versioned-element-type">
          <xs:sequence>
            <xs:element ref="xsl:context-item" minOccurs="0" maxOccurs="unbounded"/>
          </xs:sequence>
          <xs:attribute name="name" type="xsl:EQName"/>
          <xs:attribute name="streamable" type="xsl:yes-or-no" default="no"/>
          <xs:attribute name="initial" type="xsl:yes-or-no" default="yes"/>
          <xs:attribute name="on-no-match" type="xsl:on-no-match-type" default="shallow-skip"/>
          <xs:attribute name="on-multiple-match" type="xsl:on-multiple-match-type" default="use-last"/>
          <xs:attribute name="warning-on-no-match" type="xsl:yes-or-no"/>
          <xs:attribute name="warning-on-multiple-match" type="xsl:yes-or-no"/>
          <xs:attribute name="typed" type="xsl:typed-type"/>
          <xs:attribute name="visibility">
            <xs:simpleType>
              <xs:restriction base="xsl:visibility-type">
                <xs:enumeration value="public"/>
                <xs:enumeration value="private"/>
                <xs:enumeration value="final"/>
              </xs:restriction>
            </xs:simpleType>
          </xs:attribute>
          <xs:assert test="not(normalize-space(@initial) = 'no' and exists(xsl:context-item))">
            <xs:annotation>
              <xs:documentation>
                <p>It is a static error if an xsl:mode declaration specifying initial="no" 
                  contains an xsl:context-item element.
                </p>
              </xs:documentation>
            </xs:annotation>
          </xs:assert> 
        </xs:extension>
      </xs:complexContent>
    </xs:complexType>
  </xs:element>


  <xs:element name="namespace" substitutionGroup="xsl:instruction">
    <xs:complexType>
      <xs:complexContent mixed="true">
        <xs:extension base="xsl:sequence-constructor-or-select">
          <xs:attribute name="name" type="xsl:avt" use="required"/>
        </xs:extension>
      </xs:complexContent>
    </xs:complexType>
  </xs:element>

  <xs:element name="namespace-alias" substitutionGroup="xsl:declaration">
    <xs:complexType>
      <xs:complexContent>
        <xs:extension base="xsl:element-only-versioned-element-type">
          <xs:attribute name="stylesheet-prefix" type="xsl:prefix-or-default" use="required"/>
          <xs:attribute name="result-prefix" type="xsl:prefix-or-default" use="required"/>
        </xs:extension>
      </xs:complexContent>
    </xs:complexType>
  </xs:element>


  <xs:element name="next-iteration" substitutionGroup="xsl:instruction">
    <xs:complexType>
      <xs:complexContent mixed="true">
        <xs:extension base="xsl:element-only-versioned-element-type">
          <xs:sequence>
            <xs:element ref="xsl:with-param" minOccurs="0" maxOccurs="unbounded"/>
          </xs:sequence>
        </xs:extension>
      </xs:complexContent>
    </xs:complexType>
  </xs:element>


  <xs:element name="next-match" substitutionGroup="xsl:instruction">
    <xs:complexType>
      <xs:complexContent>
        <xs:extension base="xsl:element-only-versioned-element-type">
          <xs:choice minOccurs="0" maxOccurs="unbounded">
            <xs:element ref="xsl:with-param"/>
            <xs:element ref="xsl:fallback"/>
          </xs:choice>
        </xs:extension>
      </xs:complexContent>
    </xs:complexType>
  </xs:element>

  <xs:element name="non-matching-substring" type="xsl:sequence-constructor"/>

  <xs:element name="number" substitutionGroup="xsl:instruction">
    <xs:complexType>
      <xs:complexContent mixed="true">
        <xs:extension base="xsl:versioned-element-type">
          <xs:attribute name="value" type="xsl:expression"/>
          <xs:attribute name="select" type="xsl:expression"/>
          <xs:attribute name="level" type="xsl:level" default="single"/>
          <xs:attribute name="count" type="xsl:pattern"/>
          <xs:attribute name="from" type="xsl:pattern"/>
          <xs:attribute name="format" type="xsl:avt" default="1"/>
          <xs:attribute name="lang" type="xsl:avt"/>
          <xs:attribute name="letter-value" type="xsl:avt"/>
          <xs:attribute name="ordinal" type="xsl:avt"/>
          <xs:attribute name="start-at" type="xsl:avt"/>
          <xs:attribute name="grouping-separator" type="xsl:avt"/>
          <xs:attribute name="grouping-size" type="xsl:avt"/>
          <xs:assert test="if (exists(@value)) then empty((@select, @level, @count, @from)) else true()">
            <xs:annotation>
              <xs:documentation>
                <p>It is a static error if the value attribute of xsl:number is present unless the 
                  select, level, count, and from attributes are all absent.
                </p>
              </xs:documentation>
            </xs:annotation>
          </xs:assert>         
          </xs:extension>
      </xs:complexContent>
    </xs:complexType>
  </xs:element>

  <xs:element name="on-completion" type="xsl:sequence-constructor-or-select"/>

  <xs:element name="otherwise" type="xsl:sequence-constructor"/>

  <xs:element name="output" substitutionGroup="xsl:declaration">
    <xs:complexType>
      <xs:complexContent mixed="true">
        <xs:extension base="xsl:generic-element-type">
          <xs:attribute name="name" type="xsl:EQName"/>
          <xs:attribute name="method" type="xsl:method"/>
          <xs:attribute name="byte-order-mark" type="xsl:yes-or-no"/>
          <xs:attribute name="cdata-section-elements" type="xsl:EQNames"/>
          <xs:attribute name="doctype-public" type="xs:string"/>
          <xs:attribute name="doctype-system" type="xs:string"/>
          <xs:attribute name="encoding" type="xs:string"/>
          <xs:attribute name="escape-uri-attributes" type="xsl:yes-or-no"/>
          <xs:attribute name="include-content-type" type="xsl:yes-or-no"/>
          <xs:attribute name="indent" type="xsl:yes-or-no"/>
          <xs:attribute name="media-type" type="xs:string"/>
          <xs:attribute name="normalization-form" type="xs:NMTOKEN"/>
          <xs:attribute name="omit-xml-declaration" type="xsl:yes-or-no"/>
          <xs:attribute name="standalone" type="xsl:yes-or-no-or-omit"/>
          <xs:attribute name="suppress-indentation" type="xsl:EQNames"/>
          <xs:attribute name="undeclare-prefixes" type="xsl:yes-or-no"/>
          <xs:attribute name="use-character-maps" type="xsl:EQNames"/>
          <xs:attribute name="version" type="xs:NMTOKEN"/>
        </xs:extension>
      </xs:complexContent>
    </xs:complexType>
  </xs:element>

  <xs:element name="output-character">
    <xs:complexType>
      <xs:complexContent>
        <xs:extension base="xsl:element-only-versioned-element-type">
          <xs:attribute name="character" type="xsl:char" use="required"/>
          <xs:attribute name="string" type="xs:string" use="required"/>
        </xs:extension>
      </xs:complexContent>
    </xs:complexType>
  </xs:element>
  
  <xs:element name="override">
    <xs:annotation>
        <xs:documentation>
            <p>This element appears as a child of <code>xsl:use-package</code> and defines 
            any overriding definitions of components that the containing package wishes to make 
            to the components made available from a library package.</p>
        </xs:documentation>
    </xs:annotation>
    <xs:complexType>
      <xs:complexContent>
        <xs:extension base="xsl:element-only-versioned-element-type">
          <xs:choice minOccurs="0" maxOccurs="unbounded">
            <xs:element ref="xsl:template"/>
            <xs:element ref="xsl:function"/>
            <xs:element ref="xsl:variable"/>
            <xs:element ref="xsl:param"/>
            <xs:element ref="xsl:attribute-set"/>
          </xs:choice>          
          <xs:assert test="every $e in * satisfies exists($e/@name)">
            <xs:annotation>
              <xs:documentation>
                <p>Every component that is overridden (in particular, templates) must have a <code>name</code> attribute</p>
              </xs:documentation>
            </xs:annotation>
          </xs:assert>
          <xs:assert test="every $e in xsl:template satisfies empty($e/@match)">
            <xs:annotation>
              <xs:documentation>
                <p>A template that is overridden must not have a <code>match</code> attribute</p>
              </xs:documentation>
            </xs:annotation>
          </xs:assert>  
        </xs:extension>
      </xs:complexContent>
    </xs:complexType>   
  </xs:element>
    
  <xs:element name="package">
    <xs:complexType>
      <xs:complexContent>
        <xs:extension base="xsl:element-only-versioned-element-type">
          <xs:sequence>
            <xs:element ref="xsl:use-package" minOccurs="0" maxOccurs="unbounded"/>
            <xs:element ref="xsl:transform" minOccurs="1" maxOccurs="1"/>
            <xs:element ref="xsl:expose" minOccurs="0" maxOccurs="unbounded"/>
          </xs:sequence>
          <xs:attribute name="name" type="xs:anyURI"/>
          <xs:attribute name="package-version" type="xs:string"/>
        </xs:extension>
      </xs:complexContent>
    </xs:complexType>
  </xs:element>

  <xs:element name="param" substitutionGroup="xsl:declaration">
    <xs:annotation>
        <xs:documentation>
            <p>Declaration of the <code>xsl:param</code> element, used both defining function
            parameters, template parameters, parameters to <code>xsl:iterate</code>,
            and global stylesheet parameters.</p>
        </xs:documentation>
    </xs:annotation>
    <xs:complexType>
      <xs:complexContent mixed="true">
        <xs:extension base="xsl:sequence-constructor-or-select">
          <xs:attribute name="name" type="xsl:EQName" use="required"/>
          <xs:attribute name="as" type="xsl:sequence-type"/>
          <xs:attribute name="required" type="xsl:yes-or-no"/>
          <xs:attribute name="tunnel" type="xsl:yes-or-no"/>
          <xs:attribute name="visibility" type="xsl:visibility-type" use="optional"/>
        </xs:extension>
      </xs:complexContent>
    </xs:complexType>
  </xs:element>

  

  <xs:element name="perform-sort" substitutionGroup="xsl:instruction">
    <xs:complexType>
      <xs:complexContent mixed="true">
        <xs:extension base="xsl:versioned-element-type">
          <xs:sequence>
            <xs:element ref="xsl:sort" minOccurs="1" maxOccurs="unbounded"/>
            <xs:group ref="xsl:sequence-constructor-group" minOccurs="0" maxOccurs="unbounded"/>
          </xs:sequence>
          <xs:attribute name="select" type="xsl:expression"/>
          <xs:assert test="every $e in subsequence(xsl:sort, 2) satisfies empty($e/@stable)">
            <xs:annotation>
              <xs:documentation>
                <p>It is a static error if an xsl:sort element other than the first in a 
                  sequence of sibling xsl:sort elements has a stable attribute.
                </p>
              </xs:documentation>
            </xs:annotation>
          </xs:assert>
        </xs:extension>
      </xs:complexContent>
    </xs:complexType>
  </xs:element>

  <xs:element name="preserve-space" substitutionGroup="xsl:declaration">
    <xs:complexType>
      <xs:complexContent>
        <xs:extension base="xsl:element-only-versioned-element-type">
          <xs:attribute name="elements" type="xsl:nametests" use="required"/>
        </xs:extension>
      </xs:complexContent>
    </xs:complexType>
  </xs:element>

  <xs:element name="processing-instruction" substitutionGroup="xsl:instruction">
    <xs:complexType>
      <xs:complexContent mixed="true">
        <xs:extension base="xsl:sequence-constructor-or-select">
          <xs:attribute name="name" type="xsl:avt" use="required"/>
        </xs:extension>
      </xs:complexContent>
    </xs:complexType>
  </xs:element>

  <xs:element name="result-document" substitutionGroup="xsl:instruction">
    <xs:complexType>
      <xs:complexContent mixed="true">
        <xs:extension base="xsl:sequence-constructor">
          <xs:attribute name="format" type="xsl:avt"/>
          <xs:attribute name="href" type="xsl:avt"/>
          <xs:attribute name="type" type="xsl:EQName"/>
          <xs:attribute name="validation" type="xsl:validation-type"/>
          <xs:attribute name="method" type="xsl:avt"/>
          <xs:attribute name="byte-order-mark" type="xsl:avt"/>
          <xs:attribute name="cdata-section-elements" type="xsl:avt"/>
          <xs:attribute name="doctype-public" type="xsl:avt"/>
          <xs:attribute name="doctype-system" type="xsl:avt"/>
          <xs:attribute name="encoding" type="xsl:avt"/>
          <xs:attribute name="escape-uri-attributes" type="xsl:avt"/>
          <xs:attribute name="include-content-type" type="xsl:avt"/>
          <xs:attribute name="indent" type="xsl:avt"/>
          <xs:attribute name="media-type" type="xsl:avt"/>
          <xs:attribute name="normalization-form" type="xsl:avt"/>
          <xs:attribute name="omit-xml-declaration" type="xsl:avt"/>
          <xs:attribute name="standalone" type="xsl:avt"/>
          <xs:attribute name="suppress-indentation" type="xsl:avt"/>
          <xs:attribute name="undeclare-prefixes" type="xsl:avt"/>
          <xs:attribute name="use-character-maps" type="xsl:EQNames"/>
          <xs:attribute name="output-version" type="xsl:avt"/>
          <xs:assert test="not(exists(@type) and exists(@validation))">
            <xs:annotation>
              <xs:documentation>
                <p>The <code>type</code> and <code>validation</code> attributes are mutually exclusive
                  (if one is present, the other must be absent).</p>
              </xs:documentation>
            </xs:annotation>
          </xs:assert>
        </xs:extension>
      </xs:complexContent>
    </xs:complexType>
  </xs:element>
  
  <xs:element name="sequence" substitutionGroup="xsl:instruction" type="xsl:sequence-constructor-or-select"/>

  <xs:element name="sort">
    <xs:complexType>
      <xs:complexContent mixed="true">
        <xs:extension base="xsl:sequence-constructor-or-select">
          <xs:attribute name="lang" type="xsl:avt"/>
          <xs:attribute name="data-type" type="xsl:avt" default="text"/>
          <xs:attribute name="order" type="xsl:avt" default="ascending"/>
          <xs:attribute name="case-order" type="xsl:avt"/>
          <xs:attribute name="collation" type="xsl:avt"/>
          <xs:attribute name="stable" type="xsl:yes-or-no"/>
        </xs:extension>
      </xs:complexContent>
    </xs:complexType>
  </xs:element>

  <xs:element name="strip-space" substitutionGroup="xsl:declaration">
    <xs:complexType>
      <xs:complexContent>
        <xs:extension base="xsl:element-only-versioned-element-type">
          <xs:attribute name="elements" type="xsl:nametests" use="required"/>
        </xs:extension>
      </xs:complexContent>
    </xs:complexType>
  </xs:element>

  <xs:element name="stylesheet" substitutionGroup="xsl:transform"/>

  <xs:element name="stream" substitutionGroup="xsl:instruction">
    <xs:complexType>
      <xs:complexContent>
        <xs:extension base="xsl:sequence-constructor">
          <xs:attribute name="href" type="xs:anyURI" use="required"/>
        </xs:extension>
      </xs:complexContent>
    </xs:complexType>
  </xs:element>

  <xs:element name="template" substitutionGroup="xsl:declaration">
    <xs:complexType>
      <xs:complexContent mixed="true">
        <xs:extension base="xsl:versioned-element-type">
          <xs:sequence>
            <xs:element ref="xsl:context-item" minOccurs="0" maxOccurs="1"/>
            <xs:element ref="xsl:param" minOccurs="0" maxOccurs="unbounded"/>
            <xs:group ref="xsl:sequence-constructor-group" minOccurs="0" maxOccurs="unbounded"/>
          </xs:sequence>
          <xs:attribute name="match" type="xsl:pattern"/>
          <xs:attribute name="priority" type="xs:decimal"/>
          <xs:attribute name="mode" type="xsl:modes"/>
          <xs:attribute name="name" type="xsl:EQName"/>
          <xs:attribute name="as" type="xsl:sequence-type" default="item()*"/>
          <xs:attribute name="visibility" type="xsl:visibility-type"/>
          <xs:assert test="exists(@match) or exists(@name)">
            <xs:annotation>
              <xs:documentation>
                <p>An xsl:template element must have either a match attribute or a name attribute, or both.</p>
              </xs:documentation>
            </xs:annotation>
          </xs:assert>
          <xs:assert test="if (empty(@match)) then (empty(@mode) and empty(@priority)) else true()">
            <xs:annotation>
              <xs:documentation>
                <p>An xsl:template element that has no match attribute must have no mode attribute and no priority attribute.</p>
              </xs:documentation>
            </xs:annotation>
          </xs:assert>
          <xs:assert test="not(exists(@visibility) and empty(@name))">
            <xs:annotation>
              <xs:documentation>
                <p>An xsl:template element that has no name attribute must have no visibility attribute</p>
              </xs:documentation>
            </xs:annotation>
          </xs:assert>
          <xs:assert test="if (normalize-space(@visibility) = 'abstract') then empty(* except (xsl:context-item, xsl:param)) else true()">
            <xs:annotation>
              <xs:documentation>
                <p>If the visibility attribute is present with the value abstract then (a) the sequence constructor defining 
                  the template body must be empty: that is, the only permitted children are xsl:context-item and xsl:param</p>
              </xs:documentation>
            </xs:annotation>
          </xs:assert>
          <xs:assert test="not(normalize-space(@visibility) = 'abstract' and exists(@match))">
            <xs:annotation>
              <xs:documentation>
                <p>If the visibility attribute is present with the value abstract then there must be no match attribute.</p>
              </xs:documentation>
            </xs:annotation>
          </xs:assert>
          <xs:assert test="every $e in xsl:param satisfies empty($e/@visibility)">
            <xs:annotation>
              <xs:documentation>
                <p>A parameter for a template must have no <code>visibility</code> attribute.</p>
              </xs:documentation>
            </xs:annotation>
          </xs:assert>
        </xs:extension>
      </xs:complexContent>
    </xs:complexType>
  </xs:element>

  <xs:complexType name="text-element-base-type">
    <xs:simpleContent>
      <xs:restriction base="xsl:versioned-element-type">
        <xs:simpleType>
          <xs:restriction base="xs:string"/>
        </xs:simpleType>
        <xs:anyAttribute namespace="##other" processContents="lax"/>
      </xs:restriction>
    </xs:simpleContent>
  </xs:complexType>

  <!--* first cut (for reference)
<xs:element name="text" substitutionGroup="xsl:instruction">
  <xs:complexType>
    <xs:simpleContent>
      <xs:extension base="xsl:text-element-base-type">
        <xs:attribute name="disable-output-escaping" type="xsl:yes-or-no" default="no"/>
      </xs:extension>
    </xs:simpleContent>
  </xs:complexType>
</xs:element>
*-->

  <xs:complexType name="text-element-type">
    <xs:simpleContent>
      <xs:extension base="xsl:text-element-base-type">
        <xs:attribute name="disable-output-escaping" type="xsl:yes-or-no" default="no"/>
      </xs:extension>
    </xs:simpleContent>
  </xs:complexType>

  <xs:element name="text" substitutionGroup="xsl:instruction" type="xsl:text-element-type"/>


  <xs:complexType name="transform-element-base-type">
    <xs:complexContent>
      <xs:restriction base="xsl:element-only-versioned-element-type">
        <xs:attribute name="version" type="xs:decimal" use="required"/>
        <xs:anyAttribute namespace="##other" processContents="lax"/>
      </xs:restriction>
    </xs:complexContent>
  </xs:complexType>

  <xs:element name="transform">
    <xs:complexType>
      <xs:complexContent>
        <xs:extension base="xsl:transform-element-base-type">
          <xs:sequence>
            <xs:element ref="xsl:import" minOccurs="0" maxOccurs="unbounded"/>
            <xs:choice minOccurs="0" maxOccurs="unbounded">
              <xs:element ref="xsl:declaration"/>
              <xs:any namespace="##other" processContents="lax"/>
              <!-- weaker than XSLT 1.0 -->
            </xs:choice>
          </xs:sequence>
          <xs:attribute name="id" type="xs:ID"/>
          <xs:attribute name="default-validation" type="xsl:validation-strip-or-preserve"
            default="strip"/>
          <xs:attribute name="input-type-annotations" type="xsl:input-type-annotations-type"
            default="unspecified"/>
        </xs:extension>
      </xs:complexContent>
    </xs:complexType>
  </xs:element>

  <xs:element name="try" substitutionGroup="xsl:instruction">
    <xs:complexType>
      <xs:complexContent mixed="true">
        <xs:extension base="xsl:versioned-element-type">
          <xs:sequence>
            <xs:group ref="xsl:sequence-constructor-group" minOccurs="0" maxOccurs="unbounded"/>
            <xs:element ref="xsl:catch" minOccurs="1" maxOccurs="1"/>
            <xs:choice minOccurs="0" maxOccurs="unbounded">
              <xs:element ref="xsl:catch"/>
              <xs:element ref="xsl:fallback"/>
            </xs:choice>
          </xs:sequence>
          <xs:attribute name="select" type="xsl:expression" use="required"/>
        </xs:extension>
      </xs:complexContent>
    </xs:complexType>
  </xs:element>
  
  <xs:element name="use-package">
    <xs:annotation>
        <xs:documentation>
            <p>This element appears as a child of <code>xsl:package</code> and defines a dependency
            of the containing package on another package, identified by URI in the <code>name</code>
            attribute. The <code>package-version</code> attribute indicates which version of the
            library package is required, or may indicate a range of versions.</p>
        </xs:documentation>
    </xs:annotation>
    <xs:complexType>
      <xs:complexContent mixed="false">
        <xs:extension base="xsl:element-only-versioned-element-type">
          <xs:choice minOccurs="0" maxOccurs="unbounded">
            <xs:element ref="xsl:accept"/>
            <xs:element ref="xsl:override"/>
          </xs:choice>
          <xs:attribute name="name" type="xs:anyURI"/>
          <xs:attribute name="package-version" type="xs:string"/>
        </xs:extension>
      </xs:complexContent>
    </xs:complexType>
  </xs:element>

  <xs:element name="value-of" substitutionGroup="xsl:instruction">
    <xs:complexType>
      <xs:complexContent mixed="true">
        <xs:extension base="xsl:sequence-constructor-or-select">
          <xs:attribute name="separator" type="xsl:avt"/>
          <xs:attribute name="disable-output-escaping" type="xsl:yes-or-no" default="no"/>
        </xs:extension>
      </xs:complexContent>
    </xs:complexType>
  </xs:element>

  <xs:element name="variable" substitutionGroup="xsl:declaration xsl:instruction">
    <xs:annotation>
        <xs:documentation>
            <p>Declaration of the <code>xsl:variable</code> element, used both for local
            and global variable bindings.</p>
            <p>This definition takes advantage of the ability in XSD 1.1 for an element
                to belong to more than one substitution group. A global variable
                is a declaration, while a local variable can appear as an instruction
                in a sequence constructor.</p>
        </xs:documentation>
    </xs:annotation>
    <xs:complexType>
      <xs:complexContent mixed="true">
        <xs:extension base="xsl:sequence-constructor-or-select">
          <xs:attribute name="name" type="xsl:EQName" use="required"/>
          <xs:attribute name="as" type="xsl:sequence-type" use="optional"/>
          <xs:attribute name="visibility" type="xsl:visibility-type" use="optional"/>
        </xs:extension>
      </xs:complexContent>
    </xs:complexType>
  </xs:element>

  <xs:element name="when">
    <xs:complexType>
      <xs:complexContent mixed="true">
        <xs:extension base="xsl:sequence-constructor">
          <xs:attribute name="test" type="xsl:expression" use="required"/>
        </xs:extension>
      </xs:complexContent>
    </xs:complexType>
  </xs:element>

  <xs:element name="with-param">
    <xs:complexType>
      <xs:complexContent mixed="true">
        <xs:extension base="xsl:sequence-constructor-or-select">
          <xs:attribute name="name" type="xsl:EQName" use="required"/>
          <xs:attribute name="as" type="xsl:sequence-type"/>
          <xs:attribute name="tunnel" type="xsl:yes-or-no"/>
        </xs:extension>
      </xs:complexContent>
    </xs:complexType>
  </xs:element>

  <!-- ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ -->
  <xs:annotation>
    <xs:documentation> PART C: definition of literal result elements There are three ways to define
      the literal result elements permissible in a stylesheet. (a) do nothing. This allows any
      element to be used as a literal result element, provided it is not in the XSLT namespace (b)
      declare all permitted literal result elements as members of the xsl:literal-result-element
      substitution group (c) redefine the model group xsl:result-elements to accommodate all
      permitted literal result elements. Literal result elements are allowed to take certain
      attributes in the XSLT namespace. These are defined in the attribute group
      literal-result-element-attributes, which can be included in the definition of any literal
      result element. </xs:documentation>
  </xs:annotation>
  <!-- ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ -->

  <xs:element name="literal-result-element" abstract="true" type="xs:anyType"/>

  <xs:attributeGroup name="literal-result-element-attributes">
    <xs:attribute name="default-collation" form="qualified" type="xsl:uri-list"/>
    <xs:attribute name="extension-element-prefixes" form="qualified" type="xsl:prefixes"/>
    <xs:attribute name="exclude-result-prefixes" form="qualified" type="xsl:prefixes"/>
    <xs:attribute name="xpath-default-namespace" form="qualified" type="xs:anyURI"/>
    <xs:attribute name="inherit-namespaces" form="qualified" type="xsl:yes-or-no" default="yes"/>
    <xs:attribute name="use-attribute-sets" form="qualified" type="xsl:EQNames" default=""/>
    <xs:attribute name="use-when" form="qualified" type="xsl:expression"/>
    <xs:attribute name="version" form="qualified" type="xs:decimal"/>
    <xs:attribute name="type" form="qualified" type="xsl:EQName"/>
    <xs:attribute name="validation" form="qualified" type="xsl:validation-type"/>
  </xs:attributeGroup>

  <xs:group name="result-elements">
    <xs:choice>
      <xs:element ref="xsl:literal-result-element"/>
      <xs:any namespace="##other" processContents="lax"/>
      <xs:any namespace="##local" processContents="lax"/>
    </xs:choice>
  </xs:group>


  <!-- ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ -->
  <xs:annotation>
    <xs:documentation> PART D: definitions of simple types used in stylesheet attributes
    </xs:documentation>
  </xs:annotation>
  <!-- ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ -->

  <xs:simpleType name="avt">
    <xs:annotation>
      <xs:documentation> This type is used for all attributes that allow an attribute value
        template. The general rules for the syntax of attribute value templates, and the specific
        rules for each such attribute, are described in the XSLT 2.1 Recommendation.
      </xs:documentation>
    </xs:annotation>
    <xs:restriction base="xs:string"/>
  </xs:simpleType>

  <xs:simpleType name="char">
    <xs:annotation>
      <xs:documentation> A string containing exactly one character. </xs:documentation>
    </xs:annotation>
    <xs:restriction base="xs:string">
      <xs:length value="1"/>
    </xs:restriction>
  </xs:simpleType>
  
   <xs:simpleType name="component-kind-type">
    <xs:annotation>
      <xs:documentation> Describes a kind of component within a package.
      </xs:documentation>
    </xs:annotation>
    <xs:restriction base="xs:token">
      <xs:enumeration value="template"/>
      <xs:enumeration value="function"/>
      <xs:enumeration value="variable"/>
      <xs:enumeration value="attribute-set"/>
      <xs:enumeration value="mode"/>
    </xs:restriction>
  </xs:simpleType>

  <xs:simpleType name="expression">
    <xs:annotation>
      <xs:documentation> An XPath 2.0 expression. </xs:documentation>
    </xs:annotation>
    <xs:restriction base="xs:token">
      <xs:pattern value=".+"/>
    </xs:restriction>
  </xs:simpleType>

  <xs:simpleType name="item-type">
    <xs:annotation>
      <xs:documentation> An XPath 2.1 ItemType</xs:documentation>
    </xs:annotation>
    <xs:restriction base="xs:token">
      <xs:pattern value=".+"/>
    </xs:restriction>
  </xs:simpleType>

  <xs:simpleType name="input-type-annotations-type">
    <xs:annotation>
      <xs:documentation> Describes how type annotations in source documents are handled.
      </xs:documentation>
    </xs:annotation>
    <xs:restriction base="xs:token">
      <xs:enumeration value="preserve"/>
      <xs:enumeration value="strip"/>
      <xs:enumeration value="unspecified"/>
    </xs:restriction>
  </xs:simpleType>

  <xs:simpleType name="level">
    <xs:annotation>
      <xs:documentation> The level attribute of xsl:number: one of single, multiple, or any.
      </xs:documentation>
    </xs:annotation>
    <xs:restriction base="xs:NCName">
      <xs:enumeration value="single"/>
      <xs:enumeration value="multiple"/>
      <xs:enumeration value="any"/>
    </xs:restriction>
  </xs:simpleType>

  <xs:simpleType name="mode">
    <xs:annotation>
      <xs:documentation> The mode attribute of xsl:apply-templates: either a QName, or #current, or
        #default. </xs:documentation>
    </xs:annotation>
    <xs:union memberTypes="xsl:EQName">
      <xs:simpleType>
        <xs:restriction base="xs:token">
          <xs:enumeration value="#default"/>
          <xs:enumeration value="#current"/>
        </xs:restriction>
      </xs:simpleType>
    </xs:union>
  </xs:simpleType>

  <xs:simpleType name="modes">
    <xs:annotation>
      <xs:documentation> The mode attribute of xsl:template: either a list, each member being either
        a QName or #default; or the value #all </xs:documentation>
    </xs:annotation>   
      <xs:union>
        <xs:simpleType>
          <xs:restriction>           
            <xs:simpleType>
              <xs:list>
                <xs:simpleType>
                  <xs:union memberTypes="xsl:EQName">
                    <xs:simpleType>
                      <xs:restriction base="xs:token">
                        <xs:enumeration value="#default"/>
                      </xs:restriction>
                    </xs:simpleType>
                  </xs:union>
                </xs:simpleType>
              </xs:list>
            </xs:simpleType>
            <xs:assertion test="count($value) = count(distinct-values($value))">
              <xs:annotation>
                <xs:documentation>
                  <p>It is a static error if the same token is included more than once in the list.
                  </p>
                </xs:documentation>
              </xs:annotation>
            </xs:assertion>
          </xs:restriction>
        </xs:simpleType>
        <xs:simpleType>
          <xs:restriction base="xs:token">
            <xs:enumeration value="#all"/>
          </xs:restriction>
        </xs:simpleType>
      </xs:union>     
  </xs:simpleType>

  <xs:simpleType name="nametests">
    <xs:annotation>
      <xs:documentation> A list of NameTests, as defined in the XPath 2.0 Recommendation. Each
        NameTest is either a QName, or "*", or "prefix:*", or "*:localname" </xs:documentation>
    </xs:annotation>
    <xs:list>
      <xs:simpleType>
        <xs:union memberTypes="xsl:EQName">
          <xs:simpleType>
            <xs:restriction base="xs:token">
              <xs:enumeration value="*"/>
            </xs:restriction>
          </xs:simpleType>
          <xs:simpleType>
            <xs:restriction base="xs:token">
              <xs:pattern value="\i\c*:\*"/>
              <xs:pattern value="\*:\i\c*"/>
            </xs:restriction>
          </xs:simpleType>
        </xs:union>
      </xs:simpleType>
    </xs:list>
  </xs:simpleType>
  
  <xs:simpleType name="on-multiple-match-type">
    <xs:annotation>
      <xs:documentation> Describes the action to be taken when there are several template rules to match an item in a given mode.
      </xs:documentation>
    </xs:annotation>
    <xs:restriction base="xs:NMTOKEN">
      <xs:enumeration value="use-last"/>
      <xs:enumeration value="fail"/>
    </xs:restriction>
  </xs:simpleType>
  
  <xs:simpleType name="on-no-match-type">
    <xs:annotation>
      <xs:documentation> Describes the action to be taken when there is no template rule to match an item in a given mode.
      </xs:documentation>
    </xs:annotation>
    <xs:restriction base="xs:NMTOKEN">
      <xs:enumeration value="deep-copy"/>
      <xs:enumeration value="shallow-copy"/>
      <xs:enumeration value="deep-skip"/>
      <xs:enumeration value="shallow-skip"/>
      <xs:enumeration value="text-only-copy"/>
      <xs:enumeration value="fail"/>
    </xs:restriction>
  </xs:simpleType>

  <xs:simpleType name="prefixes">
    <xs:list itemType="xs:NCName"/>
  </xs:simpleType>

  <xs:simpleType name="prefix-list-or-all">
    <xs:union memberTypes="xsl:prefix-list">
      <xs:simpleType>
        <xs:restriction base="xs:token">
          <xs:enumeration value="#all"/>
        </xs:restriction>
      </xs:simpleType>
    </xs:union>
  </xs:simpleType>

  <xs:simpleType name="prefix-list">
    <xs:list itemType="xsl:prefix-or-default"/>
  </xs:simpleType>

  <xs:simpleType name="method">
    <xs:annotation>
      <xs:documentation> The method attribute of xsl:output: Either one of the recognized names
        "xml", "xhtml", "html", "text", or a QName that must include a prefix. </xs:documentation>
    </xs:annotation>
    <xs:union>
      <xs:simpleType>
        <xs:restriction base="xs:NCName">
          <xs:enumeration value="xml"/>
          <xs:enumeration value="xhtml"/>
          <xs:enumeration value="html"/>
          <xs:enumeration value="text"/>
        </xs:restriction>
      </xs:simpleType>
      <xs:simpleType>
        <xs:restriction base="xsl:EQName">
          <xs:pattern value="\c*:\c*"/>
        </xs:restriction>
      </xs:simpleType>
    </xs:union>
  </xs:simpleType>

  <xs:simpleType name="pattern">
    <xs:annotation>
      <xs:documentation> A match pattern as defined in the XSLT 2.1 Recommendation. The syntax for
        patterns is a restricted form of the syntax for XPath 2.0 expressions. Change since XSLT
        2.0: Patterns may now match any item (not only nodes) </xs:documentation>
    </xs:annotation>
    <xs:restriction base="xsl:expression"/>
  </xs:simpleType>

  <xs:simpleType name="prefix-or-default">
    <xs:annotation>
      <xs:documentation> Either a namespace prefix, or #default. Used in the xsl:namespace-alias
        element. </xs:documentation>
    </xs:annotation>
    <xs:union memberTypes="xs:NCName">
      <xs:simpleType>
        <xs:restriction base="xs:token">
          <xs:enumeration value="#default"/>
        </xs:restriction>
      </xs:simpleType>
    </xs:union>
  </xs:simpleType>

  <xs:simpleType name="EQNames">
    <xs:annotation>
      <xs:documentation> A list of QNames. Used in the [xsl:]use-attribute-sets attribute of various
        elements, and in the cdata-section-elements attribute of xsl:output </xs:documentation>
    </xs:annotation>
    <xs:list itemType="xsl:EQName"/>
  </xs:simpleType>

  <xs:simpleType name="EQName">
    <xs:annotation>
      <xs:documentation> 
        <p>An extended QName. This schema does not use the built-in type xs:QName, but rather
        defines its own QName type. This may be either a local name, or a prefixed QName, or a name written
        using the extended QName notation Q{uri}local</p>
        <p>Although xs:QName would define the correct validation on these
        attributes, a schema processor would expand unprefixed QNames incorrectly when constructing
        the PSVI, because (as defined in XML Schema errata) an unprefixed xs:QName is assumed to be
        in the default namespace, which is not the correct assumption for XSLT. The data type is therefore
        defined as a union of NCName and QName, so that an unprefixed name will be validated as an 
        NCName and will therefore not be treated as having the semantics of an unprefixed xs:QName. </p>
      </xs:documentation>
    </xs:annotation>
    <xs:union memberTypes="xs:NCName xs:QName">
      <xs:simpleType>
        <xs:restriction base="xs:string">
          <xs:pattern value="Q\{.*\}\i\c+"/>
        </xs:restriction>
      </xs:simpleType>
    </xs:union>
  </xs:simpleType>

  <xs:simpleType name="sequence-type">
    <xs:annotation>
      <xs:documentation> The description of a data type, conforming to the SequenceType production
        defined in the XPath 2.0 Recommendation </xs:documentation>
    </xs:annotation>
    <xs:restriction base="xs:token">
      <xs:pattern value=".+"/>
    </xs:restriction>
  </xs:simpleType>
  
  <xs:simpleType name="typed-type">
    <xs:annotation>
      <xs:documentation> Describes whether a mode is designed to match typed or untyped nodes.
      </xs:documentation>
    </xs:annotation>
    <xs:restriction base="xs:NMTOKEN">
      <xs:enumeration value="yes"/>
      <xs:enumeration value="no"/>
      <xs:enumeration value="strict"/>
      <xs:enumeration value="lax"/>
      <xs:enumeration value="unspecified"/>
    </xs:restriction>
  </xs:simpleType>

  <xs:simpleType name="uri-list">
    <xs:list itemType="xs:anyURI"/>
  </xs:simpleType>

  <xs:simpleType name="validation-strip-or-preserve">
    <xs:annotation>
      <xs:documentation> Describes different ways of type-annotating an element or attribute.
      </xs:documentation>
    </xs:annotation>
    <xs:restriction base="xsl:validation-type">
      <xs:enumeration value="preserve"/>
      <xs:enumeration value="strip"/>
    </xs:restriction>
  </xs:simpleType>

  <xs:simpleType name="validation-type">
    <xs:annotation>
      <xs:documentation> Describes different ways of type-annotating an element or attribute.
      </xs:documentation>
    </xs:annotation>
    <xs:restriction base="xs:token">
      <xs:enumeration value="strict"/>
      <xs:enumeration value="lax"/>
      <xs:enumeration value="preserve"/>
      <xs:enumeration value="strip"/>
    </xs:restriction>
  </xs:simpleType>
  
  <xs:simpleType name="visibility-type">
    <xs:annotation>
      <xs:documentation> Describes the visibility of a component within a package.
      </xs:documentation>
    </xs:annotation>
    <xs:restriction base="xs:NMTOKEN">
      <xs:enumeration value="public"/>
      <xs:enumeration value="private"/>
      <xs:enumeration value="final"/>
      <xs:enumeration value="abstract"/>
      <xs:enumeration value="hidden"/>
    </xs:restriction>
  </xs:simpleType>
  
  <xs:simpleType name="visibility-not-hidden-type">
    <xs:annotation>
      <xs:documentation> Describes the visibility of a component within a package.
      </xs:documentation>
    </xs:annotation>
    <xs:restriction base="xsl:visibility-type">
      <xs:enumeration value="public"/>
      <xs:enumeration value="private"/>
      <xs:enumeration value="final"/>
      <xs:enumeration value="abstract"/>
    </xs:restriction>
  </xs:simpleType>

  <xs:simpleType name="yes-or-no">
    <xs:annotation>
      <xs:documentation> One of the values "yes" or "no". </xs:documentation>
    </xs:annotation>
    <xs:restriction base="xs:token">
      <xs:enumeration value="yes"/>
      <xs:enumeration value="no"/>
    </xs:restriction>
  </xs:simpleType>

  <xs:simpleType name="yes-or-no-or-omit">
    <xs:annotation>
      <xs:documentation> One of the values "yes" or "no" or "omit". </xs:documentation>
    </xs:annotation>
    <xs:restriction base="xs:token">
      <xs:enumeration value="yes"/>
      <xs:enumeration value="no"/>
      <xs:enumeration value="omit"/>
    </xs:restriction>
  </xs:simpleType>

</xs:schema>

H Acknowledgements (Non-Normative)

This specification was developed and approved for publication by the W3C XSL Working Group (WG). WG approval of this specification does not necessarily imply that all WG members voted for its approval.

The chair of the XSL WG is Sharon Adler. The members of the XSL WG who are engaged in creation of the XSLT 3.0 specification are:

Sharon Adler

Invited expert

Anders Berglund

Invited expert

Oliver Becker

Invited expert

Carine Bournez

W3C

Abel Braaksma

Invited expert

Nikolay Fiykov

Nokia

Sandy Gao

IBM

Florent Georges

Invited expert

Michael Kay

Invited expert

Jirka Kosek

Invited expert

Dimitre Novatchev

Microsoft

Dmitriy Shabanov

Invited expert

C. Michael Sperberg-McQueen

Invited expert

Mohamed Zergaoui

Innovimax

Henry Zongaro

IBM

The Working Group wishes to acknowledge the pioneering work of the developers of STX (see [STX]) which has formed an important intellectual input to the design of XSLT 3.0 and has demonstrated the feasibility of creating a streaming transformation language based on the core XSLT concept of recursive descent of the source tree using rule-based templates. In particular Petr Cimprich played in an important role during the process of formulating XSLT 3.0 streaming requirements.

The SVG diagrams in this specification are drawn using GraphViz from AT&T Research, in conjunction with the DotML markup language developed by Martin Loetzsch.

I Summary of Open Issues (Non-Normative)

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.

Issue 2 (package-xslt-version):

Need to define forwards and backwards compatibility rules for package/@xsl:version

Issue 3 (cyclic-package-dependencies):

The restriction that prevents cyclic package dependencies is unfortunate, it would be nice if we can find a way of dispensing with it. It's a consequence of the decision that each use of a package effectively creates a new occurrence of all its components.

Issue 4 (use-package-xquery):

The WG intends to add an option to xsl:use-package to allow an XQuery library module to be used in the same way as a package written in XSLT. This requires defining a mapping of XQuery concepts to XSLT concepts (for example, XQuery external variables equate to XSLT stylesheet parameters). This is likely to be an optional conformance feature.

Issue 5 (normative-evaluation-context):

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

Issue 6 (error-XTRE0540):

This error is no longer recoverable; should the error code change?

Issue 7 (try-catch-output-buffering):

The rules appear inconsistent: if the processor is obliged to buffer "immediate" output from the xsl:try element before sending it the serializer, should not the same requirement apply also to xsl:result-document (rule 5)? And if output has to be buffered, is rule 7 appropriate, allowing serialization errors to be detected "on the fly"?

Issue 8 (function-override):

The setting <xsl:function override="yes"> was introduced in XSLT 2.0 as a solution to use cases involving extension functions. As currently defined, it does not license overriding of a function that is present in a library package (just as it does not affect the rules for import precedence). This could prove to be confusing.

Issue 9 (evaluate-optional-feature):

The Working Group has not yet decided whether xsl:evaluate will be an optional feature of the language, or whether all implementations will be required to provide it.

Issue 10 (refactor-format-integer):

The functionality described here has been encapsulated in a new function, format-integerFO30. The specification can be simplified by referring to the specification of that function.

Issue 11 (assuming-assertions-true):

The idea that assertions can be used as optimization hints, and assumed true without checking, requires further thought and discussion. Feedback is welcome.

Issue 12 (streaming-conformance):

We need to define the conformance rules for streaming processors.

J Changes since XSLT 2.0 (Non-Normative)

J.1 Changes in this Specification

  1. A stylesheet may now consist of multiple packages. The language specification for packages has been designed with a view to allowing packages to be compiled independently of each other. The specification provides control over the interface offered by a package to other packages; in particular it allows functions, variables, named templates and other components to be declared as public, private, final, or abstract.

  2. A new xsl:iterate instruction is added. This allows iterative processing of a sequence, with the ability for the processing of one item to depend on the results of processing of previous items, and with the ability to terminate the iteration before all the items in the sequence have been processed.

  3. A new xsl:mode declaration is added, together with the ability for a stylesheet module to declare a default mode. A mode may be declared to be streamable, and rules are given that constrain what the template rules in a streamable mode can do. A default mode can be declared for a stylesheet module, making it easier to reuse existing stylesheet modules to construct a composite stylesheet. The xsl:mode declaration may contain an xsl:context-item element to declare the expected type of the initial context item when this mode is the initial mode.

  4. An xsl:mode declaration may indicate that the template rules in a given mode are designed to process typed (schema-validated) nodes only, or untyped nodes only. It may also indicate that element names appearing in match patterns for the mode are only to match elements in the source document that have been validated against the corresponding element declarations in the schema.

  5. A new instruction xsl:stream is provided, to read and process an input document using streaming

  6. A new instruction xsl:merge is provided. This allows several input sequences to be merged into a single output sequence, based on the value of a merge key.

  7. A new top-level declaration xsl:accumulator is introduced. An accumulator represents information about a node in a document that can be computed during a streamed pass over the document, starting at the start and ending at that node.

  8. New functions copy-of and snapshot are provided, to enable streaming applications to operate in "windowing" mode, where the input document is divided into a sequence of small subtrees processed one at a time.

  9. A new xsl:try instruction is provided, to allow recovery from dynamic errors.

  10. A new xsl:evaluate instruction is provided, to allow evaluation of XPath expressions constructed dynamically from strings, or read from a source document.

  11. A new xsl:fork instruction is introduced to allow multiple results to be computed during a single pass of a streamed input document.

  12. The syntax of patterns has been generalized. Patterns may now match any item (not only nodes). In consequence, xsl:apply-templates can now process sequences of atomic values as well as nodes, and xsl:for-each-group with the group-starting-with and group-ending-with options can also process atomic sequences. As a further consequence, the initial context item supplied when initiating a transformation is no longer required to be a node.

  13. A new datatype, called a map, has been introduced, together with supporting functions, operators, and type syntax. Maps allow more complex data structures to be created than is possible using atomic values and nodes alone. This has particular applications to streamed processing: since a streamed application can visit each node of its primary input document only once, it often needs more advanced data structures to retain what it has already seen in the document.

  14. New functions are available to import and export data in JSON format.

  15. The xsl:copy instruction now has a select attribute, which is convenient when it is used inside a function where there is no context item.

  16. A basic XSLT Processor now recognizes all the built-in types defined in XML Schema.

  17. A basic XSLT Processor will now accept the attribute validation="lax" and interpret it in the same way as a schema-aware processor when there is no schema component available to perform the validation.

  18. Some functions, including generate-idFO30, format-dateFO30, format-dateTimeFO30, format-numberFO30, format-timeFO30, and unparsed-textFO30 have been moved from this specification to the core Functions and Operators specification, to make them available in other host languages.

  19. The rules for handling conflicts between xsl:strip-space and xsl:preserve-space have changed. A conflict that can be detected statically is now signaled as a static error; a run-time conflict between two declarations having the same precedence and priority is now resolved by taking whichever comes last in declaration order.

  20. A template may contain an xsl:context-item element to declare the required type of the context item when the template is called.

  21. Composite keys are supported in xsl:key and in xsl:for-each-group.

  22. An xsl:assert instruction is introduced.

  23. An [xsl:]on-empty attribute is provided for xsl:element, xsl:copy, xsl:attribute, and literal result elements, to control their behavior when the content of the constructed node would otherwise be empty.

J.2 Changes in Other Related specifications

A number of changes affecting XSLT 2.0 have been made in other related specifications. Some of the more significant changes are as follows:

  1. A number of new functions have been defined whose aim is to facilitate streaming. These include unparsed-text-linesFO30, innermostFO30, outermostFO30.

  2. XPath 3.0 supports a subset of the let expression from XQuery.

  3. XPath 3.0 supports function items as first-class values (so that functions can be passed as parameters to other functions.)

  4. XPath 3.0 supports a new syntax for writing expanded names using the namespace URI and local part only, avoiding the need to create a static context that binds namespace prefixes. This is intended to be particularly useful when XPath expressions are software-generated. Complementing this, a new function pathFO30 is available to generate a (namespace-context-independent) path to any node that can subsequently be evaluated using the xsl:evaluate instruction, or otherwise.

K Changes since the Working Draft of 11 May 2010 (Non-Normative)

This section outlines the most significant changes since the Working Draft published on 11 May 2010.

  1. The version number has been changed from 2.1 to 3.0.

  2. Support for packages is introduced.

  3. The rules for assessing streamability have been greatly simplified. The guaranteed-streamable subset of the language is now smaller, but easier to explain and understand. Implementations remain free to stream a larger subset of the language if they choose.

  4. There are minor changes to the syntax and semantics of xsl:merge based on implementation feedback.

  5. Accumulators are introduced.

  6. The xsl:fork instruction is simplified.

  7. The [xsl:]on-empty attribute is introduced for xsl:element, xsl:copy, xsl:attribute, and literal result elements.

  8. The current grouping key and current group established by the xsl:for-each-group instruction can be bound to variables with static scope, and must be used in this way if streaming is required.

  9. Added the xsl:assert instruction.

  10. An empty xsl:value-of instruction with no select attribute is now permitted; its effect is to construct a zero-length text node.

L Incompatibilities with XSLT 2.0 (Non-Normative)

This section lists all known incompatibilities with XSLT 2.0, that is, situations where a stylesheet that is error-free according to the XSLT 2.0 specification and where all elements have an effective version of 2.0 or less, will produce different results depending on whether it is run under an XSLT 2.0 processor or an XSLT 3.0 processor.

  1. XSLT 2.0 gave implementations freedom what to do when a node selected by xsl:apply-templates matched more than one template rule. XSLT 3.0 is more prescriptive in this situation. The behavior prescribed in XSLT 3.0 (selecting the template rule that is last in declaration order) is compatible with the action of some XSLT 2.0 processors but not necessarily others.

  2. It is now a static error if the same NameTest appears in both an xsl:strip-space and an xsl:preserve-space declaration with the same precedence and priority. Previously this was a dynamic error, and processors were allowed to recover from the error.

  3. The current group and current grouping key are now absent rather than empty when not in use, which means that attempting to refer to them in this state gives a dynamic error.

  4. As a consequence of functions such as format-dateFO30 moving from this specification to [Functions and Operators], error codes associated with these functions have changed.