W3C

XSL Transformations (XSLT) Version 3.0

W3C Candidate Recommendation 19 November 2015

This version:
http://www.w3.org/TR/2015/CR-xslt-30-20151119/
Latest version:
http://www.w3.org/TR/xslt-30/
Previous versions:
http://www.w3.org/TR/2014/WD-xslt-30-20141002/

http://www.w3.org/TR/2012/WD-xslt-30-20131212/

http://www.w3.org/TR/2012/WD-xslt-30-20120710/

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

See also translations.

The following associated resources are available:


Abstract

This specification defines the syntax and semantics of XSLT 3.0, a language designed primarily 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 [XDM 3.0], and it uses the library of functions and operators defined in [Functions and Operators 3.0]. XPath 3.0 and the underlying function library introduce a number of enhancements, for example the availability of higher-order functions.

As an implementer option, XSLT 3.0 can also be used with XPath 3.1. All XSLT 3.0 processors provide maps, an addition to the data model which is specified (identically) in both XSLT 3.0 and XPath 3.1. Other features from XPath 3.1, such as arrays, and new functions such as random-number-generatorFO31 and sortFO31, are available in XSLT 3.0 stylesheets only if the implementer chooses to support XPath 3.1.

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]. Again, the new serialization capabilities of [XSLT and XQuery Serialization 3.1] are available at the implementer’s option.

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 document is governed by the 1 September 2015 W3C Process Document.

This is a Candidate Recommendation as described in the process document. It has been developed by the W3C XSLT Working Group, which is part of the XML Activity. Comments on this document will be formally accepted until 31 March 2016. The Working Group expects to advance this specification first to Proposed Recommendation and then to Recommendation status.

In publishing a Candidate Recommendation, the Working Group invites interested parties to implement the specification and to submit feedback from their implementation experience, in the form of comments on the specification, reports of test results, or otherwise. The Working Group intends to proceed to the next stage in the process, namely Proposed Recommendation, as soon as sufficient implementation experience has been generated. This will include evidence of at least two independent and substantially complete implementations of the basic XSLT processor conformance level as well as the optional streaming feature, and at least one substantially complete implementation of other optional features defined in 27 Conformance.

This specification has been developed in conjunction with [XPath 3.0] and other documents that underpin both XSLT and XQuery. XSLT 3.0 requires support for XPath 3.0 augmented by a selection of features from XPath 3.1 which are described in 21 Maps and 22 Processing JSON Data. XSLT 3.0 in addition allows a processor to support the whole of XPath 3.1, in which case it must do so as described in 27.7 XPath 3.1 Feature. In the event that future versions of XPath are defined beyond XPath 3.1, this specification allows XSLT 3.0 processors to provide support for such versions, but leaves it implementation-defined how this is done. References in this document to XPath and related specifications are by default to the 3.0 versions, but such references should be treated as version-agnostic unless the relevant prose indicates otherwise.

This document specifies extensions to the XDM 3.0 data model, to the XPath 3.0 language syntax, and to the XPath 3.0 function library to underpin the introduction of maps, which have been found necessary to support some XSLT streaming use cases, to enable XSLT to process JSON data, and to make many other processing tasks easier. This has involved extensive consultation with the XQuery Working Group (which has joint responsibility for XDM and XPath), and these extensions have been incorporated into the current drafts of XDM 3.1 and XPath 3.1.

Changes since the previous Recommendation are listed in J Changes since XSLT 2.0. The only incompatibilities with XSLT 2.0 relate to the way in which certain error conditions are handled: the details are given in L Incompatibilities with XSLT 2.0.

The second Last Call Working Draft was published on 2 October 2014. Some 147 formal comments were received and most of these resulted in changes to the specification. The changes are listed at K Changes since the Last Call Working Draft of 2 October 2014. The change-marked version of this publication links each entry in the change list to the specific places in the text that changed as a result. Some of the changes are substantive. Many are concerned with the detailed rules for streamability of stylesheets. Most of the changes result from practical experience in implementing product features and writing test cases; some of them result from user experience with early implementations.

Note:

At a late stage during the development of this specification, the W3C Internationalization Working Group (I18N) requested that the XSLT WG consider closer alignment of some of the language features (for sorting strings and for formatting numbers and dates) with various external specifications. The XSLT WG declined to make any substantial changes in this area on the grounds that the work fell outside the agreed charter and requirements for XSLT 3.0; that the WG lacked resources; and that such changes would result in significant delays. The Internationalization Working Group accepted this decision but requested that it be highlighted for the attention of W3C reviewers.

Certain features in this specification are designated "at risk". These features may be removed from the specification before advancing to Proposed Recommendation status if feedback on these features from implementers or users is negative. These features are:

  1. Streamable stylesheet functions: see 19.8.5 Classifying Stylesheet Functions.

  2. Streamability of the xsl:for-each-group instruction.

  3. The requirement for every processor to report any departure from guaranteed streamability, even in cases where the processor is able to use streaming anyway.

    Note:

    It is important for interoperability that users should have access to tools that assess a stylesheet against the rules for guaranteed streamability; but it is not clear that every conformant processor needs to include such tools.

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

A public test suite for XSLT 3.0 is under continuous development. The test suite currently contains nearly 11,000 tests, of which over half depend on new XSLT 3.0 features. Implementers and others are encouraged to run these tests, to submit comments and contributions, and to report their results. W3C will maintain confidentiality and anonymity of submitted results if requested. Test results are useful even if they demonstrate only partial implementation, and the implementation under test does not need to be generally available to the public at the time of submission, or indeed later. The test suite is available at https://dvcs.w3.org/hg/xslt30-test/.

Publication as a Candidate Recommendation 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.

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.3.1 Information needed for Static Analysis
        2.3.2 Priming a Stylesheet
        2.3.3 Apply-Templates Invocation
        2.3.4 Call-Template Invocation
        2.3.5 Function Call Invocation
        2.3.6 Post-processing the Raw Result
    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 Streamed Validation
    2.12 Error Handling
3 Stylesheet Structure
    3.1 XSLT Namespace
    3.2 Extension Attributes
    3.3 XSLT Media Type
    3.4 Standard Attributes
    3.5 Packages
        3.5.1 Versions of a Package
        3.5.2 Dependencies between Packages
        3.5.3 Named Components in Packages
            3.5.3.1 Visibility of Components
            3.5.3.2 Accepting Components
            3.5.3.3 Overriding Named Components from a Used Package
            3.5.3.4 Referring to Overridden Components
            3.5.3.5 Binding References to Components
            3.5.3.6 Dynamic References to Components
        3.5.4 Overriding Template Rules from a Used Package
            3.5.4.1 Requiring Explicit Mode Declarations
        3.5.5 Declarations Local to a Package
        3.5.6 Declaring the Global Context Item
        3.5.7 Worked Example of a Library Package
            3.5.7.1 Default Functionality of the CSV Package
            3.5.7.2 Package Structure
            3.5.7.3 The csv:parse Function and its User-customization Hooks
            3.5.7.4 Breaking the Input into Lines
            3.5.7.5 Pre-processing the Lines
            3.5.7.6 The Mode csv:parse-line
            3.5.7.7 Mode csv:parse-field
            3.5.7.8 The csv:quote Variable
            3.5.7.9 The csv:preprocess-field Function
            3.5.7.10 The Mode csv:post-process
            3.5.7.11 Overriding the Default Behavior
    3.6 Stylesheet Modules
    3.7 Stylesheet Element
        3.7.1 The default-collation Attribute
        3.7.2 The default-mode Attribute
        3.7.3 User-defined Data Elements
    3.8 Simplified Stylesheet Modules
    3.9 Backwards Compatible Processing
        3.9.1 XSLT 1.0 Compatibility Mode
        3.9.2 XSLT 2.0 Compatibility Mode
    3.10 Forwards Compatible Processing
    3.11 Combining Stylesheet Modules
        3.11.1 Locating Stylesheet Modules
        3.11.2 Stylesheet Inclusion
        3.11.3 Stylesheet Import
    3.12 Embedded Stylesheet Modules
    3.13 Stylesheet Preprocessing
        3.13.1 Conditional Element Inclusion
        3.13.2 Shadow Attributes
    3.14 Built-in Types
    3.15 Importing Schema Components
4 Data Model
    4.1 XML Versions
    4.2 XDM versions
    4.3 Stripping Whitespace from the Stylesheet
    4.4 Stripping Type Annotations from a Source Tree
    4.5 Stripping Whitespace from a Source Tree
    4.6 Attribute Types and DTD Validation
    4.7 Data Model for Streaming
        4.7.1 Streamed Documents
        4.7.2 Other Data Structures
    4.8 Limits
    4.9 Disable Output Escaping
5 Features of the XSLT Language
    5.1 Names
        5.1.1 Qualified Names
        5.1.2 Unprefixed Lexical QNames in Expressions and Patterns
        5.1.3 Reserved Namespaces
    5.2 Expressions
    5.3 The Static and Dynamic Context
        5.3.1 Initializing the Static Context
        5.3.2 Additional Static Context Components used by XSLT
        5.3.3 Initializing the Dynamic Context
            5.3.3.1 Maintaining Position: the Focus
            5.3.3.2 Other Components of the XPath Dynamic Context
        5.3.4 Additional Dynamic Context Components used by XSLT
    5.4 Defining a Decimal Format
    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 Value Templates
        5.6.1 Attribute Value Templates
        5.6.2 Text 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 Using Modes
        6.6.3 Declaring the Type of Nodes Processed by a Mode
        6.6.4 Streamable Templates
    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 Recovery of Result Trees
        8.3.2 Try/Catch Examples
    8.4 Conditional Content Construction
        8.4.1 The xsl:where-populated instruction
        8.4.2 The xsl:on-empty instruction
        8.4.3 The xsl:on-non-empty instruction
        8.4.4 Evaluating xsl:on-empty and xsl:on-non-empty Instructions
        8.4.5 A More Complex Example
9 Variables and Parameters
    9.1 Variables
    9.2 Parameters
        9.2.1 The Required Type of a Parameter
        9.2.2 Default Values of Parameters
    9.3 Values of Variables and Parameters
    9.4 Creating Implicit Document Nodes
    9.5 Global Variables and Parameters
    9.6 Static Variables and Parameters
    9.7 Static Expressions
    9.8 Local Variables and Parameters
    9.9 Scope of Variables
    9.10 Setting Parameter Values
    9.11 Circular Definitions
10 Callable Components
    10.1 Named Templates
        10.1.1 Declaring the Context Item for a Template
        10.1.2 Passing Parameters to Named Templates
        10.1.3 Tunnel Parameters
    10.2 Named Attribute Sets
        10.2.1 Using Attribute Sets
        10.2.2 Visibility of Attribute Sets
        10.2.3 Streamability of Attribute Sets
        10.2.4 Evaluating Attribute Sets
        10.2.5 Attribute Sets: Examples
    10.3 Stylesheet Functions
        10.3.1 Function Name and Arity
        10.3.2 Arguments
        10.3.3 Function Result
        10.3.4 Visibility and Overriding of Functions
        10.3.5 Streamability of Stylesheet Functions
        10.3.6 Dynamic Access to Functions
        10.3.7 Determinism of Functions
        10.3.8 Memoization
        10.3.9 Examples of Stylesheet Functions
    10.4 Dynamic XPath Evaluation
        10.4.1 Static context for the target expression
        10.4.2 Dynamic context for the target expression
        10.4.3 The effect of the xsl:evaluate instruction
        10.4.4 xsl:evaluate as an optional feature
        10.4.5 Examples of xsl:evaluate
11 Creating Nodes and Sequences
    11.1 Literal Result Elements
        11.1.1 Setting the Type Annotation for Literal Result Elements
        11.1.2 Attribute Nodes for Literal Result Elements
        11.1.3 Namespace Nodes for Literal Result Elements
        11.1.4 Namespace Aliasing
    11.2 Creating Element Nodes Using xsl:element
        11.2.1 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.3 Creating Attribute Nodes Using xsl:attribute
        11.3.1 Setting the Type Annotation for a Constructed Attribute Node
    11.4 Creating Text Nodes
        11.4.1 Literal Text Nodes
        11.4.2 Creating Text Nodes Using xsl:text
        11.4.3 Generating Text with xsl:value-of
    11.5 Creating Document Nodes
    11.6 Creating Processing Instructions
    11.7 Creating Namespace Nodes
    11.8 Creating Comments
    11.9 Copying Nodes
        11.9.1 Shallow Copy
        11.9.2 Deep Copy
    11.10 Constructing Sequences
12 Numbering
    12.1 The start-at Attribute
    12.2 Formatting a Supplied Number
    12.3 Numbering based on Position in a Document
    12.4 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
    13.4 The Unicode Collation Algorithm
14 Grouping
    14.1 The xsl:for-each-group Element
    14.2 Accessing Information about the Current Group Value
        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 Current Merge Group and Key
        15.6.1 fn:current-merge-group
        15.6.2 fn:current-merge-key
    15.7 The xsl:merge-action Element
    15.8 Examples of xsl:merge
16 Splitting
    16.1 The xsl:fork Instruction
    16.2 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 Streaming
    18.1 The xsl:stream Instruction
        18.1.1 Validation of Streamed Documents
        18.1.2 Examples of xsl:stream
        18.1.3 fn:stream-available
    18.2 Accumulators
        18.2.1 Declaring an Accumulator
        18.2.2 Applicability of Accumulators
        18.2.3 Informal Model for Accumulators
        18.2.4 Formal Model for Accumulators
        18.2.5 fn:accumulator-before
        18.2.6 fn:accumulator-after
        18.2.7 Importing of Accumulators
        18.2.8 Streamability of Accumulators
        18.2.9 Copying Accumulator Values
        18.2.10 Examples of Accumulators
    18.3 fn:copy-of
    18.4 fn:snapshot
19 Streamability
    19.1 Determining the Static Type of a Construct
    19.2 Determining the Context Item Type
    19.3 Operand Roles
        19.3.1 Examples showing the Effect of Operand Usage
    19.4 Determining the Posture of a Construct
    19.5 Determining the Context Posture
    19.6 The Sweep of a Construct
    19.7 Grounded Consuming Constructs
    19.8 Classifying Constructs
        19.8.1 General Rules for Streamability
        19.8.2 Examples of the General Streamability Rules
        19.8.3 Classifying Sequence Constructors
        19.8.4 Classifying Instructions
            19.8.4.1 Streamability of Literal Result Elements
            19.8.4.2 Streamability of extension instructions
            19.8.4.3 Streamability of xsl:analyze-string
            19.8.4.4 Streamability of xsl:apply-imports
            19.8.4.5 Streamability of xsl:apply-templates
            19.8.4.6 Streamability of xsl:assert
            19.8.4.7 Streamability of xsl:attribute
            19.8.4.8 Streamability of xsl:break
            19.8.4.9 Streamability of xsl:call-template
            19.8.4.10 Streamability of xsl:choose
            19.8.4.11 Streamability of xsl:comment
            19.8.4.12 Streamability of xsl:copy
            19.8.4.13 Streamability of xsl:copy-of
            19.8.4.14 Streamability of xsl:document
            19.8.4.15 Streamability of xsl:element
            19.8.4.16 Streamability of xsl:evaluate
            19.8.4.17 Streamability of xsl:fallback
            19.8.4.18 Streamability of xsl:for-each
            19.8.4.19 Streamability of xsl:for-each-group
            19.8.4.20 Streamability of xsl:fork
            19.8.4.21 Streamability of xsl:if
            19.8.4.22 Streamability of xsl:iterate
            19.8.4.23 Streamability of xsl:map
            19.8.4.24 Streamability of xsl:map-entry
            19.8.4.25 Streamability of xsl:merge
            19.8.4.26 Streamability of xsl:message
            19.8.4.27 Streamability of xsl:namespace
            19.8.4.28 Streamability of xsl:next-iteration
            19.8.4.29 Streamability of xsl:next-match
            19.8.4.30 Streamability of xsl:number
            19.8.4.31 Streamability of xsl:on-empty
            19.8.4.32 Streamability of xsl:on-non-empty
            19.8.4.33 Streamability of xsl:perform-sort
            19.8.4.34 Streamability of xsl:processing-instruction
            19.8.4.35 Streamability of xsl:result-document
            19.8.4.36 Streamability of xsl:sequence
            19.8.4.37 Streamability of xsl:stream
            19.8.4.38 Streamability of xsl:text
            19.8.4.39 Streamability of xsl:try
            19.8.4.40 Streamability of xsl:value-of
            19.8.4.41 Streamability of xsl:variable
            19.8.4.42 Streamability of xsl:where-populated
        19.8.5 Classifying Stylesheet Functions
            19.8.5.1 Streamability Category: unclassified
            19.8.5.2 Streamability Category: absorbing
            19.8.5.3 Streamability Category: inspection
            19.8.5.4 Streamability Category: filter
            19.8.5.5 Streamability Category: shallow-descent
            19.8.5.6 Streamability Category: deep-descent
            19.8.5.7 Streamability Category: ascent
        19.8.6 Classifying Attribute Sets
        19.8.7 Classifying Value Templates
        19.8.8 Classifying Expressions
            19.8.8.1 Streamability of for Expressions
            19.8.8.2 Streamability of Quantified Expressions
            19.8.8.3 Streamability of if expressions
            19.8.8.4 Streamability of union, intersect, and except Expressions
            19.8.8.5 Streamability of instance of Expressions
            19.8.8.6 Streamability of Simple Mapping Expressions
            19.8.8.7 Streamability of Path Expressions
            19.8.8.8 Streamability of Axis Steps
            19.8.8.9 Streamability of Filter Expressions
            19.8.8.10 Streamability of Dynamic Function Calls
            19.8.8.11 Streamability of Variable References
            19.8.8.12 Streamability of the Context Item Expression
            19.8.8.13 Streamability of Static Function Calls
            19.8.8.14 Streamability of Named Function References
            19.8.8.15 Streamability of Inline Function Declarations
            19.8.8.16 Streamability of Map Constructors
            19.8.8.17 Streamability of Lookup Expressions
        19.8.9 Classifying Calls to Built-In Functions
            19.8.9.1 Streamability of the accumulator-after Function
            19.8.9.2 Streamability of the accumulator-before Function
            19.8.9.3 Streamability of the current Function
            19.8.9.4 Streamability of the current-group Function
            19.8.9.5 Streamability of the current-grouping-key Function
            19.8.9.6 Streamability of the current-merge-group Function
            19.8.9.7 Streamability of the current-merge-key Function
            19.8.9.8 Streamability of the fold-left Function
            19.8.9.9 Streamability of the fold-right Function
            19.8.9.10 Streamability of the for-each Function
            19.8.9.11 Streamability of the for-each-pair Function
            19.8.9.12 Streamability of the function-lookup Function
            19.8.9.13 Streamability of the innermost Function
            19.8.9.14 Streamability of the last Function
            19.8.9.15 Streamability of the outermost Function
            19.8.9.16 Streamability of the position Function
            19.8.9.17 Streamability of the reverse Function
            19.8.9.18 Streamability of the root Function
        19.8.10 Classifying Patterns
    19.9 Examples of Streamability Analysis
    19.10 Streamability Guarantees
20 Additional Functions
    20.1 fn:document
    20.2 Keys
        20.2.1 The xsl:key Declaration
        20.2.2 fn:key
    20.3 Miscellaneous Additional Functions
        20.3.1 fn:current
        20.3.2 fn:unparsed-entity-uri
        20.3.3 fn:unparsed-entity-public-id
        20.3.4 fn:system-property
        20.3.5 fn:available-system-properties
21 Maps
    21.1 The Type of a Map
    21.2 Functions that Operate on Maps
        21.2.1 op:same-key
        21.2.2 map:merge
        21.2.3 map:size
        21.2.4 map:keys
        21.2.5 map:contains
        21.2.6 map:get
        21.2.7 map:put
        21.2.8 map:entry
        21.2.9 map:remove
        21.2.10 map:for-each
        21.2.11 fn:collation-key
        21.2.12 The fn:deep-equal Function
    21.3 Map Instructions
    21.4 Map Constructors
    21.5 The Map Lookup Operator
        21.5.1 The Unary Lookup Operator
        21.5.2 The Postfix Lookup Operator
    21.6 Maps and Streaming
    21.7 Examples using Maps
22 Processing JSON Data
    22.1 XML Representation of JSON
    22.2 fn:json-to-xml
    22.3 fn:xml-to-json
    22.4 Transforming XML to JSON
23 Diagnostics
    23.1 Messages
    23.2 Assertions
24 Extensibility and Fallback
    24.1 Extension Functions
        24.1.1 fn:function-available
        24.1.2 Calling Extension Functions
        24.1.3 External Objects
        24.1.4 fn:type-available
    24.2 Extension Instructions
        24.2.1 Designating an Extension Namespace
        24.2.2 fn:element-available
        24.2.3 Fallback
25 Transformation Results
    25.1 Creating Secondary Results
    25.2 Restrictions on the use of xsl:result-document
    25.3 The Current Output URI
        25.3.1 fn:current-output-uri
    25.4 Validation
        25.4.1 Validating Constructed Elements and Attributes
            25.4.1.1 Validation using the [xsl:]validation Attribute
            25.4.1.2 Validation using the [xsl:]type Attribute
            25.4.1.3 The Validation Process
        25.4.2 Validating Document Nodes
26 Serialization
    26.1 Character Maps
    26.2 Disabling Output Escaping
27 Conformance
    27.1 Basic XSLT Processor
    27.2 Schema-Awareness Conformance Feature
    27.3 Serialization Feature
    27.4 Compatibility Features
    27.5 Streaming Feature
    27.6 Dynamic Evaluation Feature
    27.7 XPath 3.1 Feature
        27.7.1 Arrays
    27.8 Higher-Order Functions Feature

Appendices

A References
    A.1 Normative References
    A.2 Other References
B XML Representation of JSON
    B.1 Schema for the XML Representation of JSON
    B.2 Stylesheet for converting XML to JSON (without indentation)
C Glossary (Non-Normative)
D Element Syntax Summary (Non-Normative)
E Summary of Error Conditions (Non-Normative)
F Checklist of Implementation-Defined Features (Non-Normative)
    F.1 Application Programming Interfaces
    F.2 Vendor and User Extensions
    F.3 Localization
    F.4 Optional Features
    F.5 Dependencies
    F.6 Defaults and Limits
    F.7 Detection and Reporting of Errors
G List of XSLT-defined functions (Non-Normative)
H Schema for XSLT Stylesheets (Non-Normative)
I Acknowledgements (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 Last Call Working Draft of 2 October 2014 (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.

A transformation in the XSLT language is expressed in the form of a stylesheet. A stylesheet is made up of one or more well-formed XML [XML 1.0] documents conforming to the Namespaces in XML Recommendation [Namespaces in XML].

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

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

A transformation expressed in XSLT describes rules for transforming input data into output data. The inputs and outputs will all be instances of the XDM data model, described in [XDM 3.0]. In the simplest and most common case, the input is an XML document referred to as the source tree, and the output is an XML document referred to as the result tree. It is also possible to process multiple source documents, to generate multiple result documents, and to handle formats other than XML. The transformation is achieved by a set of template rules. A template rule associates a pattern, which typically matches nodes in the source document, with a sequence constructor. In many cases, evaluating the sequence constructor will cause new nodes to be constructed, which can be used to produce part of a result tree. The structure of the result trees can be completely different from the structure of the source trees. In constructing a result tree, nodes from the source trees can be filtered and reordered, and arbitrary structure can be added. This mechanism allows a stylesheet to be applicable to a wide class of documents that have similar source tree structures.

Stylesheets have a modular structure; they may contain several packages developed independently of each other, and each package may consist of several stylesheet modules.

[Definition: A stylesheet consists of one or more packages: specifically, one top-level package and zero or more library packages.]

[Definition: For a given transformation, one package functions as the top-level package. The complete stylesheet is assembled by finding the packages referenced directly or indirectly from the top-level package using xsl:use-package declarations: see 3.5.2 Dependencies between Packages.]

[Definition: Every package within a stylesheet, other than the top-level package, is referred to as a library package.]

[Definition: Within a package, one stylesheet module functions as the principal stylesheet module. The complete package is assembled by finding the stylesheet modules referenced directly or indirectly from the principal stylesheet module using xsl:include and xsl:import elements: see 3.11.2 Stylesheet Inclusion and 3.11.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:global-context-item, used to declare the stylesheet’s expectations of the global context item (notably, its type).

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

XSLT 3.0 also 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. Initially developed as XSLT-specific extensions, maps have now been integrated into XPath 3.1 (see [XPath 3.1]). XSLT 3.0 does not require implementations to support XPath 3.1 in its entirety, but it does requires support for these specific features.

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 C 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 tree is used (as in [XDM 3.0]) to refer to the aggregate consisting of a parentless node together with all its descendant nodes, plus all their attributes and namespaces.]

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.

The output of a transformation consists of the following:

  1. [Definition: A principal result: this can be any sequence of items (as defined in [XDM 3.0]).] The principal result is the value returned by the function or template in the stylesheet that is nominated as the entry point, as described in 2.3 Initiating a Transformation.

  2. [Definition: Zero or more secondary results: each secondary result can be any sequence of items (as defined in [XDM 3.0]).] A secondary result is the value returned by evaluating the body of an xsl:result-document instruction.

  3. Zero or more messages. Messages are generated by the xsl:message and xsl:assert instructions, and are described in 23.1 Messages and 23.2 Assertions.

  4. Static or dynamic errors: see 2.12 Error Handling.

The principal result and the secondary results may be post-processed as described in 2.3.6 Post-processing the Raw Result.

[Definition: 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 output of a transformation: specifically, a tree built by post-processing the items in the principal result or in a secondary result. Once created, the contents of a final result tree are not accessible within the stylesheet itself.] Any final result tree may be serialized as described in 26 Serialization.

[Definition: The term source tree means any tree provided as input to the transformation. This includes the document containing the global context item if any, documents containing nodes present in the initial match selection, documents containing nodes supplied as the values of stylesheet parameters, documents obtained from the results of functions such as document, 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. Unless otherwise stated, the term "tree" refers to a tree rooted at a parentless node: that is, the term does not include subtrees of larger trees. Every node therefore belongs to exactly one tree.

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

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

Where the phrase must, must not, or required relates to a stylesheet then the processor must enforce this constraint on stylesheets by 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 [XDM 3.0]. 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 [XDM 3.0]. If the XPath 3.1 Feature is implemented, then arrays (see 27.7.1 Arrays) are atomized by atomizing their members, recursively.] For some items (for example, elements with element-only content, function items, and maps), atomization generates a dynamic error.

  • [Definition: The term typed value is defined in Section 5.15 typed-value Accessor DM30. Every node, other than an element whose type annotation identifies it as having element-only content, has a typed value. For example, the typed value of an attribute of type xs:IDREFS is a sequence of zero or more xs:IDREF values.]

  • [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 core functions are: functions specified in [Functions and Operators 3.0] in either the standard function namespace or the namespace http://www.w3.org/2005/xpath-functions/math; plus functions defined in this specification in namespace http://www.w3.org/2005/xpath-functions/map.]

For a processor that implements the XPath 3.1 Feature, the term core function refers to the function library defined in [Functions and Operators 3.1], with the addition of the namespace http://www.w3.org/2005/xpath-functions/array.

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 D 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 D Element Syntax Summary. The meaning of the syntax summary notation is as follows:

  • An attribute that is required is shown with its name in bold. An attribute that may be omitted is shown with a question mark following its name.

  • An attribute that is deprecated is shown in a grayed font within square brackets.

  • The string that occurs in the place of an attribute value specifies the allowed values of the attribute. If this is surrounded by curly brackets ({...}), then the attribute value is treated as an attribute value template, and the string occurring within curly brackets specifies the allowed values of the result of evaluating the attribute value template. Alternative allowed values are separated by |. A quoted string indicates a value equal to that specific string. An unquoted, italicized name specifies a particular type of value.

    The types used are as follows:

    Type nameMeaning
    booleanOne of the strings "yes", "true", or "1" to indicate the value true, or one of the strings "no", "false", or "0" to indicate the value false. Note: the values are synonyms; where this specification uses a phrase such as "If required='yes' is specified ..." this is to be interpreted as meaning "If the attribute named required is present, and has the value yes, true, or 1 (after stripping leading and trailing whitespace) ...".
    stringAny string
    expressionAn XPath expression
    patternA pattern as described in 5.5 Patterns.
    item-typeAn ItemTypeXP30 as defined in the XPath 3.0 specification (or in XPath 3.1 if the processor implements the XPath 3.1 Feature)
    sequence-typeA SequenceTypeXP30 as defined in the XPath 3.0 specification (or in XPath 3.1 if the processor implements the XPath 3.1 Feature)
    uri; urisA URI, for example a namespace URI or a collation URI; a whitespace-separated list of URIs
    qnameA lexical QName as defined in 5.1.1 Qualified Names
    eqname; eqnamesAn EQName as defined in 5.1.1 Qualified Names; a whitespace-separated list of EQNames
    token; tokensA string containing no significant whitespace; a whitespace-separated list of such strings
    nmtoken; nmtokensA string conforming to the XML schema rules for the type xs:NMTOKEN; a whitespace-separated list of such strings.
    charA string comprising a single Unicode character
    integerAn integer, that is a string in the lexical space of the schema type xs:integer
    decimalA decimal value, that is a string in the lexical space of the schema type xs:decimal
    ncnameAn unprefixed name: a string in the value space of the schema type xs:NCName
    prefixAn xs:NCName representing a namespace prefix, which must be in scope for the element on which it appears
    idAn xs:NCName used as a unique identifier for an element in the containing XML document

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

  • 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 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? = boolean
  validation? = { "strict" | "lax" } >
  <!-- Content: ((xsl:variable | xsl:param)*, xsl:sequence) -->
</xsl:example-element>

This example defines a (non-existent) element xsl:example-element. The element is classified as an instruction. It takes the following attributes:

  1. A mandatory select attribute, whose value is an XPath expression

  2. An optional debug attribute, whose value must be yes, true, or 1 to indicate true, or no, false, or 0 to indicate false.

  3. An optional validation attribute, whose value must be strict or lax; the curly brackets indicate that the value can be defined as an attribute value template, allowing a value such as validation="{$val}", where the variable val is evaluated to yield "strict" or "lax" 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.

The rules in the element syntax summary (both for the element structure and for its attributes) apply to the stylesheet content after preprocessing as described in 3.13 Stylesheet Preprocessing.

Attributes are validated as follows. These rules apply to the value of the attribute after removing leading and trailing whitespace.

  • [ERR XTSE0020] It is a static error if an attribute (other than an attribute written using curly brackets in a position where an attribute value template is permitted) contains a value that is not one of the permitted values for that attribute.

  • [ERR XTDE0030] It is a dynamic error if the effective value of an attribute written using curly brackets, in a position where an attribute value template is permitted, is a value that is not one of the permitted values for that attribute. If the processor is able to detect the error statically (for example, when any XPath expressions within the curly brackets can be evaluated statically), then the processor may optionally 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.10 Forwards Compatible Processing.

[Definition: Some constructs defined in this specification are described as being deprecated. The use of this term implies that stylesheet authors should not use the construct, and that the construct may be removed in a later version of this specification.]

Note:

This specification includes a non-normative XML Schema for XSLT stylesheet modules (see H 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 3.0]. A list of these functions appears in G List of XSLT-defined functions. The signatures of these functions are described using the same notation as used in [Functions and Operators 3.0]. 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.

The execution of a stylesheet necessarily involves two activities: static analysis and dynamic evaluation. Static analysis consists of those tasks that can be performed by inspection of the stylesheet alone, including the binding of static variables, the evaluation of [xsl:]use-when expressions (see 3.13.1 Conditional Element Inclusion), and shadow attributes (see 3.13.2 Shadow Attributes) and detection of static errors. Dynamic evaluation consists of tasks which in general cannot be carried out until a source document is available.

Dynamic evaluation is further divided into two activities: priming the stylesheet, and invoking a selected component.

  • Priming the stylesheet provides the dynamic context for evaluation, and supplies all the information needed to establish the values of global variables.

  • Invoking a component (such as a template or function) causes evaluation of that template or function to produce a result, which is an arbitrary XDM value.

    [Definition: The result of invoking the selected component, after any required conversion to the declared result type of the component, is referred to as the raw result.]

    This raw result may optionally be post-processed to construct a result tree, to serialize the result, or both, as described in 2.3.6 Post-processing the Raw Result.

Implementations may allow static analysis and dynamic evaluation to be initiated independently, so that the cost of static analysis can be amortized over multiple transformations using the same stylesheet. Implementations may also allow priming of a stylesheet and invocation of components to be initiated independently, in which case a single act of priming the stylesheet may be followed by a series of independent component invocations. Although this specification does not require such a separation, this section distinguishes information that is needed before static analysis can proceed, information that is needed to prime the stylesheet, and information that is needed when invoking components.

The language is designed to allow the static analysis of each package to be performed independently of other packages, with only basic knowledge of the properties of components made available by used packages. Beyond this, the specification leaves it to implementations to decide how to organize this process. When packages are not used explicitly, the entire stylesheet is treated as a single package.

2.3.1 Information needed for Static Analysis

The following information is needed prior to static analysis of a package:

Conceptually, the output of the static analysis of a package is an object which might be referred to (without constraining the implementation) as a compiled package. Prior to dynamic evaluation, all the compiled packages needed for execution must be checked for consistency, and component references must be resolved. This process may be referred to, again without constraining the implementation, as linking.

2.3.2 Priming a Stylesheet

The information needed when priming a stylesheet is as follows:

  • A set (possibly empty) of values for non-static stylesheet parameters (see 9.5 Global Variables and Parameters). These values are available for use within expressions in the stylesheet. As a minimum, values must be supplied for any parameters declared with the attribute required="yes".

    A supplied value is converted if necessary to the declared type of the stylesheet parameter using the function conversion rules.

    Note:

    Non-static stylesheet parameters are implicitly public, which ensures that all the parameters in the stylesheet for which values can be supplied externally have distinct names. Static parameters, by contrast, are local to a package.

  • [Definition: An item that acts as the global context item for the transformation. This item is accessible as the initial value of the XPath expressions . (dot) and self::node() appearing within the select expression or sequence constructor of a global variable declaration within the top-level package, as described in 5.3.3.1 Maintaining Position: the Focus. ]

    Note:

    In previous releases of this specification, a single node was typically supplied to represent the source document for the transformation. This node was used as the target node for the implicit call on xsl:apply-templates used to start the transformation process (now called the initial match selection), and the root node of the containing tree was used as the context item for evaluation of global variables (now called the global context item). This relationship between the initial match selection and the global context item is likely to be found for compatibility reasons in a transformation API designed to work with earlier versions of this specification, but it is no longer a necessary relationship; the two values can in principle be completely independent of each other.

    Stylesheet authors wanting to write code that can be invoked using legacy APIs should not rely on the caller being able to supply different values for the initial match selection and the global context item.

    The global context item is potentially used when initializing global variables and parameters. If the initialization of any global variables or parameter depends on the context item, a dynamic error can occur if the context item is absent. It is implementation-defined whether this error occurs during priming of the stylesheet or subsequently when the variable is referenced; and it is implementation-defined whether the error occurs at all if the variable or parameter is never referenced. The error can be suppressed by use of xsl:try and xsl:catch within the sequence constructor used to initialize the variable or parameter. It cannot be suppressed by use of xsl:try around a reference to the global variable.

    In a library package, the context item, context position, and context size used for evaluation of global variables will be absent, and the evaluation of any expression that references these values will result in a dynamic error. This will also be the case in the top-level package if no global context item is supplied.

    Note:

    If a context item is available within a global variable declaration, then the context position and context size will always be 1 (one).

    Note:

    For maximum reusability of code, it is best to avoid use of the context item when initializing global variables and parameters. Instead, all external information should be supplied using named stylesheet parameters. Especially when these use namespaces to avoid conflicts, there is then no risk of confusion between the information supplied externally to different packages.

    When a stylesheet parameter is defined in a library package, it is possible for a using package to supply a value for the parameter by overriding the parameter declaration within an xsl:override element. If the using package is the top-level package then the overriding declaration can refer to the global context item.

  • A mechanism for obtaining a document node and a media type, given an absolute URI. The total set of available documents (modeled as a mapping from URIs to document nodes) forms part of the context for evaluating XPath expressions, specifically the 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 [XDM 3.0].

Once a stylesheet is primed, the values of global variables remain stable through all component invocations. In addition, priming a stylesheet creates an execution scopeFO30 during which the dynamic context and all calls on deterministicFO30 functions remain stable; for example two calls on the current-dateTimeFO30 function within an execution scope are defined to return the same result.

Parameters passed to the transformation by the client application when a stylesheet is primed are matched against stylesheet parameters (see 9.5 Global Variables and Parameters), not against the template parameters of any template executed during the course of the transformation.

[ERR XTDE0050] It is a dynamic error if a stylesheet declares a visible stylesheet parameter that is explicitly or implicitly mandatory, and no value for this parameter is supplied when the stylesheet is primed. A stylesheet parameter is visible if it is not masked by another global variable or parameter with the same name and higher import precedence. If the parameter is a static parameter then the value must be supplied prior to the static analysis phase.

2.3.3 Apply-Templates Invocation

[Definition: A stylesheet may be evaluated by supplying a value to be processed, together with an initial mode. The value (which can be any sequence of items) is referred to as the initial match selection. The processing then corresponds to the effect of the xsl:apply-templates instruction.]

The initial match selection will often be a single document node, traditionally called the source document of the transformation; but in general, it can be any sequence. If the initial match selection is an empty sequence, the result of the transformation will be empty, since no template rules are evaluated.

Processing proceeds by finding the template rules that match the items in the initial match selection, and evaluating these template rules with a focus based on the initial match selection. The template rules are evaluated in final output state.

The following information is needed when dynamic evaluation is to start with a template rule:

  • The initial match selection. An API that chooses to maintain compatibility with previous versions of this specification should allow a method of invocation in which a singleton node is provided, which is then used in two ways: the node itself acts as the initial match selection, and the root node of the containing tree acts as the global context item.

  • Optionally, an initial mode.

    [Definition: The initial mode, if specified, must either be the unnamed mode, or a mode that is explicitly named either in an xsl:mode declaration, or in the mode attribute of an xsl:template declaration within the stylesheet, or in the default-mode attribute of an xsl:stylesheet or xsl:transform element. If an initial mode is supplied, then in searching for the template rule that best matches the items in the initial match selection, the processor considers only those rules that apply to the initial mode. If no initial mode is supplied, then the mode used is that named in the default-mode attribute of the (explicit or implicit) xsl:package element of the top-level package or in the absence of such an attribute, the unnamed mode.]

  • Parameters, which will be passed to the template rules used to process items in the input sequence. The parameters consist of two sets of (QName, value) pairs, one set for tunnel parameters and one for non-tunnel parameters, in which the QName identifies the name of a parameter and the value provides the value of the parameter. Either or both sets of parameters may be empty. The effect is the same as when a template is invoked using xsl:apply-templates with an xsl:with-param child specifying tunnel="yes" or tunnel="no" as appropriate. If a parameter is supplied that is not declared or used, the value is simply ignored. These parameters are not used to set stylesheet parameters.

    A supplied value is converted if necessary to the declared type of the template parameter using the function conversion rules.

The raw result of the invocation is the result of processing the supplied input sequence as if by a call on xsl:apply-templates in the specified mode: specifically, each item in the input sequence is processed by selecting and evaluating the best matching template rule, and converting the result (if necessary) to the type declared in the as attribute of that template using the function conversion rules; and the results of processing each item are then concatenated into a single sequence, respecting the order of items in the input sequence.

Note:

If the initial mode is a streamable mode, then streaming will only be possible if nodes in the input sequence are 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.

[ERR XTDE0044] It is a dynamic error if the invocation of the stylesheet specifies an initial mode and if no initial match selection is supplied (either explicitly, or defaulted to the global context item).

[ERR XTDE0045] It is a dynamic error if the invocation of the stylesheet specifies an initial mode (other than the unnamed mode) that does not match either the expanded QName in the name attribute of an xsl:mode declaration, or the expanded QName in the mode attribute of any template defined in the stylesheet.

It is a dynamic error [see ERR XTDE0700] if the template rule selected for processing any item in the initial match selection defines a template parameter that specifies required="yes" and no value is supplied for that parameter.

Note:

A stylesheet can process further source documents in addition to those supplied when the transformation is invoked. These additional documents can be loaded using the functions document (see 20.1 fn:document) or docFO30 or collectionFO30 (see [Functions and Operators 3.0]), 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 24.1 Extension Functions).

2.3.4 Call-Template Invocation

[Definition: A stylesheet may be evaluated by selecting a named template to be evaluated; this is referred to as the initial named template.] The effect is analogous to the effect of executing an xsl:call-template instruction. The following information is needed in this case:

  • Optionally, the name of the initial named template which is to be executed as the entry point to the transformation. If no template name is supplied, the default template name is xsl:initial-template. The selected template must exist within the stylesheet.

  • Optionally, a context item for evaluation of this named template, defaulting to the global context item if it exists. This is constrained by any xsl:context-item element appearing within the selected xsl:template element. The initial named template is evaluated with a singleton focus based on this context item if it exists, or with an absent focus otherwise.

  • Parameters, which will be passed to the selected template rule. The parameters consist of two sets of (QName, value) pairs, one set for tunnel parameters and one for non-tunnel parameters, in which the QName identifies the name of a parameter and the value provides the value of the parameter. Either or both sets of parameters may be empty. The effect is the same as when a template is invoked using xsl:call-template with an xsl:with-param child specifying tunnel="yes" or tunnel="no" as appropriate. If a parameter is supplied that is not declared or used, the value is simply ignored. These parameters are not used to set stylesheet parameters.

    A supplied value is converted if necessary to the declared type of the template parameter using the function conversion rules.

The raw result of the invocation is the result of evaluating the initial named template, after conversion of the result to the type declared in the as attribute of that template using the function conversion rules, if such conversion is necessary.

The initial named template is evaluated in final output state.

[ERR XTDE0040] It is a dynamic error if the invocation of the stylesheet specifies a template name that does not match the expanded QName of a named template defined in the stylesheet, whose visibility is public or final.

It is a dynamic error [see ERR XTDE0700] if the initial named template, or any of the template rules invoked to process items in the initial match selection, defines a template parameter that specifies required="yes" and no value is supplied for that parameter.

2.3.5 Function Call Invocation

[Definition: A stylesheet may be evaluated by calling a named stylesheet function, referred to as the initial function.] The following additional information is needed in this case:

  • The name and arity of a stylesheet function which is to be executed as the entry point to the transformation.

    Note:

    In the design of a concrete API, the arity may be inferred from the length of the parameter list.

  • A list of values to act as parameters to the initial function. The number of values in the list must be the same as the arity of the function.

    A supplied value is converted if necessary to the declared type of the function parameter using the function conversion rules.

The raw result of the invocation is the result of evaluating the initial function, after conversion of the result to the type declared in the as attribute of that function using the function conversion rules, if such conversion is necessary.

Note:

The initial function (like all stylesheet functions) is evaluated with an absent focus.

[ERR XTDE0041] It is a dynamic error if the invocation of the stylesheet specifies a function name and arity that does not match the expanded QName and arity of a named stylesheet function defined in the stylesheet, whose visibility is public or final.

When a transformation is invoked by calling an initial function, the entire transformation executes in temporary output state, which means that calls on xsl:result-document are not permitted.

2.3.6 Post-processing the Raw Result

At user option, the raw result of a component invocation may either be returned to the calling application unchanged, or it may be post-processed. Two stages of post-processing are defined, both of which are optional:

  1. Result tree construction

    If the raw result 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 raw result R were processed by the following function:

    <xsl:function name="f:construct-result-tree" as="document-node()">
      <xsl:param name="R" as="item()*"/>
      <xsl:document validation="preserve">
        <xsl:sequence select="$R"/>
      </xsl:document>  
    </xsl:function>
    

    An implicit result tree is also created when the raw result is empty, provided that no xsl:result-document instruction has been evaluated during the course of the transformation (which will always be the case if the stylesheet is invoked by calling an initial function). 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 when stylesheet invocation is by supplying an initial mode (see 2.3.3 Apply-Templates Invocation) or a named template (see 2.3.4 Call-Template Invocation), and the content of the initial named template is a single xsl:result-document instruction, as in the example template with name="IMPLICIT" shown in 2.4 Executing a Transformation, then only one result tree is produced, not two. It is useful to make the result document explicit as this is a convenient way of invoking document-level validation. (Validation of the implicit result document can also be achieved by adding an xsl:document instruction to the initial template.)

    If the result of the initial named 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.

  2. Serialization

    See 2.6 Parsing and Serialization.

    Either the raw result, or a result tree produced as described above, may optionally be serialized as described in 26 Serialization.

    Note:

    The first phase of serialization, called sequence normalization, has no effect if the supplied value is a single document node, which will be the case if serialization is preceded by result tree construction. In the case of any other supplied value, the effect of sequence normalization is very similar to the effect of result tree construction, except where an item-separator serialization parameter is present. Use of item-separator allows, for example, a sequence of strings returned by invoking a stylesheet function to be output with newline separators.

[Definition:  The base output URI is a URI to be used as the base URI when resolving a relative URI reference allocated to a final result tree. If the transformation generates more than one final result tree, then typically each one will be allocated a URI relative to this base URI.] The way in which a base output URI is established is implementation-defined. Each invocation of the stylesheet may supply a different base output URI. It is acceptable for the base output URI to be absent, provided no constructs (such as xsl:result-document) are evaluated that depend on the value of the base output URI.

Note:

It will often be convenient for the base output URI to be the same as the location to which the principal result document is serialized, but this relationship is not a necessary one.

Note:

This specification does not constrain the design of application programming interfaces or the choice of defaults. In previous versions of this specification, result tree construction was a mandatory process, while serialization was optional. When invoking stylesheet functions directly, however, result tree construction and serialization may be inappropriate as defaults. These considerations may affect the design of APIs.

2.4 Executing a Transformation

The classic method of executing an XSLT transformation is to apply template rules to an input document (see 2.3.3 Apply-Templates Invocation), and then to deliver the result as a result tree which is optionally serialized (see 2.3.6 Post-processing the Raw Result). This processing model is described in this section. Other ways of invoking a transformation or processing the result are outlined in the previous section.

[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 source document is typically processed by finding the template rule that best matches its root (document) node, and evaluating the sequence constructor contained in this template rule, as described in 5.7 Sequence Constructors.

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

  1. If the template has an as attribute, then the raw result sequence is checked against the required type in the same way as for any other template, and is converted if necessary to the required type by applying the function conversion rules.

  2. If the result sequence is non-empty, then it is typically post-processed (as described in 2.3.6 Post-processing the Raw Result) 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>
    

The process of generating a result tree from the raw result of the initial template may be replaced with the very similar sequence normalization process described in 26 Serialization. In the latter case the serialization parameter item-separator may be used to separate items in the raw result with a string other than space (for example, newlines).

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 (unless raw output is requested) 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 24.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.3 The Static and Dynamic Context.

2.6 Parsing and Serialization

An XSLT stylesheet describes a process that constructs a set of results from a set of inputs. The inputs are the data provided at stylesheet invocation, as described in 2.3 Initiating a Transformation. The results include the principal result (an arbitrary sequence), which is the result of the initial component invocation, together with any secondary results produced using xsl:result-document instructions.

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

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

Like parsing, serialization is not part of the transformation process, and it is not required that an XSLT processor must be able to perform serialization. However, for pragmatic reasons, this specification describes declarations (the xsl:output element and the xsl:character-map declarations, see 26 Serialization), and attributes on the xsl:result-document instruction, that allow a stylesheet to specify the desired properties of a serialized output file. When serialization is not being performed, either because the implementation does not support the serialization option, or because the user is executing the transformation in a way that does not invoke serialization, then the content of the xsl:output and xsl:character-map declarations has no effect. Under these circumstances the processor may 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 optional child elements xsl:use-package and xsl:expose describing properties of the package. The package manifest may refer to an external top-level stylesheet module using an xsl:include or xsl:import declaration, or it may contain the body of a stylesheet module inline (the two approaches can also be mixed).

When no packages are explicitly defined, the entire stylesheet is treated as a single package; the effect is as if the xsl:stylesheet or xsl:transform element of the principal stylesheet module were replaced by 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 24.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 24.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 24 Extensibility and Fallback.

The XSLT language can also be extended by the use of extension attributes (see 3.2 Extension Attributes), and by means of user-defined data elements (see 3.7.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 a SequenceType.

[Definition: A SequenceType constrains the type and number of items in a sequence. The term is used both to denote the concept, and to refer to the syntactic form in which sequence types are expressed in the XPath grammar: specifically SequenceTypeXP30 in [XPath 3.0], or SequenceTypeXP31 in [XPath 3.1], depending on whether or not the XPath 3.1 Feature is implemented.]

[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 package are referred to as the in-scope schema components.]

The set of in-scope schema components may vary between one package and another, but as explained in 3.15 Importing Schema Components, the schema components used in different packages must be consistent with each other.

The conformance rules for XSLT 3.0, defined in 27 Conformance, distinguish between a basic XSLT processor and a schema-aware XSLT processor. As the names suggest, a basic XSLT processor does not support the features of XSLT that require access to schema information, either statically or dynamically. A stylesheet that works with a basic XSLT processor will produce the same results with a schema-aware XSLT processor provided that the source documents are untyped (that is, they are not validated against a schema). However, if source documents are validated against a schema then the results may be different from the case where they are not validated. Some constructs that work on untyped data may fail with typed data (for example, an attribute of type xs:date cannot be used as an argument of the 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.14 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 typed="lax"/>
<xsl:global-context-item use="required"
            as="document-node(schema-element(my:invoice))"/>

This example will cause the transformation to fail with an error message, unless the global context item is valid against the top-level element declaration my:invoice, and has been annotated as such.

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 [XDM 3.0]. The implementation may choose one of several strategies for dealing with this situation:

  1. The processor may signal a 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 [XDM 3.0], 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.12 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 result tree. This can be done in a number of ways.

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

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

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

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

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

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 three ways:

  • The initial mode can be declared as a streamable mode. In this case the initial match selection will generally be a document node (or sequence of document nodes), 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 these nodes can be constrained by using the attribute on-no-match="fail" on the initial mode, and using this mode only for processing the top-level nodes.

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

  • Streamed merging of a set of input documents can be initiated using the xsl:merge instruction.

The rules for streamability, which are defined in detail in 19 Streamability, 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.

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

When streaming is initiated, for example using the xsl:stream instruction, it is necessary to declare which accumulators are applicable to the streamed document.

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

2.11 Streamed Validation

Streaming can be combined with schema-aware processing: that is, the streamed input to a transformation can be subjected to on-the-fly validation, a process which typically accepts an input stream from the XML parser and delivers an output stream (of type-annotated nodes) to the transformation processor. The XSD specification is designed so that validation is, with one or two exceptions, a streamable process. The exceptions include:

  • There may be a need to allocate memory to hold keys, in order to enforce uniqueness and referential integrity constraints (xs:unique, xs:key, xs:keyref).

  • In XSD 1.1, assertions can be defined by means of XPath expressions. These are not constrained to be streamable; in the general case, any subtree of the document that is validated using an assertion may need to be buffered in memory while the assertion is processed.

Applications that need to run in finite memory may therefore need to avoid these XSD features, or to use them with care.

XSD is designed so that the intended type of an element (the “governing type”) can be determined as soon as the start tag of the element is encountered: the process of validation checks whether the content of the element actually conforms to this type, and by the time the end tag is encountered, the process will have established either that the element is valid against the governing type, or that it is invalid.

By default, dynamic errors occurring during streamed processing are fatal: they typically cause the transformation to fail immediately. XSLT 3.0 introduces the ability to catch dynamic errors and recover from them. Schema invalidity, however, is treated as a dynamic error of the instruction that processes the entire input stream, so after a validation failure, no further processing of that input stream is possible.

In consequence, a streamed validator that is running in tandem with a streamed transformation can present the transformer with element nodes that carry a provisional type annotation representing the type that the element will have if it turns out to be valid. As soon as a node is encountered that violates this assumption, the validator should stop the flow of data to the transformer, so that the transformer never sees invalid data. This allows the stylesheet code to be compiled with the assumption of type-safety: at run-time, all nodes seen by the transformation will conform to their XSLT-declared types (for example, a type declared implicitly using match="schema-element(invoice)" on an xsl:template element).

A streamed transformation that only accesses part of the input document (for example, a header at the start of a document) is not required to continue reading once the data it needs has been read. This means that XML well-formedness or validity errors occurring in the unread part of the input stream may go undetected.

2.12 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 a principal result .

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

When a dynamic error occurs, and is not caught using xsl:catch, the processor must signal the error, and the transformation fails.

Because different implementations may optimize execution of the stylesheet in different ways, the detection of dynamic errors is to some degree implementation-dependent. In cases where an implementation is able to produce a principal result or secondary result without evaluating a particular construct, the implementation is never required to evaluate that construct solely in order to determine whether doing so causes a dynamic error. For example, if a variable is declared but never referenced, an implementation may choose whether or not to evaluate the variable declaration, which means that if evaluating the variable declaration causes a dynamic error, some implementations will 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.11 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.

A dynamic error is also signaled during the static analysis phase if the error occurs during evaluation of a static expression.

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 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 principal result or secondary result, it is still possible that errors may occur in serializing that result . For example, it may be impossible to serialize the result using the encoding selected by the user. Such an error is referred to as a serialization error.] If the processor performs serialization, then it must do so as specified in 26 Serialization, and in particular it must 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), 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 E Summary of Error Conditions.

Errors defined in related specifications ([XPath 3.0], [Functions and Operators 3.0] [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.7 Stylesheet Element and 3.8 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 D 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 24.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:

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

3.2 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 principal result or any secondary result of the transformation to be different from the results 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 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.3 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.4 Standard Attributes

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

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

It is recommended that all these attributes should also be permitted on extension instructions, but this is at the discretion of the implementer of each extension instruction. They may also be permitted on user-defined data elements, though they will only have any useful effect in the case of data elements that are designed to behave like XSLT declarations or instructions.

In the following descriptions, these attributes are referred to generically as [xsl:]version, and so on.

These attributes all affect the element they appear on, together with any elements and attributes that have that element as an ancestor. The two forms with and without the XSLT namespace have the same effect; the XSLT namespace is used for the attribute if and only if its parent element is not in the XSLT namespace.

In the case of [xsl:]default-collation, [xsl:]expand-text, [xsl:]version, and [xsl:]xpath-default-namespace, the value can be overridden by a different value for the same attribute appearing on a descendant element. The effective value of the attribute for a particular stylesheet element is determined by the innermost ancestor-or-self element on which the attribute appears.

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

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

The effect of the [xsl:]use-when attribute is described in 3.13.1 Conditional Element Inclusion.

Because these attributes may appear on any XSLT element, they are not listed in the syntax summary of each individual element. Instead they are listed and described in the entry for the xsl:stylesheet, xsl:transform, and xsl:package elements only. This reflects the fact that these attributes are often used on the outermost element of the stylesheet, in which case they apply to the entire stylesheet module or package manifest.

Note that the effect of these attributes does not extend to stylesheet modules referenced by xsl:include or xsl:import declarations, nor to packages referenced using xsl:use-package.

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

[xsl:]default-collation

see 3.7.1 The default-collation Attribute

[xsl:]default-mode

see 3.7.2 The default-mode Attribute

[xsl:]default-validation

see 25.4 Validation

[xsl:]exclude-result-prefixes

see 11.1.3 Namespace Nodes for Literal Result Elements

[xsl:]expand-text

see 5.6.2 Text Value Templates

[xsl:]extension-element-prefixes

see 24.2 Extension Instructions

[xsl:]use-when

see 3.13.1 Conditional Element Inclusion

[xsl:]version

see 3.9 Backwards Compatible Processing and 3.10 Forwards Compatible Processing

[xsl:]xpath-default-namespace

see 5.1.2 Unprefixed Lexical QNames in Expressions and Patterns

3.5 Packages

[Definition: An explicit package is represented by an xsl:package element, which will generally be the outermost element of an XML document. When the xsl:package element is not used explicitly, the entire stylesheet comprises a single implicit package.] (This specification does not preclude the xsl:package being embedded in another XML document, but it will never have any other XSLT element as an ancestor).

<xsl:package
  id? = id
  name? = uri
  package-version? = string
  version = decimal
  input-type-annotations? = "preserve" | "strip" | "unspecified"
  declared-modes? = boolean
  default-mode? = eqname | "#unnamed"
  default-validation? = "preserve" | "strip"
  default-collation? = uris
  extension-element-prefixes? = prefixes
  exclude-result-prefixes? = prefixes
  expand-text? = boolean
  use-when? = expression
  xpath-default-namespace? = uri >
  <!-- Content: ((xsl:expose | declarations)*) -->
</xsl:package>

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

The version attribute indicates the version of the XSLT language specification to which the package manifest conforms. The value should normally be 3.0. If the value is numerically less than 3.0, the content of the xsl:package element is processed using the rules for backwards compatible behavior (see 3.9 Backwards Compatible Processing). If the value is numerically greater than 3.0, it is processed using the rules for forwards compatible behavior (see 3.10 Forwards Compatible Processing).

A package typically has a name, given in its name attribute, which must be an absolute URI. Unnamed packages are allowed, but they can only be used as the “top level” of an application; they cannot be the target of an xsl:use-package declaration in another package.

A package may have a version identifier, given in its package-version attribute. This is used to distinguish different versions of a package. The value of the version attribute, after trimming leading and trailing whitespace, must conform to the syntax given in 3.5.1 Versions of a Package. If no version number is specified for a package, version 1 is assumed.

The attributes default-collation, default-mode, default-validation, exclude-result-prefixes, expand-text, extension-element-prefixes, use-when, version, and xpath-default-namespace are standard attributes that can appear on any XSLT element, and potentially affect all descendant elements. Their meaning is described in 3.4 Standard Attributes.

The package manifest contains the following elements, arbitrarily ordered:

  1. Zero or more xsl:expose declarations that define the interface offered by this package to the outside world. An xsl:expose declaration may appear only as a child of xsl:package.

  2. Zero or more additional declarations. These are the same as the declarations permitted as children of xsl:stylesheet or xsl:transform.

    Some declarations of particular relevance to packages include:

    1. The xsl:use-package declaration, which declares the names and versions of the packages on which this package is dependant.

    2. The optional xsl:global-context-item element; if present this element defines constraints on the existence and type of the global context item.

    3. Zero or more xsl:include and xsl:import declarations, which define additional stylesheet modules to be incorporated into this package.

    4. Zero or more ordinary declarations, that is, elements that are permitted as children of xsl:stylesheet or xsl:transform. One possible coding style is to include in the package manifest just a single xsl:import or xsl:include declaration as a reference to the effective top-level stylesheet module; this approach is particularly suitable when writing code that is required to run under earlier releases of XSLT as well as under XSLT 3.0. Another approach is to include the substance of the top-level stylesheet module inline within the package manifest.

Example: An example package

The following example shows a package that offers a number of functions for manipulating complex numbers. A complex number is represented as a map with two entries, the keys being 0 for the real part, and 1 for the imaginary part.

<xsl:package
  name="http://example.org/complex-arithmetic.xsl"
  package-version="1.0"
  version="3.0"
  xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
  xmlns:xs="http://www.w3.org/2001/XMLSchema"
  xmlns:f="http://example.org/complex-arithmetic.xsl">
  
  <xsl:function name="f:complex-number" 
                as="map(xs:integer, xs:double)" visibility="public">
    <xsl:param name="real" as="xs:double"/>
    <xsl:param name="imaginary" as="xs:double"/>
    <xsl:sequence select="map{ 0:$real, 1:$imaginary }"/>
  </xsl:function>
  
  <xsl:function name="f:real" 
                as="xs:double" visibility="public">
    <xsl:param name="complex" as="map(xs:integer, xs:double)"/>
    <xsl:sequence select="$complex(0)"/>
  </xsl:function>
  
  <xsl:function name="f:imag" 
                as="xs:double" visibility="public">
    <xsl:param name="complex" as="map(xs:integer, xs:double)"/>
    <xsl:sequence select="$complex(1)"/>
  </xsl:function>
  
  <xsl:function name="f:add" 
                as="map(xs:integer, xs:double)" visibility="public">
    <xsl:param name="x" as="map(xs:integer, xs:double)"/>
    <xsl:param name="y" as="map(xs:integer, xs:double)"/>
    <xsl:sequence select="
         f:complex-number(
           f:real($x) + f:real($y), 
           f:imag($x) + f:imag($y)"/>
  </xsl:function>
  
  <xsl:function name="f:multiply" 
                as="map(xs:integer, xs:double)" visibility="public">
    <xsl:param name="x" as="map(xs:integer, xs:double)"/>
    <xsl:param name="y" as="map(xs:integer, xs:double)"/>
    <xsl:sequence select="
         f:complex-number(
           f:real($x)*f:real($y) - f:imag($x)*f:imag($y),
           f:real($x)*f:imag($y) + f:imag($x)*f:real($y))"/>
  </xsl:function>
  
  <!-- etc. -->
  
</xsl:package>

A more complex package might include private or abstract functions as well as public functions; it might expose components other than functions (for example, templates or global variables), and it might contain xsl:use-package elements to allow it to call on the services of other packages.

Note:

In this example, the way in which complex numbers are represented is exposed to users of the package. It would be possible to hide the representation by declaring the types on public functions simply as item(); but this would be at the cost of type safety.

A package that does not itself expose any components may be written using a simplified syntax: the xsl:package element is omitted, and the xsl:stylesheet or xsl:transform element is now the outermost element of the stylesheet module. For compatibility reasons, all the named templates and modes declared in the package are made public. More formally, the principal stylesheet module of the top-level package may be expressed as an xsl:stylesheet or xsl:transform element, which is equivalent to the package represented by the output of the following transformation, preserving the base URI of the source:

 <xsl:transform version="3.0" 
    xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    xmlns:t="http://www.w3.org/1999/XSL/TransformAlias">
 
    <xsl:namespace-alias stylesheet-prefix="t" result-prefix="xsl"/>
    
    <xsl:template match="xsl:stylesheet|xsl:transform">
      <t:package declared-modes="no">
        <xsl:copy-of select="@*"/>
        <t:expose component="mode" names="*" visibility="public"/>
        <t:expose component="template" names="*" visibility="public"/>
        <xsl:copy-of select="node()"/>
      </t:package>
    </xsl:template>
 </xsl:transform>
       

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

A more extensive example of a package, illustrating how components in a package can be overridden in a client package, is given in 3.5.7 Worked Example of a Library Package.

3.5.1 Versions of a Package

If a package has a version number, the version number must conform to the grammar:

        PackageVersion   ::= NumericPart ( "-" NamePart )?
        NumericPart      ::= IntegerLiteral ( "." IntegerLiteral )*
        NamePart         ::= NCName
               

Here IntegerLiteralXP30 and NCName are as defined in the XPath 3.0 grammar productions of the same name (including rules on limits). Leading and trailing whitespace is ignored; no other whitespace is allowed.

Examples of valid version numbers are 2.0.5 or 3.10-alpha.

[Definition: The integer literals and the optional NamePart within the version number are referred to as the portions of the version number.]

Note:

This means that 1-alpha-2 is a valid version number, with two portions: 1 and alpha-2. The second hyphen is part of the NCName, it does not act as a portion separator.

Versions are ordered. When comparing two versions:

  1. Trailing zero portions (that is, any zero-valued integer that is not followed by another integer) are discarded.

  2. Comparison proceeds by comparing portions pairwise from the left.

  3. If both versions have the same number of portions and all portions compare equal (under the rules of the XPath eq operator using the Unicode codepoint collation), then the versions compare equal.

  4. If the number of portions in the two versions V1 and V2 is N1 and N2, with N1<N2, and if all portions in positions 1 to N compare equal, then V1 is less than V2 if the portion of V2 in position N1 is an integer, and is greater than V2 if this portion is an NCName. For example, 1.2 is less than 1.2.5, while 2.0 is greater than 2.0-rc1.

  5. Portions are compared as follows:

    1. If both portions are integers, they are compared using the rules of XPath value comparisons.

    2. If both portions are NCNames, they are compared using the rules of XPath value comparisons, using the Unicode Codepoint Collation.

    3. If one portion is an integer and the other is an NCName, the NCName comes first.

For example, the following shows a possible ordered sequence of version numbers:

0-rc1 < 0-rc2 < 0 < 1 = 1.0 < 1.0.2 < 1.0.3-rc1 < 1.0.3 < 1.0.3.2 < 1.0.10

Note:

The version number format defined here is designed to be general enough to accommodate a variety of conventions in common use, and to allow useful semantics for matching of versions and ranges of versions, without being over-prescriptive. It is influenced by [SemVer], but is not as prescriptive, and it imposes no assumptions about backwards compatibility of packages between successive versions.

Dependencies between packages may specify a version range (see 3.5.2 Dependencies between Packages). A version range represents a set of accepted versions. The syntax of a version range is shown below. Whitespace is permitted only where indicated, using the terminal symbol S.

        PackageVersionRange    ::=  AnyVersion | VersionRanges
        AnyVersion             ::=  "*"
        VersionRanges          ::=  VersionRange (S? "," S? VersionRange)*
        VersionRange           ::=  PackageVersion | VersionPrefix | VersionFrom | VersionTo | VersionFromTo
        VersionPrefix          ::=  PackageVersion ".*"
        VersionFrom            ::=  PackageVersion "+"
        VersionTo              ::=  "to" S (PackageVersion | VersionPrefix)
        VersionFromTo          ::=  PackageVersion S "to" S (PackageVersion | VersionPrefix)     
               

The meanings of the various forms of version range are defined below:

  • The range AnyVersion matches any version.

  • The range VersionRanges matches a version if any constituent VersionRange matches that version.

    For example, 9.5.0.8, 9.6.1.2 matches those specific versions only, while 9.5.0.8, 9.6+ matches either version 9.5.0.8 or any version from 9.6 onwards.

  • A range that is a PackageVersion matches that version only.

  • The range VersionPrefix matches any version whose leading portions are the same as the portions in the PackageVersion part of the VersionPrefix.

    For example, 1.3.* matches 1.31.3.51.3.10.2,  and 1.3-beta (but not 1 or 1.4).

    Note:

    The .* indicates that additional portions may follow; it does not indicate a substring match on the final portion. So 1.3.* does not match 1.35, and 3.3-beta.* does not match 3.3-beta12. Also, 3.3-beta.* does not match 3.3-beta.5: this is because the last dot is not a portion separator, but is part of the final NCName. In fact, using .* after a version number that includes an NCName portion is pointless, because an NCName portion can never be followed by further portions.

  • The range VersionFrom matches any version that is greater than or equal to the version supplied.

    For example 1.3+ matches 1.31.3.21.4,  and 2.1 (but not 1.3-beta or 1.2). And 1.3-beta+ matches 1.3-beta1.3-gamma1.3.01.4, and 8.0, but not 1.3-alpha or 1.2.

  • The range VersionTo matches any version that is less than or equal to some version that matches the VersionPrefix.

    For example, to 4.0 matches 1.52.33.84.0,  and 4.0-beta (but not 4.0.1), while to 3.3.* matches 1.5 or 2.0.6 or 3.3.4621, but not 3.4.0 or 3.4.0-beta.

  • The range VersionFromTo matches any version that is greater than or equal to the starting PackageVersion, and less than or equal to some version that matches the VersionPrefix.

    For example, 1 to 5 matches 1.12.13.1,  or 5.0 (but not 5.1), while 1 to 5.* matches all of these, plus versions such as 5.7.2 (but not 6.0 or 6.0-beta). Similarly, 1.0-beta to 1.0 matches 1.0-beta, 1.0-beta.2, 1.0-gamma, and 1.0, but not 1.0-alpha or 1.0.1.

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

<!-- Category: declaration -->
<xsl:use-package
  name = uri
  package-version? = string >
  <!-- 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.

The name and package-version attributes together identify the used package. The value of the package-version attribute, if present, must conform to the rules for a PackageVersionRange given in 3.5.1 Versions of a Package; if omitted the value * is assumed, which matches any version. The used package must have a name that is an exact match for the name in the name attribute (using codepoint comparison), and its explicit or implicit package-version must match the version range given in the package-version attribute.

This specification does not define how the implementation locates a package given its name and version. If several matching versions of a package are available, it does not define which of them is chosen. 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 dereferenceable URI is not recommended, because the intent of the packaging feature is to allow a package to be distributed as reusable code and therefore to exist in many different locations.

[ERR XTSE3000] It is a static error if no package matching the package name and version specified in an xsl:use-package declaration can be located.

[ERR XTSE3005] It is a static error if a package is dependent on itself, where package A is defined as being dependent on package B if A contains an xsl:use-package declaration that references B, or if A contains an xsl:use-package declaration that references a package C that is itself dependent on B.

Note:

Depending on the implementation architecture, there may be a need to locate used packages both during static analysis (for example, to get information about the names and type signatures of the components exposed by the used package), and also at evaluation time (to link to the implementation of these components so they can be invoked). A failure to locate a package may cause an error at either stage.

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.5.3.2 Accepting Components below.

3.5.3 Named Components in Packages

This section discusses the use of named components in packages.

The components which can be declared in one package and referenced in another are: functions, named templates, attribute sets, modes, and global variables and parameters.

In addition, keys and accumulators are classified as named components because they can contain references to components in another package, even though they cannot themselves be referenced from outside the package.

Named and unnamed modes come within the scope of this section, but there are differences noted in 3.5.4 Overriding Template Rules from a Used Package.

Not all declarations result in components:

  • Named declarations that can neither be referenced from outside their containing package, nor can contain references to components in other packages (examples are xsl:output, xsl:character-map, and xsl:decimal-format) are not considered to be components and are therefore outside the scope of this section.

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

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

  • A named declaration, for example a named template, a function, or a global variable, may be overridden within the same package by another like-named declaration having higher import precedence. When a declaration is overridden in this way it cannot be referenced by name either from within its containing package or from outside that package; it can however be referenced from the overriding declaration using the special name xsl:original, as described in 3.5.3.4 Referring to Overridden Components.

  • In the case of xsl:attribute-set and xsl:key declarations, several declarations combine to form a single component.

The section is largely concerned with details of the rules that affect references from one component to another by name, whether the components are in the same package or in different packages. The rules are designed to meet a number of requirements:

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

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

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

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

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

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

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

Note:

In the case of the unnamed mode, the expanded QName of the component may be considered to be some system-allocated name different from any user-defined mode name.

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

Every component has a declaration in some stylesheet module and therefore within some package. In the case of attribute sets and keys, there may be several declarations. The declaration is an element in an XDM tree representing the stylesheet module. Declarations therefore have identity, based on XDM node identity.

[Definition: The declaring package of a component is the package that contains the declaration (or, in the case of xsl:attribute-set and xsl:key, multiple declarations) of the component.]

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

[Definition: A component declaration results in multiple components, one in the package in which the declaration appears, and potentially one in each package that uses the declaring package, directly or indirectly, subject to the visibility of the component. Each of these multiple components has the same declaring package, but each has a different containing package. For the original component, the declaring package and the containing package are the same; for a copy of a component made as a result of an xsl:use-package declaration, the declaring package will be the original package, and the containing package will be the package in which the xsl:use-package declaration appears.]

Note:

Within this specification, we generally use the notation CP for a component named C whose declaring package and containing package are both P; and the notation CPQ for a component whose containing package is P and whose declaring package is Q (that is, a component in P that is derived from a component CQ in the used package Q).

The properties of a component are as follows:

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 explicit or implicit mode attribute of xsl:apply-templates; XPath variable references referring to global variables; XPath static function calls (including partial function applications) referring to stylesheet functions; and named function references (example: my:f#1) referring to stylesheet functions. .]

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

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

For example, suppose that in some package Q, function A calls B, which in turn calls C, and that B is private. Now suppose that in some package P which uses Q, C is overridden. The effect of the binding process is that P will contain three components corresponding to A, B, and C, which we might call AP, BP, and CP. The declarations of AP and BP are in package Q, but the declaration of CP is in P. The internal visibility of BP will be hidden (meaning that it cannot be referenced from within P), and BP will contain a binding for the component CP that corresponds to the outward reference from B to C. The effect is that when A calls B and B calls C, it is the overriding version of C that is executed.

In another package R that uses Q without overriding C, there will be three different components AR, BR, and CR. This time the declaration of all three components is in the original package Q. Component BR will contain a binding to CR, so in this package, the original version of C is executed. The fact that one package P overrides C thus has no effect on R, which does not override it.

The binding process outlined above is described in more detail in 3.5.3.5 Binding References to Components.

Template rules are not components in their own right; unlike named templates, they are never referenced by name. Component references within a template rule (for example, references to functions, global variables, or named templates) are treated as occurring within the component that represents the containing mode. This includes component references within the match patterns of template rules. If a template rule lists several modes, it is treated as if there were multiple template rules one in each mode.

An xsl:apply-templates instruction with no mode attribute is treated as a reference to the default mode defined for that instruction (see 3.7.2 The default-mode Attribute), which in turn defaults to the unnamed mode. An implicit reference to the unnamed made is treated in the same way as any other symbolic reference. Note that there is an unnamed mode in every package, and the unnamed mode always has private visibility.

Where an xsl:template element has both a name and a match attribute, it is treated as if there were two separate xsl:template elements, one with a name attribute and one with a match attribute.

Keys and accumulators behave rather differently from other components. Their visibility is always private, which means they can only be used within their declaring package. In addition, the component binding is generally made dynamically rather than statically, by virtue of a string passed as an argument to the function key, accumulator-before, or accumulator-after. (In the case of accumulators, there can also be static references: see the use-accumulators attribute of xsl:stream.) However, outward references from key definitions and accumulators to other components (such as global variables and functions) behave in the same way as component references contained in any other private component, in that they may be re-bound to an overriding declaration of the target component.

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

VisibilityMeaning
publicThe 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.
privateThe component can be referenced from other components in this package; it cannot be referenced or overridden within a using package.
abstractThe 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.
finalThe 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.
hiddenThe component cannot be referenced from other components in this package; it cannot be referenced or overridden within a using package.

Note:

The visibility of a component in a package P primarily affects how the component can be used in other packages, specifically, packages that use P. There is one exception: if the visibility is hidden, it also affects how the component can be used within P.

When a component is declared within a particular package, its visibility, which affects how it can be used in other (using) packages, depends on two factors: the value of the visibility declaration on the declaration itself (if present), and the rules given in the xsl:expose declarations of the package manifest.

The xsl:function, xsl:template, xsl:attribute-set, xsl:variable, and xsl:mode declarations each have an optional visibility attribute. The value is one of private, public, abstract, or final (never hidden).

Any xsl:expose declarations that appear as children of xsl:package define the visibility of components whose declaration has no explicit visibility attribute, and can also be used to reduce the visibility of components where this attribute is present.

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

The xsl:expose element allows the visibility of selected components within a package to be defined.

The components in question are identified using their symbolic identifiers. The component attribute defines the kind of component that is selected. The 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 of a named template, function, variable, attribute set, or mode declared within a package is the first of the following that applies, subject to consistency constraints which are defined below:

  1. If the package manifest contains an xsl:expose element that matches this component by virtue of an explicit EQName or NamedFunctionRef (that is, not by virtue of a wildcard match), then the value of the visibility attribute of the last such xsl:expose element in document order (call this the explicit exposed visibility).

  2. If the declaration of the component has a visibility attribute, then the value of this attribute (call this the declared visibility).

  3. If the package manifest contains an xsl:expose element that matches this component by virtue of a wildcard match that specifies either the namespace part of the component name or the local part of the name (for example, prefix:* or *:local or Q{uri}*), then the value of the visibility attribute of the last such xsl:expose element in document order.

  4. If the package manifest contains an xsl:expose element that matches this component by virtue of a wildcard match that matches all names (that is, *), then the value of the visibility attribute of the last such xsl:expose element in document order.

  5. Otherwise, private.

If both a declared visibility and an explicit exposed visibility exist for the same component, then as mentioned above, they must be consistent. This is determined by reference to the following table, where the entry N/P means “not permitted”. (In cases where the combination is permitted, the actual visibility is always the same as the visibility determined by xsl:expose.)

Explicit exposed visibilityDeclared visibility
publicprivatefinalabstract
publicpublicN/PN/PN/P
privateprivateprivateprivateN/P
finalfinalN/PfinalN/P
abstractN/PN/PN/Pabstract

[ERR XTSE3010] It is a static error if the explicit exposed visibility of a component is inconsistent with its declared visibility, as defined in the above table. (This error occurs only when the component declaration has an explicit visibility attribute, and the component is also listed explicitly by name in an xsl:expose declaration.)

[ERR XTSE3020] It is a static error if a token in the names attribute of xsl:expose, other than a wildcard, matches no component in the containing package.

Note:

There is no ambiguity, and no error, if several tokens within the same xsl:expose element match the same component.

If the visibility of a component as established by the above rules is abstract, then the component must have a declared visibility of abstract.

Note:

In other words, the xsl:expose declaration cannot be used to make a component abstract unless it was declared as abstract to start with.

[ERR XTSE3025] It is a static error if the effect of an xsl:expose declaration would be to make a component abstract, unless the component is already abstract in the absence of the xsl:expose declaration.

For a component accepted into a package P from another package Q, the visibility of the component in P (which primarily affects how it can be used in a package R that uses P) depends on the visibility declared in the relevant xsl:accept or xsl:override element in P (see 3.5.3.2 Accepting Components); this in turn has a default that depends on the visibility of the corresponding component in Q. In this case the visibility is unaffected by any xsl:expose declaration in P.

3.5.3.2 Accepting Components

When a package P uses a package Q, by virtue of an xsl:use-package element in the package manifest of P, then P will contain a component corresponding to every component in Q. The visibility of the component within P depends on the visibility of the component in Q, 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 CQ in package Q that is not matched by any xsl:override or xsl:accept element in the package manifest of P, there will be a corresponding component CP in package P that has the same symbolic identifier and declaration as CQ. The visibility of CP will be the same as the visibility of CQ, except that where the visibility of CQ is private, the visibility of CP will be hidden.

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

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

The xsl:accept element has very similar syntax and semantics to xsl:expose. 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 a token in the names attribute of xsl:accept, other than a wildcard, matches no component in the used package.

In the absence of a matching xsl:override element (see 3.5.3.3 Overriding Named Components from a Used Package), the 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 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 elementVisibility in used package
publicprivatefinalabstract
publicpublicN/PN/PN/P
privateprivateN/PprivateN/P
finalfinalN/PfinalN/P
abstractN/PN/PN/Pabstract
hiddenhiddenN/PhiddenN/P
absentN/PN/PN/Pabsent

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

  3. If a component is explicitly accepted from a used package (by name, rather than by a matching wildcard, and if the same component is the subject of an xsl:override declaration, then a static error occurs (see below). There is no conflict, however, if a component declared within xsl:override also matches a wildcard in an xsl:accept element.

    [ERR XTSE3051] It is a static error if a token in the names attribute of xsl:accept, other than a wildcard, matches the symbolic name of a component declared within an xsl:override child of the same xsl:use-package element.

The value visibility="absent" may be used only in the case of a component that is present in the used package with exposed visibility abstract. It is used to indicate that the using package does not intend to provide an implementation of the abstract component, and that any invocation of the abstract component is therefore to result in an error. Specifically:

  1. Any component reference to the component within the using package is a static error, as if the component were hidden: in effect, the name of the component is not in scope in the using package.

  2. Any invocation of the absent component (typically from within its declaring package) causes a dynamic error, as if the component were overridden by a component that unconditionally raises a dynamic error.

    [ERR XTDE3052] It is a dynamic error if an invocation of an absent component (that is, an abstract component accepted into a using package with visibility="absent") is evaluated.

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

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

Note:

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

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

The using package P will also contain a component CPQ whose body is the same as the body of CQ and whose visibility is hidden. This component is used as the target of a binding for the symbolic reference xsl:original described below.

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

The rules in the remainder of this section apply to components having a name attribute (named components). The only element with no name attribute that can appear as a child of xsl:override is an xsl:template declaration having a match attribute (that is, a template rule). The rules for overriding of template rules appear in 3.5.4 Overriding Template Rules from a Used Package. If an xsl:template element has both a name attribute and a match attribute, then it defines both a named component and a template rule, and both sections apply.

The visibility of the overriding component in the using package is defined by the visibility attribute appearing on the overriding declaration, except in the case of xsl:param, which is implicitly public.

[ERR XTSE3055] It is a static error if a component declaration appearing as a child of xsl:override is homonymous with any other declaration in the using package, regardless of import precedence, including any other overriding declaration in the package manifest of the using package.

Note:

When an attribute set is overridden, the overriding attribute set must be defined using a single xsl:attribute-set element. Attribute sets defined in different packages are never merged by virtue of having the same name, though they may be merged explicitly by using the use-attribute-sets attribute.

[ERR XTSE3058] It is a static error if a component declaration appearing as a child of xsl:override does not match (is not homonymous with) some component in the used package.

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

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

Note:

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

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

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

Compatibility is only relevant when comparing two components that have the same symbolic identifier. The compatibility rules for each kind of component are as follows:

  • Two attribute sets with the same name are compatible if and only if they satisfy the following rule:

    1. If the overridden attribute set specifies streamable="yes" then the overriding attribute set also specifies streamable="yes".

  • Two functions with the same name and arity are compatible if and only if they satisfy all the following rules:

    1. The types of the arguments are pairwise identical.

    2. The return types are identical.

    3. The effective value of the new-each-time attribute on the overriding function is the same as its value on the overridden function.

    4. If the overridden function specifies streamable="yes" then the overriding function also specifies streamable="yes", and in addition, it has the same posture and sweep as the function that it overrides.

  • Two named templates with the same name are compatible if and only if they satisfy all the following rules:

    1. Their return types are identical.

    2. For every parameter on the overridden template, there is a parameter on the overriding template that has the same name, an identical required type, and the same effective values for the tunnel and required attributes.

    3. Any parameter on the overriding template for which there is no corresponding parameter on the overridden template specifies required="no".

    4. The two templates have equivalent xsl:context-item children, where equivalence means that the use attributes are the same and the required types are identical; an absent xsl:context-item is equivalent to one that specifies use="optional" and as="item()".

  • Two variables (including parameters) with the same name are compatible if and only if they satisfy all the following rules:

    1. Their declared types are identical.

    Note:

    A variable may override a parameter or vice-versa, and the initial value may differ.

    Because static variables and parameters are constrained to have visibility private , they cannot be overridden in another package. The compatibility rules therefore do not arise. The reason that such variables cannot be overridden is that they are typically used during stylesheet compilation (for example, in [xsl:]use-when expressions and shadow attributes) and it is a design goal that packages should be capable of independent compilation.

[Definition: Types S and T are considered identical for the purpose of these rules if and only if subtype(S, T) and subtype(T, S) both hold, where the subtype relation is defined in Section 2.5.6.1 The judgement subtype(A, B) XP30.]

Note:

  1. One consequence of this rule is that two plain union types are considered identical if they have the same set of member types, even if the union types have different names or the ordering of the member types is different.

  2. While this rule may appear formal, it is not as straightforward as might be supposed, because the subtype relation in XPath has a dependency on the “Type derivation OK (Simple)” relation in XML Schema, which itself appeals to a judgement as to whether the two type definitions being compared “are the same type definition”. Both XSD 1.0 and XSD 1.1 add the note “The wording of [this rule] appeals to a notion of component identity which is only incompletely defined by this version of this specification.” However, they go on to say that component identity is well defined if the components are named simple type definitions, which will always apply in this case. For named atomic types, the final result of these rules is that two atomic types are identical if and only if they have the same name.

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

3.5.3.4 Referring to Overridden Components

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

  • Within a named template appearing as a child of xsl:override, the name xsl:original may appear as the value of the name attribute of xsl:call-template: for example, <xsl:call-template name="xsl:original"/>.

  • Within a stylesheet function appearing as a child of xsl:override, the static context for contained XPath expressions (other than static expressions) is augmented as follows: the statically known function signatures includes a mapping from the name xsl:original to the signature of the overridden function (which is the same as the signature of the overriding function). This means that the name xsl:original can be used in static function calls, including calls that use partial function application (where one of the arguments is given as "?"), and also in named function references. For example: xsl:original($x), xsl:original($x, ?), xsl:original#2.

    Note:

    The result of calling function-name(xsl:original#2) is the name of the overridden function, not xsl:original.

    Neither xsl:original, nor the overridden function, is added to the named functions component of the dynamic context for XPath expressions within the overriding function. This means that any attempt to bind the function name xsl:original dynamically (for example using function-lookupFO30, or function-available, or xsl:evaluate) will fail, and any attempt to bind the name of the overriding/overridden function dynamically will return the overriding function.

  • Within a global variable or parameter appearing as a child of xsl:override, the static context for contained XPath expressions (other than static expressions) is augmented as follows: the in-scope variables includes a mapping from the name xsl:original to the declared type of the overridden variable or parameter (which is the same as the type of the overriding global variable or parameter).

  • Within an attribute set appearing as a child of xsl:override, any [xsl:]use-attribute-sets attribute (whether on the xsl:attribute-set element itself, or on any descendant element) may include the name xsl:original as a reference to the overridden attribute set.

Within the overriding component CP, the symbolic reference xsl:original is bound to the hidden component CPQ described earlier, whose body is that of the component CQ in the used package.

[ERR XTSE3075] It is a static error to use the component reference xsl:original when the overridden component has visibility="abstract".

Modes are not overridable, so the name xsl:original cannot be used to refer to a mode (for example in the mode attribute of xsl:apply-templates).

Note:

In the case of variables, templates, and attribute sets, the invocation of the overridden component can occur only within the lexical scope of the overriding component. With functions, however, there is greater flexibility. The overriding component can obtain a reference to the overridden component in the form of a function item, and can export this value by passing it to other functions or returning it in its result. A dynamic invocation of this function item (and hence, of the overridden function) can thus occur anywhere.

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

The process of reference binding in the presence of overriding declarations is best illustrated by an example. The formal rules follow later in the section.

Example: Binding References to Named Components

Consider a package Q defined as follows:

<xsl:package name="Q" 
        xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <xsl:variable name="A" visibility="final" select="$B + 1"/>
  <xsl:variable name="B" visibility="private" select="$C * 2"/>
  <xsl:variable name="C" visibility="public" select="22"/>
</xsl:package>

(The process is illustrated here using variables as the components, but the logic would be the same if the example used functions, named templates, or attribute sets.)

There are three components in this package, and their properties are illustrated in the following table. (The ID column is an arbitrary component identifier used only for the purposes of this exposition.)

IDSymbolic NameDeclaring PackageContaining PackageVisibilityBodyBindings
AQvariable AQQfinal$B + 1$B → BQ
BQvariable BQQprivate$C * 2$C → CQ
CQvariable CQQpublic22none

Now consider a package P that uses Q, and that overrides one of the variables declared in Q:

<xsl:package name="P" 
        xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <xsl:use-package name="Q">
    <xsl:override>
      <xsl:variable name="C" visibility="private" select="$xsl:original + 3"/>
    </xsl:override>
  </xsl:use-package>
  
  <xsl:template name="T" visibility="public">
    <xsl:value-of select="$A"/>
  </xsl:template>
</xsl:package>

Package P has five components, whose properties are shown in the following table:

IDSymbolic NameDeclaring PackageContaining PackageVisibilityBodyBindings
APQvariable AQPfinal$B + 1$B → BPQ
BPQvariable BQPhidden$C * 2$C → CP
CPQvariable CQPhidden22none
CPvariable CPPpublic$xsl:original + 3$xsl:original → CPQ
TPtemplate TPPpublicvalue-of select="$A$A → APQ

The effect of these bindings is that when template T is called, the result is 51. This is why:

  1. The result of T is the value of APQ.

  2. The value of APQ is the value of BPQ plus 1.

  3. The value of BPQ is the value of CP times 2.

  4. The value of CP is the value of CPQ plus 3.

  5. The value of CPQ is 22.

  6. So the final result is ((22 + 3) * 2) + 1

In this example, the components of P are established in three different ways:

  1. Components APQ, BPQ, and CPQ are modified copies of the corresponding component AQ, BQ, and CQ in the used package Q. The properties of these components are modified as follows:

    1. The symbolic identifier, declaring package, and body are unchanged.

    2. The containing package is changed to P.

    3. The visibility is changed according to the rules in 3.5.3.2 Accepting Components: in particular, visibility="private" changes to visibility="hidden".

    4. The references to other components are rebound as described in this section.

  2. Component CP is the overriding component. Its properties are exactly as if it were declared as a top-level component in P (outside the xsl:use-package element), except that (a) it must adhere to the constraints on overriding components (see 3.5.3.3 Overriding Named Components from a Used Package), (b) it is allowed to use the variable reference $xsl:original, and (c) the fact that it overrides CQ affects the way that references from other components are rebound.

  3. Component TP is a new component declared locally in P.

The general rules for reference binding can now be stated:

  1. If the containing package of a component CP is P, then all symbolic references in CP are bound to components whose containing package is P.

  2. When a package P uses a package Q, then for every component CQ in Q, there is a corresponding component CP in P, as described in 3.5.3.2 Accepting Components.

  3. Given a component CP whose containing package and declaring package are the same package P, then (as a consequence of rules elsewhere in this specification) for every symbolic reference D within CP, other than a reference using the name xsl:original, there will always be exactly one non-hidden component DP whose containing package is P and whose symbolic identifier matches D (otherwise a static error will have been reported). The reference is then bound to DP.

  4. In the case of a component reference using the name xsl:original, this will in general appear within a component CP that overrides a component CQ whose corresponding component in P is CPQ, and the xsl:original reference is bound to CPQ.

  5. Given a component CP whose containing package P is a different package from its declaring package R (that is, CP is present in P by virtue of an xsl:use-package declaration referencing package Q, which may or may not be the same as R), then the component bindings in CP are derived from the component bindings in the corresponding component CQ as follows: if the component binding within CQ is to a component DQ, then:

    1. If DQ is overridden within P by a component DP, then the reference is bound to DP;

    2. Otherwise, the reference is bound to the component DPQ in P whose corresponding component in Q is DQ.

When reference resolution is performed on a package that is intended to be used as a stylesheet (that is, for the top-level package), there must be no symbolic references referring to components whose visibility is abstract (that is, an implementation must be provided for every abstract component).

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

Note:

This means that abstract components must either be overridden in a using package either by a component that supplies a real implementation, or they must be accepted with visibility="absent" (see 3.5.3.2 Accepting Components), which has the effect that any invocation of the component raises a dynamic error.

Note:

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

Note:

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

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

The mechanism for resolving component references described in this section is consistent with the mechanism used for binding function and variable references described in the XPath specification. XPath requires these variable and function names to be present in the static context for an XPath expression. XSLT ensures that all the non-hidden functions, global variables, and global parameters in a package are present in the static context for every XPath expression that appears in that package, along with required information such as the type of a variable and the signature of a function.

3.5.3.6 Dynamic References to Components

There are several functions in which a dynamically-evaluated QName is used to identify a component: these include key, accumulator-before, accumulator-after, function-lookupFO30, and function-available. Dynamic references can also occur in the XPath expression supplied to the xsl:evaluate instruction.

In all these cases, the set of components that are available to be referenced are those that are declared in the package where this function call appears, including components declared within an xsl:override declaration in that package, but excluding components declared with visibility="abstract". If the relevant component has been overridden in a different package, the overriding declarations are not considered.

If one of these functions (for example key or accumulator-before) is invoked via a dynamic function invocation, then the relevant package is the one in which the function item is created (using a construct such as key#2, key('my-key', ?), or function-lookup($KEYFN, 2). (Function items referring to context-dependent functions bind the context at the point where the function item is created, not the context at the point where the function item is invoked.)

Note:

This means that if a package wishes to make a key available for use by a calling package, it can do so by creating a public global variable whose value is a partial application of the key function:

<xsl:variable name="get-order" select="key('orders-key', ?, ?)"/>

which the calling code can invoke as $get-order('123-456', /).

3.5.4 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. An xsl:apply-templates instruction with no mode attribute is treated as a symbolic reference to the default mode defined for that instruction (see 3.7.2 The default-mode Attribute), which in turn defaults to the unnamed mode. Because the unnamed mode always has private visibility, it cannot be overridden in another package.

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

ValueMeaning
publicA 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.
privateA 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.
finalA using package may use xsl:apply-templates to invoke templates in this mode, but it must not provide additional template rules in this mode.

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

The xsl:mode declaration itself must not be overridden. A using package must not contain an xsl:mode declaration whose name matches that of a public or 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 import precedence and priority operate as normal, with the addition that template rules declared within an xsl:use-package element have higher precedence than any template rule declared in the used package. More specifically, given an xsl:apply-templates instruction in package P, naming a mode M that is declared in a used package Q and is overridden in P, the search order for template rules is:

  1. Rules declared within P (specifically, xsl:template rules declared as children of an xsl:override element within the xsl:use-package element that references package Q). If there are multiple rules declared within P that match a selected node, they are resolved on the basis of their explicit or implicit priority, and if the priorities are equal, the last one in declaration order wins.

  2. Rules declared within Q, taking import precedence, priority, and declaration order into account in the usual way (see 6.4 Conflict Resolution for Template Rules).

  3. Built-in template rules (see 6.7 Built-in Template Rules) selected according to the on-no-match attribute of the xsl:mode declaration (in Q), or its default.

If the mode is overridden again in a package R that uses P, then this search order is extended by adding R at the start of the search list, and so on recursively.

Note:

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

3.5.4.1 Requiring Explicit Mode Declarations

In previous versions of XSLT, modes were implicitly declared by simply using a mode name in the mode attribute of xsl:template or xsl:apply-templates. XSLT 3.0 introduces the ability to declare a mode explicitly using an xsl:mode declaration (see 6.6.1 Declaring Modes).

By default, within a package that is defined using an explicit xsl:package element, all modes must be explicitly declared. In an implicit package, however (that is, one rooted at an xsl:stylesheet or xsl:transform element), modes can be implicitly declared as in previous XSLT versions.

The declared-modes attribute of xsl:package determines whether or not modes that are referenced within the package must be explicitly declared. If the value is yes (the default), then it is an error to use a mode name unless the package either contains an explicit xsl:mode declaration for that mode, or accepts the mode from a used package. If the value is no, then this is not an error.

This attribute affects all modules making up the package, it is not confined to declarations appearing as children of the xsl:package element.

[ERR XTSE3085] It is a static error, when the effective value of the declared-modes attribute of an xsl:package element is yes, if the package contains an explicit reference to an undeclared mode, or if it implicitly uses the unnamed mode and the unnamed mode is undeclared. A mode is declared if the package contains an xsl:mode declaration for that mode, or if the mode is a public or final mode accepted from a used package. The offending reference may occur in the mode attribute of an xsl:template or xsl:apply-templates instruction, or in an [xsl:]default-mode attribute. The offending reference may be either an explicit mode name, or the token #unnamed treated as a reference to the unnamed mode. A package implicitly uses the unnamed mode if there is an xsl:template or xsl:apply-templates element with no mode attribute, and with no ancestor-or-self having an [xsl:]default-mode attribute.

3.5.5 Declarations Local to a Package

The xsl:import and xsl:include declarations are local to a package.

Declarations of keys, accumulators, decimal formats, namespace aliases (see 11.1.4 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 top-level package additionally affects stripping of whitespace in the document that contains the global context item.

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

An xsl:namespace-alias declaration 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.5.6 Declaring the Global Context Item

The xsl:global-context-item element is used to declare whether a global context item is required, and if so, what its required type is.

The element is a declaration that can appear at most once in any stylesheet module; and if more than one xsl:global-context-item declaration appears within a package, then the declarations must be consistent. Specifically, all the attributes must have semantically-equivalent values.

Note:

This means that omitting an attribute is equivalent to specifying its default value explicitly; and purely lexical variations, such as the order of names or choice of prefixes in the use-accumulators attribute, are not considered significant.

[ERR XTSE3087] It is a static error if more than one xsl:global-context-item declaration appears within a stylesheet module, or if several modules within a single package contain inconsistent xsl:global-context-item declarations

If there is no xsl:global-context-item declaration for a package, this is equivalent to specifying the empty element <xsl:global-context-item/>, which imposes no constraints.

<!-- Category: declaration -->
<xsl:global-context-item
  as? = item-type
  use? = "required" | "optional" | "absent"
  streamable? = boolean
  use-accumulators? = tokens />

The use attribute takes the value required, optional, or absent. The default is optional.

  • If the value required is specified, then there must be a global context item.

  • If the value optional is specified, or if the attribute is omitted, or if the xsl:global-context-item element is omitted, then there may or may not be a global context item.

  • If the value absent is specified, then the global focus (context item, position, and size) will be absent

    Note:

    This specification does not define whether supplying a global context item in this situation results in an error or warning, or whether the supplied context item is simply ignored.

If the as attribute is present then its value must be an ItemTypeXP30. If the attribute is omitted this is equivalent to specifying as="item()".

The as attribute defines the required type of the global context item. The default value is as="item()". If a global context item is supplied then it must conform to the required type, after conversion (if necessary) using the function conversion rules.

[ERR XTSE3089] It is a static error if the as attribute is present when use="absent" is specified.

If the streamable attribute is present with the value yes, then the select expression or contained sequence constructor of every global xsl:variable and xsl:param declaration in the containing package must be grounded and motionless, when assessed with a context posture of striding, and a context item type based on the declared type of the global context item. The consequences of violating this rule depend on the conformance level of the processor, as described in 19.10 Streamability Guarantees.

If the streamable attribute is absent or has the value no, or if there is no xsl:global-context-item declaration, then when the transformation is primed, the item supplied as the global context item cannot be a node in a streamed document (the transformation API may handle this either by disallowing such an input, or by building the corresponding tree in memory and supplying the global context item as an unstreamed node.)

The use-accumulators attribute defines which accumulators are available with the document containing the global context item. Details are given in 18.2.2 Applicability of Accumulators.

The global context item is available only within the top-level package. If an xsl:global-context-item declaration appears within a library package, then it is ignored, unless it specifies use="required", in which case an error is signaled: [see ERR XTTE0590].

Note:

Use of a global context item is not encouraged, especially in a complex stylesheet made up of several packages. There is only one global context item shared between all packages, which does not work well when multiple packages are developed independently. Named stylesheet parameters, perhaps in distinct namespaces, are more flexible.

A type error is signaled if there is a package with an xsl:global-context-item declaration specifying a required type that does not match the supplied global context item. The error code is the same as for xsl:param: [see ERR XTTE0590].

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.

3.5.7 Worked Example of a Library Package

The example in this section illustrates the use of overrides to customize or extend a (fictional) library package named http://example.com/csv-parser, which provides a parsing function for data formatted as lines containing comma-separated values. For simplicity of exposition, the example shows a simple, naive implementation; a realistic CSV parser would be more complicated and make the example harder to follow.

3.5.7.1 Default Functionality of the CSV Package

The basic functionality of the package is provided by the function csv:parse, which expects a string parameter named input. By default, the function parses the input into lines, and breaks lines on commas, returning as result an element named csv containing one row element per line, each row containing a sequence of field elements.

A simple stylesheet which uses this library and applies it to a string might look like the following. The initial template applies csv:parse to a suitable string and returns a copy of the result:

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
   xmlns:xs="http://www.w3.org/2001/XMLSchema"
   xmlns:csv="http://example.com/csv"
   exclude-result-prefixes="xs csv"
   version="3.0">

   <xsl:output indent="yes" />

   <xsl:use-package name="http://example.com/csv-parser" 
                    package-version="*" />

   <!-- example input "file"  -->
   <xsl:variable name="input" as="xs:string">
       name,id,postal code
       "Abel Braaksma",34291,1210 KA
       "Anders Berglund",473892,9843 ZD
   </xsl:variable>

   <!-- entry point -->
   <xsl:template name="xsl:initial-template">
       <xsl:copy-of select="csv:parse($input)" />
   </xsl:template>

</xsl:stylesheet>

The result returned by this stylesheet would be:

<csv>
  <row>
    <field quoted="no">name</field>
    <field quoted="no">id</field>
    <field quoted="no">postal code</field>
  </row>
  <row>
    <field quoted="yes">Abel Braaksma</field>
    <field quoted="no">34291</field>
    <field quoted="no">1210 KA</field>
  </row>
  <row>
    <field quoted="yes">Anders Berglund</field>
    <field quoted="no">473892</field>
    <field quoted="no">9843 ZD</field>
  </row>
</csv>

Variations on this default behavior are achieved by overriding selected declarations in the package, as described below.

3.5.7.2 Package Structure

The package module itself is version 1.0.0 of a package called http://example.com/csv-parser; it has the following structure:

<?xml version="1.0" encoding="UTF-8"?>
<xsl:package
   name="http://example.com/csv-parser"
   package-version="1.0.0"
   xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
   xmlns:xs="http://www.w3.org/2001/XMLSchema"
   xmlns:csv="http://example.com/csv"
   exclude-result-prefixes="xs csv"
   declared-modes="yes"
   version="3.0">

   <!--* Mode declarations ... *-->
   <!--* Variable declarations ... *-->
   <!--* Attribute-set declaration ... *-->
   <!--* Function declarations ... *-->
   <!--* Templates ... *-->

</xsl:package>

The contents of the package (represented here by comments) are described more fully below.

3.5.7.3 The csv:parse Function and its User-customization Hooks

The csv:parse function is final and cannot be overriden. As can be seen from the code below, it (1) parses its input parameter into lines, (2) calls function csv:preprocess-line on each line, then (3) applies the templates of mode csv:parse-line to the pre-processed value. The result is then (4) processed again by mode csv:post-process.

<xsl:function name="csv:parse" visibility="final">
    <xsl:param name="input" as="xs:string" />   
    <xsl:variable name="result" as="element()">
        <csv>
            <xsl:apply-templates 
                select="(tokenize($input, $csv:line-separator) 
                        ! csv:preprocess-line(.))" 
                mode="csv:parse-line" />
        </csv>
    </xsl:variable>
    <xsl:apply-templates select="$result" 
                         mode="csv:post-process" />
</xsl:function>

The default code for this processing is given below. Each part of the processing except the first (the tokenization into lines) can be overridden by the user of the package.

3.5.7.4 Breaking the Input into Lines

The first user-customization hook is given by the global variable csv:line-separator, which specifies the line separator used to break the input string into lines. It can be overridden by the user if need be. The default declaration attempts to handle the line-separator sequences used by most common operating systems in text files:

<xsl:variable name="csv:line-separator" 
              as="xs:string" 
              select="'\r\n?|\n\r?'" 
              visibility="public"/>
3.5.7.5 Pre-processing the Lines

The function csv:preprocess-line calls normalize-space() on its argument:

<xsl:function name="csv:preprocess-line" 
                 as="xs:string?" 
                 visibility="public">
    <xsl:param name="line" as="xs:string" />
    <xsl:sequence select="normalize-space($line)" />
</xsl:function>

Because the function is declared public, it can be overridden by a user. (This might be necessary, for example, if whitespace within quoted strings needs to be preserved.)

3.5.7.6 The Mode csv:parse-line

By default, the mode csv:parse-line parses the current item (this will be one line of the input data) into fields, using mode csv:parse-field on the individual fields and (by default) wrapping the result in a row element.

The mode is declared with visibility="public" to allow it to be called from elsewhere and overridden:

<xsl:mode name="csv:parse-line" visibility="public"/>
<xsl:template match="." mode="csv:parse-line">
    <row>
        <xsl:apply-templates 
            select="tokenize(., $csv:field-separator)" 
            mode="csv:parse-field" />
    </row>
</xsl:template>

This relies on the variable csv:field-separator, which is a comma by default but which can be overridden by the user to parse tab-separated data or data with other delimiters.

<xsl:variable name="csv:field-separator" 
              as="xs:string" 
              select="','" 
              visibility="public"/>

The default implementation of csv:parse-line does not handle occurrences of the field separator occurring within quoted strings. The user can add templates to the mode to provide that functionality.

3.5.7.7 Mode csv:parse-field

Mode csv:parse-field processes the current item as a field; by default it strips quotation marks from the value, calls the function csv:preprocess-field() on it, and wraps the result in a field element, which carries the attributes declared in the attribute set csv:field-attributes.

<xsl:template match="." 
              mode="csv:parse-field" 
              expand-text="yes">
    <xsl:variable name="string-body-pattern"
                  as="xs:string"
                  select="'([^' || $csv:validated-quote || ']*)'"/>
    <xsl:variable name="quoted-value"
                  as="xs:string"
                  select="$csv:validated-quote 
                          || $string-body-pattern 
                          || $csv:validated-quote"/>
    <xsl:variable name="unquoted-value"
                  as="xs:string"
                  select="'(.+)'"/>

    <field xsl:use-attribute-sets="csv:field-attributes">{
        csv:preprocess-field(
          replace(., 
                  $quoted-value || '|' || $unquoted-value, 
                  '$1$2'))
    }</field>
</xsl:template>

The attribute set csv:field-attributes includes, by default, a quoted attribute which has the values yes or no to show whether the input value was quoted or not.

<xsl:attribute-set name="csv:field-attributes" 
                   visibility="public">
    <xsl:attribute name="quoted" 
                   select="if (starts-with(., $csv:validated-quote)) 
                           then 'yes' 
                           else 'no'" />
</xsl:attribute-set>

The mode csv:parse-field is declared with visibility="public" to allow it to be called from elsewhere and overridden; it specifies on-no-match="shallow-copy" so that any string not matching a template will simply be copied:

<xsl:mode name="csv:parse-field"
          on-no-match="shallow-copy" 
          visibility="public"/>
3.5.7.8 The csv:quote Variable

The variable csv:quote can be used to specify the character used in a particular input stream to quote values.

<xsl:variable name="csv:quote" 
              as="xs:string" 
              select="'&quot;'" 
              visibility="public"/>

The template given above assumes that the variable is one character long. To ensure that any overriding value of the variable is properly checked, references to the value use a second variable csv:validated-quote, which is declared private to ensure that the checking cannot be disabled.

<xsl:variable name="csv:validated-quote" visibility="private"
   as="xs:string" select="
       if (string-length($csv:quote) ne 1) 
       then error(xs:QName('csv:ERR001'), 
                  'Incorrect length for $csv:quote, should be 1') 
       else $csv:quote" />

When the value of csv:quote is not exactly one character long, the reference to csv:validated-quote will cause an error (csv:ERR001) to be raised.

3.5.7.9 The csv:preprocess-field Function

The function csv:preprocess-field is called on each field after any quotation marks are stripped and before it is written out as the value of a field element:

<xsl:function name="csv:preprocess-field" 
              as="xs:string">
    <xsl:param name="field" 
               as="xs:string" />
    <xsl:sequence select="$field" />
</xsl:function>

As can be seen, the function does nothing but return its input; its only purpose is to provide the opportunity for the user to supply a suitable function to be invoked at this point in the processing of each field.

3.5.7.10 The Mode csv:post-process

The mode csv:post-process is intended solely as a hook for user code. By default, it does nothing.

The package defines no templates for this mode; the mode definition makes it return a copy of its input:

<xsl:mode name="csv:post-process" 
          on-no-match="shallow-copy" 
          visibility="public"/>
3.5.7.11 Overriding the Default Behavior

As can be seen from the code shown above, the package provides several opportunities for users to override the default behavior:

  • The global variables csv:line-separator, csv:field-separator, and csv:quote can be overridden to specify the character strings used to separate lines and fields and to quote individual field values.

  • The function csv:preprocess-line can be overridden to do more (or less) than stripping white space; the function csv:preprocess-field can be overridden to process individual field values.

  • Templates can be added to the modes csv:parse-line, csv:parse-field, and csv:post-process to change their behavior.

  • The attribute set csv:field-attributes can be overridden to specify a different set of attributes (or none) for field elements.

The following using stylesheet illustrates the use of the xsl:override element to take advantage of several of these opportunities:

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

   <xsl:output indent="yes" />

   <xsl:use-package name="http://example.com/csv-parser" 
                    package-version="*">
       <xsl:override>
           <!-- Change the root element from 'csv' to 'root' -->
           <xsl:template match="csv" mode="csv:post-process">
               <root>
                   <xsl:apply-templates mode="csv:post-process" />
               </root>
           </xsl:template>

           <!-- add an extra attribute that uses the context item -->
           <xsl:attribute-set name="csv:field-attributes" 
                              use-attribute-sets="xsl:original">
               <xsl:attribute name="type" 
                              select="if (. castable as xs:decimal) 
                                      then 'numeric' 
                                      else 'string'" />
           </xsl:attribute-set>          

           <!-- use semicolon not comma between fields -->
           <xsl:variable name="csv:field-separator" 
                         as="xs:string" select="';'" 
                         visibility="public"/>

           <!-- prevent empty rows from appearing with empty lines -->
           <xsl:function name="csv:preprocess-line" 
                         as="xs:string?" 
                         visibility="public">
               <xsl:param name="line" as="xs:string" />
               <xsl:variable name="norm-line" 
                             select="normalize-space(xsl:original($line))" />
               <xsl:sequence select="if (string-length($norm-line) > 0) 
                                     then $norm-line 
                                     else ()" />
           </xsl:function>
       </xsl:override>
   </xsl:use-package>

   <!-- example input "file"  -->
   <xsl:variable name="input" as="xs:string">
       name;id;postal code
       "Braaksma Abel";34291;1210 KA
       "Berglund Anders";473892;9843 ZD
   </xsl:variable>

   <!-- entry point -->
   <xsl:template name="xsl:initial-template">
       <xsl:copy-of select="csv:parse($input)" />
   </xsl:template>

</xsl:stylesheet>

Note:

  • As it does elsewhere, the visibility of components declared within xsl:override defaults to private; to keep the component public, it is necessary to specify visibility explicitly.

  • The types and optionality of all function parameters must match those of the function being overridden; for function overriding to be feasible, packages must document the function signature thoroughly.

  • The names, types, and optionality of all named-template parameters must match those of the template being overridden; for overriding to be feasible, packages must document the template signature thoroughly.

  • The values for the attributes in the attribute set csv:field-attributes are calculated once for each element for which the attribute set is supplied; the select attributes which determine the values can thus refer to the context item. Here, the value specification for the type attribute checks to see whether the string value of the context item is numeric by inquiring whether it can be cast to decimal, and sets the value for the type attribute accordingly.

The result returned by this stylesheet would be:

<root>
  <row>
    <field quoted="no" type="string">name</field>
    <field quoted="no" type="string">id</field>
    <field quoted="no" type="string">postal code</field>
  </row>
  <row>
    <field quoted="yes" type="string">Braaksma Abel</field>
    <field quoted="no" type="numeric">34291</field>
    <field quoted="no" type="string">1210 KA</field>
  </row>
  <row>
    <field quoted="yes" type="string">Berglund Anders</field>
    <field quoted="no" type="numeric">473892</field>
    <field quoted="no" type="string">9843 ZD</field>
  </row>
</root>

3.6 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 [XDM 3.0]). In the case of a standard stylesheet module, this will be an xsl:stylesheet or xsl:transform element. In the case of a simplified stylesheet module, it can be any element (not in the XSLT namespace) that has an xsl:version attribute.

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

The principal stylesheet module of a package may take one of three forms:

A stylesheet module other than the principal stylesheet module of a package may take either of two forms:

Whichever of the above forms a module takes, the outermost element (xsl:package, xsl:stylesheet, or a literal result element) may either be the outermost element of an XML document, or it may be a child of some (non-XSLT) element in a host document.

[Definition: A stylesheet module whose outermost element is the child of a non-XSLT element in a host document is referred to as an embedded stylesheet module. See 3.12 Embedded Stylesheet Modules.]

3.7 Stylesheet Element

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

<xsl:transform
  id? = id
  version = decimal
  default-mode? = eqname | "#unnamed"
  default-validation? = "preserve" | "strip"
  input-type-annotations? = "preserve" | "strip" | "unspecified"
  default-collation? = uris
  extension-element-prefixes? = prefixes
  exclude-result-prefixes? = prefixes
  expand-text? = boolean
  use-when? = expression
  xpath-default-namespace? = uri >
  <!-- Content: (declarations) -->
</xsl:transform>

A stylesheet module is represented by an xsl:stylesheet element in an XML document. xsl:transform is allowed as a synonym for xsl:stylesheet; everything this specification says about the xsl:stylesheet element applies equally to xsl:transform.

The version attribute indicates the version of XSLT that the stylesheet module requires. The attribute is required.

[ERR XTSE0110] The value of the version attribute must be a number: specifically, it must be a valid instance of the type xs:decimal as defined in [XML Schema Part 2].

The version attribute is intended to indicate the version of the XSLT specification against which the stylesheet is written. In a stylesheet written to use XSLT 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.9 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.10 Forwards Compatible Processing).

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

The [xsl:]default-validation attribute defines the default value of the validation attribute of all relevant instructions appearing within its scope. For details of the effect of this attribute, see 25.4 Validation.

[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.3 Stripping Whitespace from the Stylesheet.)

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

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

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

xsl:accumulator
xsl:attribute-set
xsl:character-map
xsl:decimal-format
xsl:function
xsl:global-context-item
xsl:import
xsl:import-schema
xsl:include
xsl:key
xsl:mode
xsl:namespace-alias
xsl:output
xsl:param
xsl:preserve-space
xsl:strip-space
xsl:template
xsl:use-package
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.

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:

3.7.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, when it appears on an element E, is used to specify the default collation used by all XPath expressions appearing in attributes or text value templates that have E as an ancestor, 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 include as the last collation URI in the list either the Unicode Codepoint Collation or a collation in the UCA family (see 13.4 The Unicode Collation Algorithm) with the parameter fallback=yes.

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

In the absence of an [xsl:]default-collation attribute, the default collation may be set by the calling application in an implementation-defined way. The recommended default, unless the user chooses otherwise, is to use the Unicode codepoint collation.

3.7.2 The default-mode Attribute

The [xsl:]default-mode attribute defines the default value for the mode attribute of all xsl:template and xsl:apply-templates elements within its scope.

More specifically, when an element E matches the pattern (xsl:template[@match] | xsl:apply-templates)[not(@mode) or normalize-space(@mode) eq "#default"] (using the Unicode codepoint collation), then the effective value of the mode attribute is taken from the value of the [xsl:]default-mode attribute of the innermost ancestor-or-self element of E that has such an attribute. If there is no such element, then the default is the unnamed mode. This is equivalent to specifying #unnamed.

The value of the [xsl:]default-mode attribute must either be an EQName, or the token #unnamed which refers to the unnamed mode.

Note:

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

It is not necessary for the referenced mode to be explicitly declared in an xsl:mode declaration, unless this is mandated by the declared-modes attribute (which defaults to yes on an xsl:package element).

3.7.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.2 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,

3.8 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 match selection, to be matched by the implicit match="/" template rule using the unnamed mode.

3.9 Backwards Compatible Processing

[Definition: The effective version of an element in a stylesheet module or package manifest is the decimal value of the [xsl:]version attribute (see 3.4 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.9.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.9.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 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.0 declarations 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.9.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. Expressions contained in text value templates are always evaluated with XPath 1.0 compatibility mode set to false, since this construct was not available in XSLT 1.0.

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

Processing an instruction with XSLT 1.0 behavior is not compatible with streaming. More specifically, and notwithstanding anything stated in 19 Streamability, an instruction that is processed with XSLT 1.0 behavior is roaming and free-ranging, which has the effect that any construct containing such an instruction is not guaranteed-streamable.

3.9.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 specification, 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.10 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.13.1 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 a child of an element whose content model requires 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 23.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>

Note:

The XSLT 1.0 and XSLT 2.0 specifications did not anticipate the introduction of the xsl:package element. An XSLT 1.0 or 2.0 processor encountering this element will report a static error, regardless of the version setting.

This problem can be circumvented by using the simplified package syntax (whereby an xsl:stylesheet element is implicitly treated as xsl:package), or by writing the stylesheet code in a separate module from the package manifest, and using the separate module as the version of the stylesheet that is presented to a 2.0 processor.

3.11 Combining Stylesheet Modules

XSLT provides two mechanisms to construct a package from multiple stylesheet modules:

  • an inclusion mechanism that allows stylesheet modules to be combined without changing the semantics of the modules being combined, and

  • an import mechanism that allows stylesheet modules to override each other.

3.11.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 must be either a standard stylesheet module or a simplified stylesheet. It must not be a package manifest. If it is a simplified stylesheet module then it is transformed into the equivalent standard stylesheet module by applying the transformation described in 3.8 Simplified Stylesheet Modules.

Implementations may choose to accept URI references containing a fragment identifier defined by reference to the XPointer specification (see [XPointer Framework]). Note that if the implementation does not support the use of fragment identifiers in the URI reference, then it will not be possible to include an embedded stylesheet module.

[ERR XTSE0165] It is a static error if the processor is not able to retrieve the resource identified by the URI reference, or if the resource that is retrieved does not contain a stylesheet module.

Note:

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

3.11.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.11.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.11.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.11.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.11.1 Locating Stylesheet Modules.

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

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.12 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 it 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 [RFC7303].

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.3 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.13 Stylesheet Preprocessing

This specification provides two features that cause the raw stylesheet to be preprocessed as the first stage of static processing: elements may be conditionally included or excluded by means of an [xsl:]use-when attribute as described in 3.13.1 Conditional Element Inclusion, and attributes may be conditionally computed as described in 3.13.2 Shadow Attributes.

Note that many of the rules affecting the validity of stylesheet documents apply to a stylesheet after this preprocessing phase has been carried out.

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

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.3 Stripping Whitespace from the Stylesheet.

The XPath expression used as the value of the xsl:use-when attribute follows the rules for static expressions, including the rules for handling errors.

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

Example: Using Conditional Exclusion to Achieve Portability

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

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

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

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

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

 

Example: Including Variant Stylesheet Modules

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

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

3.13.2 Shadow Attributes

Wherever a no-namespace attribute is defined for an element in the XSLT namespace, instead of supplying the attribute value explicitly in the stylesheet, a shadow attribute may be supplied allowing the value of the attribute to be statically computed during the preprocessing phase. The shadow attribute has a name that is the same as the name of the target attribute prefixed with an underscore, and the value of the shadow attribute is a value template in which all expressions enclosed between curly braces must be static expressions.

For example, an xsl:include element might be written:

<xsl:include _href="common{$VERSION}.xsl"/>

allowing the stylesheet to include a specific version of a library module based on the value of a static parameter.

Similarly, a mode might be declared like this:

<xsl:param name="streamable" as="xs:boolean" 
                  required="yes" static="yes"/>
<xsl:mode _streamable="{$streamable}" on-no-match="shallow-skip"/>

this allowing the streamability of the mode to be controlled using a static parameter (Note: this example relies on the fact that the streamable attribute accepts a boolean value, which means that the values true and false are accepted as synonyms of yes and no).

This mechanism applies to all attributes in the stylesheet where the attribute name is in no namespace and the name of the parent element is in the XSLT namespace. This includes attributes that have static significance such as the use-when attribute, the version attribute, or the static attribute on xsl:variable. The mechanism does not apply to shadow attributes (that is, it is not possible to invoke two stages of preprocessing by using two leading underscores). It does not apply to attributes of literal result elements, nor to attributes in a namespace such as the XML or XSLT namespace, nor to namespace declarations.

If a shadow attribute and its corresponding target attribute are both present in the stylesheet, the non-shadow attribute is ignored.

Note:

This may be useful to make stylesheet code compatible across XSLT versions; an XSLT 2.0 processor operating in forwards compatible mode will ignore shadow attributes, and will require the target attribute to be valid.

Note:

The statement that the non-shadow attribute is ignored extends to error detection: it is not an error if the non-shadow attribute has an invalid value. However, this is not reflected in the schema for XSLT stylesheets, so validation using this schema may report errors in such cases.

Note:

An attribute whose name begins with an underscore is treated specially only when it appears on an element in the XSLT namespace. On a literal result element, it is treated in the same way as any other attribute (that is, its effective value is copied to the result tree). On an extension instruction or user-defined data element, as with other attributes on these elements, its meaning is entirely implementation-defined.

Example: Using Shadow Attributes to Parameterize XPath Default Namespace

Although it is not usually considered good practice, it sometimes happens that variants or versions of an XML vocabulary exist in which the same local names are used, but in different namespaces. There is then a requirement to write code that will process source documents in a variety of different namespaces.

It is possible to define a static stylesheet parameter containing the target namespace, for example:

<xsl:param name="NS" as="xs:string" static="yes" 
                          select="'http://example.com/ns/one'"/>

And this can then be used to set the default namespace for XPath expressions:

_xpath-default-namespace="{$NS}"

However, it is not possible to put this shadow attribute on the xsl:stylesheet or xsl:package element of the principal stylesheet module, because at that point the variable $NS is not in scope. A workaround is to create a stub stylesheet module which contains nothing but the static parameter declaration and an xsl:include of the stylesheet module containing the real logic. The static stylesheet parameter will then be in scope on the xsl:stylesheet element of the included stylesheet module, and the shadow attribute _xpath-default-namespace="{$NS}" can therefore appear on this xsl:stylesheet element.

 

Example: Using Shadow Attributes to Parameterize Selection of Elements

The following stylesheet produces a report giving information about selected employees. The predicate defining which employees are to be included in the report is supplied (as a string containing an XPath expression) in a static stylesheet parameter:

          <xsl:param name="filter" static="yes"
                     as="xs:string" select="'true()'"/>
          <xsl:function name="local:filter" as="xs:boolean">
            <xsl:param name="e" as="element(employee)"/>
            <xsl:sequence _select="$e/({$filter})"/>
          </xsl:function>
          <xsl:template match="/">
            <report>
              <xsl:apply-templates mode="report" select="//employee[local:filter(.)]"/>
            </report>
          </xsl:template>
                     

If the supplied value of the filter parameter is, say location = "UK", then the report will cover employees based in the UK.

Note:

The stylesheet function local:filter is used here in preference to direct use of the supplied predicate within the select attribute of the xsl:apply-templates instruction because it reduces exposure to code injection attacks. It does not necessarily eliminate all such risks, however. For example, it would be possible for a caller to supply an expression that never terminates, thus creating a denial-of-service risk.

3.14 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 1.1 Part 1]). 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 implementers 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 24.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.15 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 27 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.14 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"
             xmlns:local="http://example.com/ns/yes-no">
    <xs:simpleType name="yes-no">
      <xs:restriction base="xs:string">
        <xs:enumeration value="yes"/>
        <xs:enumeration value="no"/>
      </xs:restriction>
    </xs:simpleType>
  </xs:schema>
</xsl:import-schema>

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

There are two built-in functions (analyze-stringFO30 and json-to-xml) whose result is an XML structure for which a schema is defined. The namespace for these schema definitions is (in both cases) http://www.w3.org/2005/xpath-functions. Schema components for these namespaces are available for reference within the stylesheet if and only if an xsl:import-schema declaration is present referencing this namespace. If such a declaration is present, then the schema that is imported is the schema defined in the specification of these functions: the schemaLocation attribute has no effect.

4 Data Model

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

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

The rules in 4.3 Stripping Whitespace from the Stylesheet and 4.5 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 [XDM 3.0] 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 26 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 which versions and editions of XML and XML Namespaces are supported by the implementation.

Note:

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

The current version of [XML Schema 1.1 Part 2] references the XML 1.1 specifications, but the previous version ([XML Schema Part 2]) (that is, XSD 1.0) remains in widespread use, and only references XML 1.0. With processors lacking support for XSD 1.1, therefore, datatypes such as xs:NCName and xs:ID may be constrained by the XML 1.0 rules, and not allow the full range of values permitted by XML 1.1. It is recommended that implementers wishing to support XML 1.1 should consult [XML Schema 1.0 and XML 1.1] for guidance.

4.2 XDM versions

XSLT 3.0 requires a processor to support XDM 3.0 as defined in [XDM 3.0], augmented with support for maps as described in 21 Maps.

A processor may also provide a user option to support XDM 3.1 as defined in [XDM 3.1], in which case it must do so as defined in 27.7 XPath 3.1 Feature.

Note:

The essential differences between XDM 3.0 (with the extensions defined in this specification) and XDM 3.1 are that XDM 3.1 adds support for arrays, and for the xs:numeric union type.

A processor may also provide a user option to support versions of XDM later than 3.1, in which case the way it does so is implementation-defined.

4.3 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:fork
    xsl:merge
    xsl:merge-source
    xsl:mode
    xsl:next-iteration
    xsl:next-match
    xsl:override
    xsl:package
    xsl:stylesheet
    xsl:transform
    xsl:use-package

  5. Any whitespace text node whose immediate following-sibling node is an xsl:param or xsl:sort or xsl:context-item or xsl:on-completion 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 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 whitespace text nodes in that part of the stylesheet 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.4 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:package element. This attribute has three permitted values: strip, preserve, and unspecified. The default value is unspecified.

The input-type-annotations attribute may also be specified on the xsl:stylesheet element; if it is specified at this level then it must be consistent for all stylesheet modules within the same package.

[ERR XTSE0265] It is a static error if there is a stylesheet module in a package that specifies input-type-annotations="strip" and another stylesheet module that specifies input-type-annotations="preserve", or if a stylesheet module specifies the value strip or preserve and the same value is not specified on the xsl:package element of the containing package.

The source trees to which this applies are the same as those affected by xsl:strip-space and xsl:preserve-space: see 4.5 Stripping Whitespace from a Source Tree. As with whitespace stripping, the rules for stripping of type annotations may vary from one package to another, and have the effect of modifying the mapping from URIs to document nodes defined in the XPath dynamic context; this means that two calls to the docFO30 function (for example) supplying the same URI may produce different document nodes if the calls appear in different packages.

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.5 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 global context item if it is a node, any documents containing nodes present in the initial match selection, any document returned by the functions document, docFO30, or collectionFO30, and any document read using xsl:stream. It does not include documents passed as the values of stylesheet parameters or parameters of the initial template or function, nor values returned from extension functions.

Each source tree is associated with a package: the relevant package for the global context item is the top-level package; the relevant package for a call on document, docFO30, or collectionFO30; is the package in which that call appears; and the relevant package for evaluation of xsl:stream is the package in which that instruction appears.

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.

Formally, the stripping process modifies the mapping from URIs to document nodes defined in the XPath dynamic context. This mapping can therefore vary from one package to another. The mapping that applies to a particular call on document, docFO30, or collectionFO30, or a particular evaluation of xsl:stream, is affected by the xsl:strip-space and xsl:preserve-space declarations within the package in which that construct appears. This means that two calls on the docFO30 function (for example) may return different nodes if the calls appear in different packages.

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 or an evaluation of an xsl:stream instruction 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. 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.

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 [XDM 3.0], 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.6 Attribute Types and DTD Validation

The mapping from the Infoset to the XDM data model, described in [XDM 3.0], 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 3.0].

4.7 Data Model for Streaming

4.7.1 Streamed Documents

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.

  • In the case of element nodes, whether or not the element has children. This information is obtained by calling the has-childrenFO30 function. This implies that the processor performs look-ahead (limited to a single token) to determine whether the start tag is immediately followed by a matching end tag.

  • In the case of document nodes, details of unparsed entities in the document. This information is obtained by calling the unparsed-entity-uri and unparsed-entity-public-id functions. A processor might enable this by reading the DTD as soon as the document is opened. Since comments and processing instructions that precede the DOCTYPE declaration are available as children of the document node, this also implies that a streaming processor needs sufficient memory to hold these comments and processing instructions until the start tag of the first element is encountered. Information about unparsed entities remains available for the duration of processing, in the same way as attributes of ancestor elements.

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.

Information about the type of a node is in general considered a property intrinsic to the node, and is available without advancing the input stream. There is an exception for an expression of the form (/) instance of document-node(element(invoice)). This is not guaranteed streamable, because it requires reading ahead to check that the document node has only one element child. However, a processor that knows that the parser delivering the document stream is only capable of delivering well-formed documents may use this knowledge (along with the limited look-ahead needed to get the name of the outermost element) to make this expression streamable.

A streaming processor is not required to read any more of the source document than 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 Streamability.

4.7.2 Other Data Structures

Two new data structures have been added to the data model: maps and arrays. Both are defined in XPath 3.1, but maps are also available in XSLT processors that only support XPath 3.0 (see 21 Maps).

Streaming facilities in this specification are, for the most part, relevant only to streamed processing of XML trees, and not to other structures such as sequences, maps and arrays, which will typically be held in memory unless the processor is capable of avoiding this.

Maps, however, play in important role in enabling streamed applications to be written. For example, a map can be used as the data structured maintained by an accumulator (see 18.2 Accumulators) to remember information that has been retrieved from a streamed document, given that it is not possible to revisit the same nodes later. There is also a special streamability rule for map constructor expressions (see 21.6 Maps and Streaming) that allows such an expression to make multiple downward selections in the streamed input document: for example one can write map{'authors':data(author), 'editors':data(editor)}, which gathers the values of these these two elements, or sets of elements, from the input stream, regardless what order they appear in — even if they are interleaved.

The rules for creating maps and arrays are designed to ensure that the entries in a map, and the members of an array, cannot contain nodes from a streamed document. This is achieved by the way in which the streamability properties of the relevant expressions and functions are defined.

By contrast, sequences can and often do contain nodes from streamed documents, and a major purpose of the rules for streamability is to make this possible.

4.8 Limits

The XDM data model (see [XDM 3.0]) 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.9 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 26.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 26.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.

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 Names

5.1.1 Qualified Names

Many constructs appearing in a stylesheet, for example named templates, modes, and attribute sets, are named using a qualified name: this consists of a local name and an optional namespace URI.

In most cases where such names are written in a stylesheet, the syntax for expressing the name is given by the production 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 [XDM 3.0]): that is, a triple containing namespace prefix (optional), namespace URI (optional), and local name. Two expanded QNames are equal if the namespace URIs are the same (or both absent) and the local names are the same. The prefix plays no part in the comparison, but is used only if the expanded QName needs to be converted back to a string.]

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

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

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

The following rules are used when interpreting a lexical QName:

  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 an attribute or text node within a stylesheet module, or as the result of evaluating an XPath expression contained in such a node. The element containing this attribute or text node is referred to as the defining element of the lexical QName.]

  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 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.2 Expressions), and in certain other contexts, the namespace to be used in expanding the QName may be specified by means of the [xsl:]xpath-default-namespace attribute, as specified in 5.1.2 Unprefixed Lexical QNames in Expressions and Patterns.

    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 or suppress-indentation attributes 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.1.2 Unprefixed Lexical QNames in Expressions and Patterns

The attribute [xsl:]xpath-default-namespace (see 3.4 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 or text node of that element (including XPath expressions in attribute value templates and text 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.1.3 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 3.0] 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 3.0].

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

  • The namespace http://www.w3.org/2005/xpath-functions/array is reserved for use as described in [Functions and Operators 3.1]. The namespace is reserved whether or not the processor actually supports XPath 3.1.

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

Note:

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

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

It is not an error to use a reserved namespace in the name of an extension attribute: attributes such as xml:space and xsi:type fall into this category. XSLT processors must not reject such attributes, and must not attach any meaning to them other than any meaning defined by the relevant specification.

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

Note:

The name xsl:original is used within xsl:override to refer to a component that is being overridden. Although the name xsl:original is used to refer to the component, the component has its own name, and no component ever has the name xsl:original.

5.2 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], with the extensions defined in 21 Maps.]

If the processor implements the XPath 3.1 Feature, then the definition of the production Expr from XPath 3.1 is used.

If the processor is configured to use a version of XPath later than XPath 3.1, then the syntax of an XPath expression is implementation-defined.

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

Except where forwards compatible behavior is enabled (see 3.10 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 or text 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 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:  When used in this specification without further qualification, the term function conversion rules means the function conversion rules defined in [XPath 3.0], applied with XPath 1.0 compatibility mode set to false.]

Note:

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 same rules are used in XSLT for converting the value of a variable to the declared type of the variable, or the result of evaluating a function or template body to the declared type of the function or template. They are also used when parameters are supplied to a template using xsl:with-param. In all such cases, the rules that apply are the XPath 3.0 rules without XPath 1.0 compatibility mode. The rules with XPath 1.0 compatibility mode set to true are used only for XPath function calls, and for the operands of certain XPath operators.

This specification also invokes the XPath 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.

The XPath specification states that the host language must specify whether the XPath processor normalizes all line breaks on input, before parsing, and if it does so, whether it uses the rules of [XML 1.0] or [XML 1.1]. In the case of XSLT, all handling of line breaks is the responsibility of the XML parser (which may support either XML 1.0 or XML 1.1); the XSLT and XPath processors perform no further changes.

Note:

Most XPath expressions in a stylesheet appear within XML attributes. They are therefore subject to XML line-ending normalization (for example, a CRLF sequence is normalized to LF) and also to XML attribute-value normalization, which replaces tabs and newlines by spaces. XPath expressions appearing in text value templates, however (see 5.6.2 Text Value Templates) are subject to line-ending normalization but not attribute-value normalization. In both cases, normalization of whitespace can be prevented by using character references such as &#x9;.

5.3 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.3.1 Initializing the Static Context
5.3.2 Additional Static Context Components used by XSLT
5.3.3 Initializing the Dynamic Context
5.3.4 Additional Dynamic Context Components used by XSLT

5.3.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 or text node whose value contains the XPath expression in question, and the term enclosing element means the containing element or any of its ancestors.

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

A dynamic function call clears the first of these components: this means that a dynamic call to the key function will always raise a dynamic error (the key name is unknown). The values of system properties and the set of available instructions, by contrast, reflect the capabilities and configuration of the processor rather than values specific to the stylesheet code itself; the result of a dynamic call to system-property or element-available will reflect the information available to the processor at evaluation time.

Note:

If these functions are called within a static expression, the results will reflect the capabilities and configuration of the processor used to perform static analysis, while if they are called elsewhere, the results should reflect the capabilities and configuration of the processor used to perform dynamic evaluation, which might give a different result. These calls should not be pre-evaluated at compile time unless it is known that this will give the same result.

5.3.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 3.0] 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.3.4 Additional Dynamic Context Components used by XSLT are also not stable.

As specified in [Functions and Operators 3.0], 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.13.1 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.3.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 [XDM 3.0]) is either an atomic value (such as an integer, date, or string), a node, or a function item. It changes whenever instructions such as xsl:apply-templates and xsl:for-each are used to process a sequence of items; each item in such a sequence becomes the context item while that item is being processed.] The context item is returned by the XPath expression . (dot).

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

The context item for evaluating global variables in the top-level package is set to the global context item supplied when the transformation is invoked (see 2.3 Initiating a Transformation). In library packages, the context item for evaluating global variables is absent.

For an XPath expression contained in a value template, the initial context item, context position, and context size for the XPath expression are the same as the context item, context position, and context size for the evaluation of the containing sequence constructor.

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

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

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

When a stylesheet function is called, the focus within the body of the function is initially absent.

When the focus is absent, evaluation of any expression that references the context item, context position, or context size results in a 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.3.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.

    The mapping from URIs to document nodes is affected by xsl:strip-space declarations and by the input-type-annotations attribute, and may therefore vary from one package to another.

    Note:

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

    The XSLT-defined document function allows the use of URI references containing fragment identifiers. The interpretation of a fragment identifier depends on the media type of the resource representation. Therefore, the information supplied in available 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.3.4 Additional Dynamic Context Components used by XSLT

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

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

ComponentInitial SettingSet byCleared by
focusSee 2.3 Initiating a Transformation.xsl:apply-templates, xsl:for-each, xsl:for-each-group, xsl:analyze-string, evaluation of patternsCalls to stylesheet functions
current template ruleIf a named template is supplied as the entry point to the transformation, then absent; otherwise the initial named templatexsl:apply-templates, xsl:apply-imports, xsl:next-matchxsl:for-each, xsl:for-each-group, xsl:analyze-string, xsl:iterate, xsl:stream, xsl:merge, xsl:evaluate, and calls to stylesheet functions, and dynamic function calls. Also cleared while evaluating global variables or default values of stylesheet parameters, patterns, and the sequence constructors contained in xsl:key and xsl:sort.
current modethe initial modexsl:apply-templatesCalls to stylesheet functions. Also cleared while evaluating global variables and stylesheet parameters, patterns, and 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 groupabsentxsl:for-each-groupSee 14.2.1 fn:current-group.
current grouping keyabsentxsl:for-each-groupSee 14.2.2 fn:current-grouping-key.
current merge groupabsentxsl:mergeSee 15.6.1 fn:current-merge-group.
current merge keyabsentxsl:mergeSee 15.6.2 fn:current-merge-key.
current captured substringsempty sequencexsl:matching-substringxsl:non-matching-substring; Calls to stylesheet functions, dynamic function calls, evaluation of global variables, stylesheet parameters, and patterns
output statefinal output stateSet to temporary output state by instructions such as xsl:variable, xsl:attribute, etc., and by calls on stylesheet functionsNone
current output URIbase output URIxsl:result-documentCalls to stylesheet functions, dynamic function calls, evaluation of global variables, stylesheet parameters, and patterns.

[Definition: The initial setting of a component of the dynamic context is used when evaluating global variables and stylesheet parameters, when evaluating the use and match attributes of xsl:key, when evaluating the initial-value of xsl:accumulator and the select expressions or contained sequence constructors of xsl:accumulator-rule]

[Definition: The term non-contextual function call is used to refer to function calls that do not pass the dynamic context to the called function. This includes all calls on stylesheet functions and all dynamic function invocationsXP30, (that is calls to function items as permitted by XPath 3.0). It excludes calls to some functions in the namespace http://www.w3.org/2005/xpath-functions, in particular those that explicitly depend on the context, such as the current-group and regex-group functions. It is implementation-defined whether, and under what circumstances, calls to extension functions are non-contextual.]

Named function references (such as position#0) and calls on function-lookupFO30 (for example, function-lookup("position", 0)) are defined to retain the XPath static and dynamic context at the point of invocation as part of the closure of the resulting function item, and to use this preserved context when a dynamic function call is subsequently made using the function item. This rule does not extend to the XSLT extensions to the dynamic context defined in this section. If a dynamic function call is made that depends on the XSLT part of the dynamic context (for example, regex-group#1(2)), then the relevant components of the context are cleared as described in the table above.

5.4 Defining a Decimal Format

The definition of the format-numberFO30 function is now in [Functions and Operators 3.0]. 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
  exponent-separator? = char
  NaN? = string
  percent? = char
  per-mille? = char
  zero-digit? = char
  digit? = char
  pattern-separator? = char />

The xsl:decimal-format element sets the statically known decimal formats component of the static context for XPath expressions, which controls the interpretation of a picture string used by the format-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 defined in [Functions and Operators 3.0].

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

[Definition: All the xsl:decimal-format declarations in a package that share the same name are grouped into a named decimal format; those that have no name are grouped into a single unnamed decimal format.]

The attributes of the xsl:decimal-format declaration define the value of the corresponding property in the relevant decimal format in the statically known decimal formatsXP30 component of the static context for all XPath expressions in the package. The attribute names used in the XSLT 3.0 syntax are the same as the property names used in the definition of the static context.

The exponent-separator attribute is provided for use with XPath 3.1. It has no effect when used with XPath 3.0.

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 to separate the integer part from the fractional part of the formatted number; the default value is the period character (.)

  • grouping-separator specifies the character typically used as a thousands separator; the default value is the comma character (,)

  • percent specifies the character used to indicate that the number is represented as a per-hundred fraction; the default value is the percent character (%)

  • per-mille specifies the character used to indicate that the number is represented as a per-thousand fraction; the default value is the Unicode per-mille character (#x2030)

  • zero-digit specifies the character used to represent the digit zero; the default value is the Western 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 in the picture string as a place-holder for an optional digit; the default value is the number sign character (#)

  • pattern-separator specifies the character used to separate 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 to represent the xs:double value INF; the default value is the string Infinity

  • NaN specifies the string used to represent the xs:double value NaN (not-a-number); the default value is the string NaN

  • minus-sign specifies the character used to signal a negative number; 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.

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 kinds of pattern: predicate patterns, and selection patterns:

  • [Definition: A predicate pattern is written as . (dot) followed by zero or more predicates in square brackets, and it matches any item for which each of the predicates evaluates to true.]

    The detailed semantics are given in 5.5.3 The Meaning of a Pattern. This construct can be used to match items of any kind (nodes, atomic values, and function items). For example, the pattern .[starts-with(., '$')] matches any string that starts with the character "$", or a node whose atomized value starts with "$". This example shows a predicate pattern with a single predicate, but the grammar allows any number of predicates (zero or more).

  • [Definition: A selection pattern uses a subset of the syntax for path expressions, and is defined to match a node if the corresponding path expression would select the node. Selection patterns may also be formed by combining other patterns using union, intersection, and difference operators.]

    The syntax for selection patterns (UnionExprP in the grammar: see 5.5.2 Syntax of Patterns) is a subset of the syntax for expressions. Selection patterns are used only for matching nodes; an item other than a node will never match a selection pattern. As explained in detail below, a node matches a selection 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:

  • . matches any item.

  • * matches any element.

  • para matches any para 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'.

  • .[. instance of node()] matches any node. (Note the distinction from the pattern node().)

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

  • .[. gt current-date()] matches any date in the future. It can match an atomic value of type xs:date or xs:untypedAtomic, or a node whose atomized value is an xs:date or xs:untypedAtomic value.

  • .[starts-with(., 'e')] matches any node or atomic value that after conversion to a string using the function conversion rules starts with the letter 'e'.

  • .[. instance of function(*)] matches any function item.

  • .[$f(.)] matches any item provided that the call on the function bound to the variable $f returns a result whose effective boolean value is true.

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

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.

Patterns
[1]   Pattern30   ::=   PredicatePattern | UnionExprP
[2]   PredicatePattern   ::=   "." PredicateListXP30
[3]   UnionExprP   ::=   IntersectExceptExprP (("union" | "|") IntersectExceptExprP)*
[4]   IntersectExceptExprP   ::=   PathExprP (("intersect" | "except") PathExprP)*
[5]   PathExprP   ::=   RootedPath
| ("/" RelativePathExprP?)
| ("//" RelativePathExprP)
| RelativePathExprP
[6]   RootedPath   ::=   (VarRefXP30 | FunctionCallP) PredicateListXP30 (("/" | "//") RelativePathExprP)?
[7]   FunctionCallP   ::=   OuterFunctionName ArgumentListP
[8]   OuterFunctionName   ::=   "doc" | "id" | "element-with-id" | "key" | "root" | URIQualifiedNameXP30
[9]   ArgumentListP   ::=   "(" (ArgumentP ("," ArgumentP)*)? ")"
[10]   ArgumentP   ::=   VarRefXP30 | LiteralXP30
[11]   RelativePathExprP   ::=   StepExprP (("/" | "//") StepExprP)*
[12]   StepExprP   ::=   PostfixExprP | AxisStepP
[13]   PostfixExprP   ::=   ParenthesizedExprP PredicateListXP30
[14]   ParenthesizedExprP   ::=   "(" UnionExprP ")"
[15]   AxisStepP   ::=   ForwardStepP PredicateListXP30
[16]   ForwardStepP   ::=   (ForwardAxisP NodeTestXP30) | AbbrevForwardStepXP30
[17]   ForwardAxisP   ::=   ("child" "::")
| ("descendant" "::")
| ("attribute" "::")
| ("self" "::")
| ("descendant-or-self" "::")
| ("namespace" "::")

The names of these constructs are chosen to align with the XPath 3.0 grammar. Constructs whose names are suffixed with P are restricted forms of the corresponding XPath 3.0 construct without the suffix. Constructs labeled with the suffix "XP30" are defined in [XPath 3.0].

Where the XSLT 3.0 processor implements the XPath 3.1 Feature, the definitions that apply to constructs labeled with the suffix "XP30" are those in [XPath 3.1]

In a FunctionCallP, the EQName used for the function name must have local part doc, id, element-with-id, key, or root, and must use the standard function namespace either explicitly or implicitly.

In the case of a call to the rootFO30 function, the argument list must be empty: that is, only the zero-arity form of the function is allowed.

Note:

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

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

If the pattern is a PredicatePattern PP, then it matches an item J if the XPath expression taking the same form as PP returns a non-empty sequence when evaluated with a singleton focus based on J.

Note:

The pattern ., which is a PredicatePattern with an empty PredicateListXP30, matches every item.

A predicate with the numeric value 1 (one) always matches, and a predicate with any other numeric value never matches. Numeric predicates in a PredicatePattern are therefore not useful, but are defined this way in the interests of consistency with XPath.

Otherwise (the pattern is a selection pattern), 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 the following adjustment:

  • If any PathExprP in the Pattern is a RelativePathExprP, then the first StepExprP PS of this RelativePathExprP is adjusted to allow it to match a parentless element, attribute, or namespace node. The adjustment depends on the axis used in this step, whether it appears explicitly or implicitly (according to the rules of Section 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 (explicitly or implicitly), then the axis in step PS is replaced by namespace-or-top, which is defined as follows. If the context node is a namespace node with no parent, then the namespace-or-top axis selects the context node; otherwise it selects the namespace nodes of the context node. It is a forwards axis whose principal node kind is namespace.

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

    Note:

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

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

Specifically, an item N matches a pattern P if 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

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

Example: The Semantics of Selection Patterns

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

The selection pattern root(.)/self::E matches an E element that is the root of a tree (that is, an E element with no parent node).

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

A dynamic error or type error that occurs during the evaluation of a pattern against a particular item has the effect that the item being tested is treated as not matching the pattern. The error does not cause the transformation to fail, and cannot be caught by a try/catch expression surrounding the instruction that causes the pattern to be evaluated.

Note:

The reason for this provision is that it is difficult for the stylesheet author to predict which predicates in a pattern will actually be evaluated. In the case of match patterns in template rules, it is not even possible to predict which patterns will be evaluated against a particular node.

There is a risk that ignoring errors in this way may make programming mistakes harder to debug. Implementations may mitigate this by providing warnings or other diagnostics when evaluation of a pattern triggers an error condition.

Static errors in patterns, including dynamic and type errors that are signaled statically as permitted by the specification, are reported in the normal way and cause the transformation to fail.

The requirement to detect and report a circularity as a dynamic error overrides this rule.

5.6 Value Templates

The string value of an attribute or text node in the stylesheet may in particular circumstances contain embedded expressions enclosed between curly brackets. Attributes and text nodes that use (or are permitted to use) this mechanism are referred to respectively as attribute value templates and text value templates..

[Definition: Collectively, attribute value templates and text value templates are referred to as value templates.]

A value template is a string consisting of an alternating sequence of fixed parts and variable parts:

  • A variable part consists of an optional XPath expression enclosed in curly brackets ({}): more specifically, a string conforming to the XPath production Expr?.

    Note:

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

    Currently no XPath expression starts with an opening curly bracket, so the use of {{ creates no ambiguity. If an enclosed expression ends with a closing curly bracket, no whitespace is required between this and the closing delimiter.

    The fact that the expression is optional means that the string contained between the curly brackets may be zero-length, may comprise whitespace only, or may contain XPath comments. The effective value in this case is a zero-length string, which is equivalent to omitting the variable part entirely, together with its curly-bracket delimiters.

  • A fixed part may contain any characters, except that a left curly bracket must be written as {{ and a right curly bracket must be written as }}.

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

It is a static error if the string contained between matching curly brackets in a value template does not match the XPath production Expr?XP30, 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 a value template.

[Definition: The result of evaluating a value template is referred to as its effective value.] The effective value is the string obtained by concatenating the expansions of the fixed and variable parts:

  • The expansion of a fixed part is obtained by replacing any double curly brackets ({{ or }}) by the corresponding single curly bracket.

  • The expansion of a variable part is as follows:

    • If an expression is present, the result of evaluating the enclosed XPath expression and converting the resulting value to a string. This conversion is done using the rules given in 5.7.2 Constructing Simple Content.

    • If the expression is omitted, a zero-length string.

Note:

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

In the case of an attribute value template, the effective value becomes the string value of the new attribute node. In the case of a text value template, the effective value becomes the string value of the new text node.

5.6.1 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 ({}), following the general rules for value templates].

Curly brackets are not treated specially in an attribute value in an XSLT stylesheet unless the attribute is specifically designated as one that permits an attribute value template; in an element syntax summary, the value of such attributes is surrounded by curly brackets.

Note:

Not all attributes are designated as attribute value templates. Attributes whose value is an expression or pattern, attributes of declaration elements and attributes that refer to named XSLT objects are generally not designated as attribute value templates (an exception is the format attribute of xsl:result-document). Namespace declarations are not XDM attribute nodes and are therefore never treated as attribute value templates.

If the element containing the attribute is processed with XSLT 1.0 behavior, then the rules for converting the value of the expression to a string (given in 5.6 Value Templates) are modified as follows. After atomizing the result of the expression, all items other than the first item in the resulting sequence are discarded, and the effective value is obtained by converting the first item in the sequence to a string. If the atomized sequence is empty, the result is a zero-length string.

Note:

The above rule applies to attribute value templates but not to text value templates, since the latter were not available in XSLT 1.0.

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 cannot be Nested

For example:

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

is not allowed. Instead, use simply:

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

5.6.2 Text Value Templates

The standard attribute [xsl:]expand-text may appear on any element in the stylesheet, and determines whether descendant text nodes of that element are treated as text value templates. A text node in the stylesheet is treated as a text value template if (a) it is part of a sequence constructor or a child of an xsl:text instruction, (b) there is an ancestor element with an [xsl:]expand-text attribute, and (c) on the innermost ancestor element that has such an attribute, the value of the attribute is yes. The attribute is boolean and must therefore take one of the values yes (synonyms true or 1) or no (synonyms false or 0).

This section describes how text nodes are processed when the effective value is yes. Such text nodes are referred to as text value templates.

[Definition: In a text node that is designated as a text value template, expressions can be used by surrounding each expression with curly brackets ({}).]

The rules for text value templates are given in 5.6 Value Templates. A text node whose value is a text value template results in the construction of a text node in the result of the containing sequence constructor or xsl:text instruction. The string value of that text node is obtained by computing the effective value of the value template.

Note:

The result of evaluating a text value template is a (possibly zero-length) text node. This text node becomes part of the result of the containing sequence constructor or xsl:text instruction, and is thereafter handled exactly as if the value had appeared explicitly as a text node in the stylesheet.

The way in which the effective value is computed does not depend on any separator attribute on a containing xsl:value-of or xsl:attribute instruction. The separator attribute only affects how the text node is combined with adjacent items in the result of the containing sequence constructor.

Fixed parts consisting entirely of whitespace are significant and are handled in the same way as any other fixed part. This is different from the default treatment of “boundary space” in XQuery.

Example: Using a text value template to construct message output
<xsl:variable name="id" select="'A123'"/>
<xsl:variable name="step" select="5"/>
<xsl:message expand-text="yes"
     >Processing id={$id}, step={$step}</xsl:message>

This will typically output the message text Processing id=A123, step=5.

 

Example: Using a text value template to define the result of a function
<xsl:function name="f:sum" expand-text="yes" as="xs:integer">
<xsl:param name="x" as="xs:integer"/>
<xsl:param name="y" as="xs:integer"/>
  {$x + $y}
</xsl:function>

Note that although this is a very readable way of expressing the computation performed by the function, the semantics are somewhat complex, and this could mean that execution is inefficient. The function computes the value of $x + $y as an integer, and then constructs a text node containing the string representation of this integer (preceded and followed by whitespace). Because the declared result type of the function is xs:integer, this text node is then atomized, giving an xs:untypedAtomic value, and the xs:untypedAtomic value is then cast to an xs:integer.

Note:

The main motivations for adding text value templates to the XSLT language are firstly, to make it easier to construct parameterized text in contexts such as xsl:value-of and xsl:message, and secondly, to allow use of complex multi-line XPath expressions where maintaining correct indentation is important for readability. The fact that XML processors are required to normalize whitespace in attribute values means that writing such expressions within a select attribute is not ideal.

The facility is only present if enabled using the [xsl:]expand-text attribute. This is partly for backwards compatibility, and partly to avoid creating difficulties when constructing content that is rich in curly brackets, for example JavaScript code or CSS style sheets.

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:

  1. A Text node appearing in the stylesheet (if it has not been removed in the process of whitespace stripping: see 4.3 Stripping Whitespace from the Stylesheet) is processed as follows:

    1. if the effective value of the standard attribute [xsl:]expand-text is no, or in the absence of this attribute, the text node in the stylesheet is copied to create a new parentless text node in the result of the sequence constructor.

    2. Otherwise (the effective value of [xsl:]expand-text is yes), the text node in the stylesheet is processed as described in 5.6.2 Text Value Templates.

  2. A literal result element is evaluated to create a new parentless element node, having the same expanded QName as the literal result element: see 11.1 Literal Result Elements.

  3. An XSLT instruction produces a sequence of zero, one, or more items as its result. For most XSLT instructions, these items are nodes, but some instructions (such as xsl:sequence and xsl:copy-of) can also produce atomic values or function items. Several instructions, such as xsl:element, return a newly constructed parentless node (which may have its own attributes, namespaces, children, and other descendants). Other instructions, such as xsl:if, pass on the items produced by their own nested sequence constructors. The xsl:sequence instruction may return atomic values, function items, or existing nodes.

  4. An extension instruction (see 24.2 Extension Instructions) also produces a sequence of items as its result.

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.

However:

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 array item in the sequence (see 27.7.1 Arrays) is replaced by its members, recursively. This is equivalent to applying the array:flattenFO31 function defined in [Functions and Operators 3.1].

    Note:

    This situation only arises if the XPath 3.1 Feature is implemented. Note that if the array contains nodes, this operation leaves the nodes in the sequence: they are not atomized.

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

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

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

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

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

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

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

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

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

  11. Each node in the resulting sequence is attached as a namespace, attribute, or child of the newly constructed element or document node. Conceptually this involves making a deep copy of the node; in practice, however, copying the node will only be necessary if the existing node can be referenced independently of the parent to which it is being attached. When copying an element or processing instruction node, its base URI property is changed to be the same as that of its new parent, unless it has an xml:base attribute (see [XML Base]) that overrides this. If the copied element has an xml:base attribute, its base URI is the value of that attribute, resolved (if it is relative) against the base URI of the new parent node.

    Except for the handling of base URI, the copying of a node follows the rules of the xsl:copy-of instruction with attributes copy-namespaces="yes" copy-accumulators="no" validation="preserve".

    Note:

    This has the consequence that the type annotation and the values of the nilled, is-id, and is-idrefs properties are retained. However, if the node under construction (the new parent of the node being copied) uses a validation mode other than preserve, this will be transient: the values will be recomputed when the new parent node is validated.

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

  13. 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 a value template. In this case the sequence being processed is the result of evaluating an XPath expression enclosed between curly brackets, and the separator is a single space character.

  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 a 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>
  <xsl:attribute name="g" expand-text="yes">{1 to 5}</xsl:attribute>
</doc>

This produces the output:

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

The difference between the three cases is as follows. For the e attribute, the sequence constructor generates a sequence of five atomic 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. For the g attribute, the text value template constructs a text node using the rules for constructing simple content, which insert space separators between atomic values; the text node is then atomized to form the value of the attribute.

Specifying separator="" on the first xsl:attribute instruction would cause the attribute value to be e="12345". A separator attribute on the second xsl:attribute instruction would have no effect, since the separator only affects the way adjacent atomic values are handled: separators are never inserted between adjacent text nodes. A separator on the third xsl:attribute instruction would also have no effect, because text value templates are evaluated without regard to the containing instruction.

Note:

If an attribute value template contains a sequence of fixed and variable parts, no additional whitespace is inserted between the expansions of the fixed and variable parts. For example, the effective value of the attribute a="chapters{4 to 6}" is a="chapters4 5 6".

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 [XDM 3.0] must be satisfied. For example

  • If an element node has an expanded QName with a non-null namespace URI, then that element node must have at least one namespace node whose string value is the same as that namespace URI.

  • If an element node has an attribute node whose expanded QName has a non-null namespace URI, then the element must have at least one namespace node whose string value is the same as that namespace URI and whose name is non-empty.

  • Every element must have a namespace node whose expanded QName has local-part xml and whose string value is http://www.w3.org/XML/1998/namespace. The namespace prefix 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 match selection, 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 [XDM 3.0], including the constraints imposed by the namespace fixup process. The effect of supplying a pseudo-document that does not meet these constraints is implementation-dependent.

In an Infoset (see [XML Information Set]) created from a document conforming to [Namespaces in XML], it will always be true that if a parent element has an in-scope namespace with a non-empty namespace prefix, then its child elements will also have an in-scope namespace with the same namespace prefix, though possibly with a different namespace URI. This constraint is removed in [Namespaces in XML 1.1]. XSLT 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 3.0].

URI references used to identify external resources must conform to the same rules as the locator attribute (href) defined in section 5.4 of [XLink]. If the URI reference is relative, then it is resolved (unless otherwise specified) against the base URI of the containing element node, according to the rules of [RFC3986], after first escaping all characters that need to be escaped to make it a valid RFC3986 URI reference. (But a relative URI reference in the href attribute of xsl:result-document is resolved against the Base Output URI.)

Other URI references appearing in an XSLT stylesheet document, for example the system identifiers of external entities or the value of the xml:base attribute, must follow the rules in their respective specifications.

The base URI of an element node in the stylesheet is determined as defined in Section 5.2 base-uri Accessor DM30. Some implementations may allow the output of the static analysis phase of stylesheet processing (a “compiled stylesheet”) to be evaluated in a different location from that where static analysis took place. Furthermore, stylesheet authors may in such cases which to avoid exposing the location of resources that are private to the development environment. If the base URI of an element in the stylesheet is defined by an absolute URI appearing in an xml:base attribute within the stylesheet, this value must be used as the static base URI. In other cases where processing depends on the static base URI of a stylesheet module, implementations may use different values for the static base URI during static analysis and during dynamic evaluation (for example, an implementation may use different base URIs for resolving xsl:import module references and for resolving a relative reference used as an argument to the docFO30 function). In such cases an implementation must document how the static base URI is computed for each situation in which it is required.

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

For details of the optional xsl:context-item child element, see 10.1.1 Declaring the Context Item for a Template.

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

  1. There is a name attribute, and the package identified by the containing xsl:use-package element contains among its components a named template whose symbolic identifier is the same as that of this named template, and which has a compatible signature.

  2. Both the following conditions are true:

    1. There is a match attribute.

    2. The value of the mode attribute, or in its absence the string #default, is a whitespace-separated sequence of tokens in which each token satisfies one of the following conditions:

      1. The token is an EQName representing the name of a mode that is exposed, with visibility equal to public, by the package identified by the containing xsl:use-package element.

      2. The token is #default, and there is an ancestor-or-self element with a default-mode attribute whose value is an EQName representing the name of a mode that is exposed, with visibility equal to public, by the package identified by the containing xsl:use-package element.

    Note:

    The token #unnamed is not allowed because the unnamed mode never has public visibility. The token #all is not allowed because its intended meaning would not be obvious.

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

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

<xsl:template match=".">
  <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 XTDE0540] It is a dynamic error if the conflict resolution algorithm for template rules leaves more than one matching template rule when the declaration of the relevant mode has an on-multiple-match attribute with the value fail.

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

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 is a ParenthesizedExprP then the outer parentheses are effectively stripped; these rules are applied recursively to the UnionExprP contained in the ParenthesizedExprP.

  2. If the top-level pattern is a UnionExprP consisting of multiple alternatives separated by | or union, then the template rule is treated equivalently to a set of template rules, one for each alternative. These template rules are adjacent to each other in declaration order, and the declaration order within this set of template rules (which affects the result of xsl:next-match if the alternatives have the same default priority) is the order of alternatives in the UnionExprP.

    Note:

    The splitting of a template rule into multiple rules occurs only if there is no explicit priority attribute.

  3. If the top-level pattern is an IntersectExceptExprP containing two or more PathExprP operands separated by intersect or except operators, then the priority of the pattern is that of the first PathExprP.

  4. If the pattern is a PredicatePattern then its priority is 1 (one), unless the PredicateListXP30 is empty, in which case the priority is −1 (minus one).

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

  6. If the pattern is a PathExprP taking the form of an EQName optionally preceded by a ForwardAxisP or has the form processing-instruction( StringLiteralXP30 ) or processing-instruction( NCNameNames ) optionally preceded by a ForwardAxisP, then the priority is 0 (zero).

  7. If the pattern is a PathExprP taking the form of an ElementTestXP30 or AttributeTestXP30, optionally preceded by a ForwardAxisP, then the priority is as shown in the table below. In this table, the symbols E, A, and T represent an arbitrary element name, attribute name, and type name respectively, while the symbol * represents itself. The presence or absence of the symbol ? following a type name does not affect the priority.

    FormatPriorityNotes
    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 PathExprP 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 PathExprP taking the form of an NCNameNames:* or *:NCNameNames, optionally preceded by a ForwardAxisP, then the priority is −0.25.

  10. If the pattern is a PathExprP taking the form of any other NodeTestXP30, optionally preceded by a ForwardAxisP, 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.

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:  A mode is a set of template rules; when the xsl:apply-templates instruction selects a set of items for processing, it identifies the rules to be used for processing those items by nominating a mode, explicitly or implicitly.] Modes allow a node in a source tree (for example) to be processed multiple times, each time producing a different result. They also allow different sets of template rules to be active when processing different trees, for example when processing documents loaded using the document function (see 20.1 fn:document).

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

6.6.1 Declaring Modes

<!-- Category: declaration -->
<xsl:mode
  name? = eqname
  streamable? = boolean
  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? = boolean
  warning-on-multiple-match? = boolean
  typed? = boolean | "strict" | "lax" | "unspecified"
  visibility? = "public" | "private" | "final" />

[Definition: The unnamed mode is the default mode used when no mode attribute is specified on an xsl:apply-templates instruction or xsl:template declaration, unless a different default mode has been specified using the [xsl:]default-mode attribute of a containing element.]

Every mode other than the unnamed mode is identified by an expanded QName.

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

[Definition: All the xsl:mode declarations in a package that share the same name are grouped into a named mode definition; those that have no name are grouped into a single unnamed mode definition.]

The declared-modes attribute of the xsl:package element determines whether implicit mode declarations are allowed, as described in 3.5.4.1 Requiring Explicit Mode Declarations. If the package allows implicit mode declarations, then if a stylesheet does not contain a declaration of the unnamed mode, a declaration is implied equivalent to an xsl:mode element with no attributes. Similarly, if there is a mode that is named in an xsl:template or xsl:apply-templates element, or in the [xsl:]default-mode attribute of a containing element, and the stylesheet does not contain a declaration of that mode, then a declaration is implied comprising an xsl:mode element with a name attribute equal to that mode name, plus the attribute visibility="private".

The attributes of the xsl:mode declaration establish values for a number of properties of a mode. The allowed values and meanings of the attributes are given in the following table.

AttributeValuesMeaning
nameAn EQNameSpecifies the name of the mode. If omitted, this xsl:mode declaration provides properties of the unnamed mode
streamableyes or no (default no)Determines whether template rules in this mode are to be capable of being processed using streaming. If the value yes is specified, then the body of any template rule that uses this mode must conform to the rules for streamable templates given in 6.6.4 Streamable Templates.
on-no-matchOne of deep-copy, shallow-copy, deep-skip, shallow-skip, text-only-copy or fail (default text-only-copy)Determines selection of the built-in template rules that are used to process an item when an xsl:apply-templates instruction selects an item that does not match any user-written template rule in the stylesheet. For details, see 6.7 Built-in Template Rules.
on-multiple-matchOne of fail or use-last (default use-last)Defines the action to be taken when xsl:apply-templates is used in this mode and more than one user-written template rule is available to process an item, each having the same import precedence and priority. The value fail indicates that it is a dynamic error if more than one template rule matches an item. The value use-last indicates that the situation is not to be treated as an error (the last template in declaration order is the one that is used).
warning-on-no-matchOne of yes or no. The default is implementation-definedRequests the processor to output (or not to output) a warning message in the case where an xsl:apply-templates instruction selects an item that matches no user-written template rule. The form and destination of such warnings is implementation-defined. The processor may ignore this attribute, for example if the environment provides no suitable means of communicating with the user.
warning-on-multiple-matchOne of yes or no. The default is implementation-definedRequests the processor to output a warning message in the case where an xsl:apply-templates instruction selects an item that matches multiple template rules having the same import precedence and priority. The form and destination of such warnings is implementation-defined. The processor may ignore this attribute, for example if the environment provides no suitable means of communicating with the user.
typedOne of yes, no, strict, lax, or unspecified. The default is unspecified.See 6.6.3 Declaring the Type of Nodes Processed by a Mode.
visibilityOne of public, private, or final. The default is private.See 3.5.3.1 Visibility of Components. If the mode is unnamed, that is, if the name attribute is absent, then the visibility attribute if present must have the value private. A named mode is not eligible to be used as the initial mode if its visibility is private.

[Definition: A streamable mode is a mode that is declared in an xsl:mode declaration with the attribute streamable="yes".]

For any named mode, the effective value of each attribute is taken from an xsl:mode declaration that has a matching name in its name attribute, and that specifies an explicit value for the required attribute. If there is no such declaration, the default value of the attribute is used. If there is more than one such declaration, the one with highest import precedence is used.

For the unnamed mode, the effective value of each attribute is taken from an xsl:mode declaration that has no name attribute, and that specifies an explicit value for the required attribute. If there is no such declaration, the default value of the attribute is used. If there is more than one such declaration, the one with highest import precedence is used.

[ERR XTSE0545] It is a static error if for any named or unnamed mode, a package explicitly specifies two conflicting values for the same attribute in different xsl:mode declarations having the same import precedence, unless there is another definition of the same attribute with higher import precedence. The attributes in question are the attributes other than name on the xsl:mode element.

6.6.2 Using Modes

[Definition: A template rule is applicable to one or more modes. The modes to which it is applicable are defined by the mode attribute of the xsl:template element. If the attribute is omitted, then the template rule is applicable to the default mode specified in the [xsl:]default-mode attribute of the innermost containing element that has such an attribute, which in turn defaults to the unnamed mode. If the mode attribute is present, then its value must be a non-empty whitespace-separated list of tokens, each of which defines a mode to which the template rule is applicable.]

Each token in the mode attribute must be one of the following:

  • an EQName, which is expanded as described in 5.1.1 Qualified Names to define the name of the mode

  • the token #default, to indicate that the template rule is applicable to the default mode that would apply if the mode attribute were absent

  • the token #unnamed, to indicate that the template rule is applicable to the unnamed mode

  • the token #all, to indicate that the template rule is applicable to all modes (specifically, to the unnamed mode and to every mode that is named explicitly or implicitly in an xsl:apply-templates instruction anywhere in the stylesheet).

When a template rule specifies mode="#all" this is interpreted as meaning all modes declared implicitly or explicitly within the declaring package of the xsl:template element. This value cannot be used in the case of a template rule declared within an xsl:override element.

[ERR XTSE0550] It is a static error if the list of modes is empty, if the same token is included more than once in the list, if the list contains an invalid token, or if the token #all appears together with any other value.

[ERR XTSE3440] In the case of a template rule (that is, an xsl:template element having a match attribute) appearing as a child of xsl:override, it is a static error if the list of modes in the mode attribute contains #all or #unnamed, or if it contains #default and the default mode is the unnamed mode, or if the mode attribute is omitted when the default mode is the unnamed mode.

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

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 non-contextual function call is made, the current mode is set to the unnamed mode. While evaluating global variables and parameters, and the sequence constructor contained in xsl:key or xsl:sort, the current mode is set to the unnamed mode. No other instruction changes the current mode. The current mode while evaluating an attribute set is the same as the current mode of the caller. On completion of the xsl:apply-templates instruction, or on return from a stylesheet function call, the current mode reverts to its previous value. The current mode is used when an xsl:apply-templates instruction uses the syntax mode="#current"; it is also used by the xsl:apply-imports and xsl:next-match instructions (see 6.8 Overriding Template Rules).

6.6.3 Declaring the Type of Nodes Processed by a Mode

Typically the template rules in a particular mode will be designed to process a specific kind of input document. The typed attribute of xsl:mode gives the stylesheet author the opportunity to provide information about this document to the processor. This information may enable the processor to improve diagnostics or to optimize performance.

The typed attribute of xsl:mode informs the processor whether the nodes to be processed by template rules in this mode are to be typed or untyped.

  • If the value yes is specified (synonyms true or 1), then all nodes processed in this mode must be typed. A dynamic error occurs if xsl:apply-templates in this mode selects an element or attribute node whose type annotation is xs:untyped or xs:untypedAtomic.

  • If the value no is specified (synonyms false or 0), then all nodes processed in this mode must be untyped. A dynamic error occurs if xsl:apply-templates in this mode selects an element or attribute whose type annotation is anything other than xs:untyped or xs:untypedAtomic.

  • The value strict is equivalent to yes, with the additional provision that in the match pattern of any template rule that is applicable to this mode, any NameTest used in the ForwardStepP of the first StepExprP of a RelativePathExprP is interpreted as follows:

    • If the NameTest is an EQName E, and the principal node kind of the axis of this step is Element, then:

      • It is a static error if the in-scope schema declarations do not include a global element declaration for element name E

      • When matching templates in this mode, the element name E appearing in this step is interpreted as schema-element(E). (Informally, this means that it will only match an element if it has been validated against this element declaration).

    • Otherwise (the NameTest is a wildcard or the principal node kind is Attribute or Namespace), the template matching proceeds as if the typed attribute were absent.

  • The value lax is equivalent to yes, with the additional provision that in the match pattern of any template rule that is applicable to this mode, any NameTest used in the ForwardStepP of the first StepExprP of a RelativePathExprP is interpreted as follows:

    • If the NameTest is an EQName E, and the principal node kind of the axis of this step is Element, and the in-scope schema declarations include a global element declaration for element name E, then:

      • When matching templates in this mode, the element name E appearing in this step is interpreted as schema-element(E). (Informally, this means that it will only match an element if it has been validated against this element declaration).

    • Otherwise (the NameTest is a wildcard, or the principal node kind is Attribute or Namespace, or there is no element declaration for E), the template matching proceeds as if the typed attribute were absent.

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

[ERR XTSE3105] It is a static error if a template rule applicable to a mode that is defined with typed="strict" uses a match pattern that contains a RelativePathExprP whose first StepExprP is an AxisStepP whose ForwardStepP uses an axis whose principal node kind is Element and whose NodeTest is an EQName that does not correspond to the name of any global element declaration in the in-scope schema components.

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

6.6.4 Streamable Templates

A template rule that is applicable to a mode M is guaranteed-streamable if and only if all the following conditions are satisfied:

  1. Mode M is declared in an xsl:mode declaration that specifies streamable="yes".

  2. The pattern defined in the match attribute of the xsl:template element is a motionless pattern as defined in 19.8.10 Classifying Patterns.

  3. The sweep of the sequence constructor forming the body of the xsl:template element is either motionless or consuming.

  4. The type-adjusted posture of the sequence constructor forming the body of the xsl:template element, with respect to the U-type that corresponds to the declared return type of the template (defaulting to item()*), is grounded.

    Note:

    This means that either (a) the sequence constructor is grounded as written (that is, it does not return streamed nodes), or (b) it effectively becomes grounded because the declared result type of the template is atomic, leading to implicit atomization of the result.

  5. Every expression and contained sequence constructor in a contained xsl:param element (the construct that provides the default value of the parameter) is motionless.

Specifying streamable="yes" on an xsl:mode declaration declares an intent that every template rule that includes that mode (explicitly or implicitly, including by specifying #all), should be streamable, either because it is guaranteed-streamable, or because it takes advantage of streamability extensions offered by a particular processor. The consequences of declaring the mode to be streamable when there is such a template rule that is not guaranteed streamable depend on the conformance level of the processor, and are explained in 19.10 Streamability Guarantees.

Processing of a document using streamable templates may be initiated using code such as the following, where S is a mode declared with streamable="yes":

<xsl:stream href="bigdoc.xml">
  <xsl:apply-templates mode="S"/>
</xsl:stream>

Alternatively, streamed processing may be initiated by invoking the transformation with an initial mode declared as streamable, while supplying the initial match selection (in an implementation-defined way) as a streamed document.

Note:

Invoking a streamable template using the construct <xsl:apply-templates select="doc('bigdoc.xml')"/> does not ensure streamed processing. As always, processors may use streamed processing if they are able to do so, but when the docFO30 or document functions are used, processors are obliged to ensure that the results are deterministic, which may be difficult to reconcile with streaming (if the same document is read twice, the results must be identical). The use of xsl:stream does not offer the same guarantees of determinism.

For an example of processing a collection of documents by use of the function uri-collectionFO30 in conjunction with xsl:stream, see 18.1.2 Examples of xsl:stream.

6.7 Built-in Template Rules

When an item is selected by xsl:apply-templates and there is no user-specified template rule in the stylesheet that can be used to process that item, then a built-in template rule is evaluated instead.

The built-in template rules have lower import precedence than all other template rules. Thus, the stylesheet author can override a built-in template rule by including an explicit template rule.

There are 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 processing a tree using a mode that specifies on-no-match="text-only-copy" is that the textual content of the source document is retained while losing the markup, except where explicit template rules dictate otherwise. When an element is encountered for which there is no explicit template rule, the processing continues with the children of that element. Text nodes are copied to the output.

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

This is equivalent to the following in the case where there are no parameters:

<xsl:template match="document-node()|element()" mode="M">
  <xsl:apply-templates mode="#current"/>
</xsl:template>

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

<xsl:template match="text()|@*" mode="M">
  <xsl:value-of select="string(.)"/>
</xsl:template>

Note:

This text node may have a string value that is zero-length.

The built-in template rule for atomic values returns a text node containing the value. It is effectively:

<xsl:template match=".[. instance of xs:anyAtomicType]" mode="M">
  <xsl:value-of select="string(.)"/>
</xsl:template>

Note:

This text node may have a string value that is zero-length.

The built-in template rule for processing instructions, comments, and namespace nodes does nothing (it returns the empty sequence).

<xsl:template 
   match="processing-instruction()|comment()|namespace-node()" 
   mode="M"/>

The built-in template rule for functions (including maps) does nothing (it returns the empty sequence).

<xsl:template 
   match=".[. instance of function(*)]" 
   mode="M"/>

The built-in template rule for arrays (see 27.7.1 Arrays) is to apply templates to the members of the array. It is equivalent to invoking xsl:apply-templates with the select attribute set to ?* (which selects the members of the array), and with the mode attribute set to #current. If the built-in rule was invoked with parameters, those parameters are passed on in the implicit xsl:apply-templates instruction.

This is equivalent to the following in the case where there are no parameters:

<xsl:template match=".[. instance of array(*)]" mode="M">
  <xsl:apply-templates mode="#current"/>
</xsl:template>

The following example illustrates the use of built-in template rules when there are parameters.

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 processing a tree using a mode that specifies on-no-match="deep-copy" is that an unmatched element in the source tree is copied unchanged to the output, together with its entire subtree. Other unmatched items are also copied unchanged. The subtree is copied unconditionally, without attempting to match nodes in the subtree against template rules.

When this default action is selected for a mode M, all items (nodes, atomic values, and functions, including maps and arrays) are processed using a template rule that is equivalent to the following:

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

6.7.3 Built-in Templates: Shallow Copy

The effect of processing a tree using a mode that specifies on-no-match="shallow-copy" is that the source tree is copied unchanged to the output, except for nodes where different processing is specified using an explicit template rule.

When this default action is selected for a mode M, all items (nodes, atomic values, and functions, including maps and arrays) are processed using a template rule that is equivalent to the following, except that all parameters supplied in xsl:with-param elements are passed on implicitly to the called templates:

<xsl:template match="." mode="M">
  <xsl:copy validation="preserve">
    <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 from the traditional select="node() | @*" is that with two separate instructions, the value of position() in the called templates forms one sequence starting at 1 for the attributes, and a new sequence starting at 1 for the children.

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

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

</xsl:stylesheet>

6.7.4 Built-in Templates: Deep Skip

The effect of processing a tree using a mode that specifies on-no-match="deep-skip" is that where no explicit template rule is specified for an element, that element and all its descendants are ignored, and are not copied to the result tree.

The effect of choosing on-no-match="deep-skip" is as follows:

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

    In the case where there are no parameters, this is equivalent to the following rule:

    <xsl:template match="document-node()" mode="M">
      <xsl:apply-templates mode="#current"/>
    </xsl:template>
    
  • The built-in rule for all items other than document nodes (that is, for all other kinds of node, as well as atomic values and functions, including maps and and arrays) is to do nothing, that is, to return an empty sequence (without applying templates to any children or ancestors).

    This is equivalent to the following rule:

    <xsl:template match="." mode="M"/>
    

6.7.5 Built-in Templates: Shallow Skip

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

The built-in rule for document nodes and element nodes applies templates (in the current mode) first to the node’s attributes and then to its children. If the built-in rule was invoked with parameters, those parameters are passed on in the implicit xsl:apply-templates instructions.

In the case where there are no parameters, this is equivalent to the following rule:

<xsl:template match="document-node()|element()" mode="M">
  <xsl:apply-templates select="@*" mode="#current"/>
  <xsl:apply-templates mode="#current"/>
</xsl:template>

The built-in template rule for all other kinds of node, and for atomic values and functions (including maps, but not arrays) is empty: that is, when the item is matched, the built-in template rule returns an empty sequence.

This is equivalent to the following rule:

<xsl:template match="." mode="M"/>

The built-in template rule for arrays (see 27.7.1 Arrays) is to apply templates to the members of the array. It is equivalent to invoking xsl:apply-templates with the select attribute set to ?* (which selects the members of the array), and with the mode attribute set to #current. If the built-in rule was invoked with parameters, those parameters are passed on in the implicit xsl:apply-templates instruction.

This is equivalent to the following in the case where there are no parameters:

<xsl:template match=".[. instance of array(*)]" mode="M">
  <xsl:apply-templates mode="#current"/>
</xsl:template>

6.7.6 Built-in Templates: Fail

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

The built-in template rule is effectively:

<xsl:template match="." mode="M">
  <xsl:message terminate="yes" error-code="err:XTDE0555"/>
</xsl:template>

with an implementation-dependent message body.

[ERR XTDE0555] It is a dynamic error if xsl:apply-templates, xsl:apply-imports or xsl:next-match is used to process 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, and also declarations of the same precedence and priority that appear earlier in declaration order. 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 non-contextual function call is made, the current template rule becomes absent 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 absent.

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.

    [ERR XTSE3460] It is a static error if an xsl:apply-imports element appears in a template rule declared within an xsl:override element. (To invoke the template rule that is being overridden, xsl:next-match should therefore be used.)

  • The xsl:next-match instruction considers as candidates all those template rules that come after the current template rule in the ordering of template rules implied by the conflict resolution rules given in 6.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 with no priority attribute, 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, 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 template rule has an explicit priority.

    Note:

    Because a template rule declared as a child of xsl:override has higher precedence than any template rule declared in the used package (see 3.5.4 Overriding Template Rules from a Used Package), the effect of xsl:next-match within such a template rule is to consider as candidates first any other template rules for the same mode within the same xsl:use-package element (taking into account explicit and implicit priority, and document order, in the usual way), and then all template rules in the used package.

If a matching template rule R is found, then the result of the xsl:next-match or xsl:apply-imports instruction is the result of invoking R, with the values of parameters being set using the child xsl:with-param elements as described in 9.10 Setting Parameter Values. The template rule R is evaluated with the same focus as the xsl:next-match or xsl:apply-imports instruction. The current template rule changes to be R. The current mode does not change.

Note:

In the case where the current template rule T is declared within an xsl:override element in a using package P, while the selected rule R is declared within a different package Q, and where the current mode is MP (mode M in package P), the effect is that the current mode for evaluation of R remains MP rather than reverting to its corresponding mode MQ (mode M in package Q). If R contains an xsl:apply-templates instruction that uses mode="#current", then the set of template rules considered by this instruction will therefore include any overriding template rules declared in P as well as the original rules declared in Q.

If no matching template rule is found that satisfies these criteria, the built-in template rule for the context item is used (see 6.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.10 Setting Parameter Values). It also passes on any tunnel parameters as described in 10.1.3 Tunnel Parameters.

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

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.

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.3 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*, xsl:on-completion?, sequence-constructor) -->
</xsl:iterate>

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

<!-- Category: instruction -->
<xsl:break
  select? = expression >
  <!-- Content: sequence-constructor -->
</xsl:break>

<xsl:on-completion
  select? = expression >
  <!-- Content: sequence-constructor -->
</xsl:on-completion>

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.

Note:

The xsl:on-completion element appears before other children of xsl:iterate to ensure that variables declared in the sequence constructor are not in scope within xsl:on-completion, since such variables do not have a defined value within xsl:on-completion especially in the case where the value of the select attribute is 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 XTSE3125] It is a static error if the select attribute of xsl:break or xsl:on-completion is present and the instruction has children.

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

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

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

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

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

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

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

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

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

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

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

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

If the input sequence is empty, then the result of the xsl:iterate instruction is the result of evaluating the select attribute or sequence constructor forming the body of the xsl:on-completion element, using the initial values of the xsl:param elements. If there is no xsl:on-completion element, the result is 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:on-completion>
        <balance date="{$prevDate}" 
                 value="{format-number($balance, '0.00')}"/>
      </xsl:on-completion>     
      <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: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: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: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: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, it is not possible to determine whether the item being processed is the last in a sequence without reading ahead. The lastFO30 function therefore 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 together with the copy-of function to maintain a one-element look-ahead by explicit coding:

<xsl:template match="section" mode="streaming">
   <xsl:iterate select="para">
     <xsl:param name="prev" select="()" as="element(para)?"/>
     <xsl:on-completion>
       <xsl:apply-templates select="$prev" mode="last-para"/>      
     </xsl:on-completion>
     <xsl:if test="$prev">
       <xsl:apply-templates select="$prev"/>
     </xsl:if>
     <xsl:next-iteration>
       <xsl:with-param name="prev" select="copy-of(.)"/>
     </xsl:next-iteration>
   </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 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
  rollback-output? = boolean >
  <!-- 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).

The rollback-output attribute is described in 8.3.1 Recovery of Result Trees. The default value is yes.

[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 implementers, 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:

VariableTypeValue
err:codexs:QNameThe error code
err:descriptionxs: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:valueitem()*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:modulexs: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-numberxs: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-numberxs: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).

    Note:

    • 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 (for example) errors caused by calling the errorFO30 function, or the xsl:message instruction with terminate="yes", or the xsl:assert instruction, or the xs:error constructor function.

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

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

  4. 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 roll back any changes made by these instructions. The same applies to any side effects caused by extension functions or extension instructions.

  5. A serialization error that occurs during the serialization of a secondary result produced using xsl:result-document is treated as a dynamic error in the evaluation of the xsl:result-document instruction, and may be caught (for example by an xsl:try instruction that contains the xsl:result-document instruction). A serialization error that occurs while serializing the principal result is treated as occurring after the transformation has finished, and cannot be caught.

  6. A validation error is treated as occurring in the instruction that requested validation. For example, if the stylesheet is producing XHTML output and requests validation of the entire result document by means of the attribute validation="strict" on the instruction that creates the outermost html element, then a validation failure can be caught only at that level. Although the validation error might be detected, for example, while writing a p element at a location where no p element is allowed, it is not treated as an error in the instruction that writes the p element and cannot be caught at that level.

  7. A type error may be caught if the processor raises it dynamically; this does not affect the processor’s right to raise the error statically if it chooses.

    The following rules are provided to define which expression is considered to fail when a type error occurs, and therefore where the error can be caught. The general principle is that where the semantics of a construct C place requirements on the type of some subexpression, a type error is an error in the evaluation of C, not in the evaluation of the subexpression.

    For example, consider the following construct:

    <xsl:variable name="v" as="xs:integer">
      <xsl:sequence select="$foo"/>
    </xsl:variable>
    

    The expected type of the result of the sequence constructor is xs:integer; if the value of variable $foo turns out to be a string, then a type error will occur. It is not possible to catch this by writing:

    <xsl:variable name="v" as="xs:integer">
      <xsl:try>
        <xsl:sequence select="$foo"/>
        <xsl:catch>...</xsl:catch>
      </xsl:try>
    </xsl:variable>
    

    This fails to catch the error because the xsl:sequence instruction is deemed to evaluate successfully; the failure only occurs when the result of this instruction is bound to the variable.

    A similar rule applies to functions: if the body of a function computes a result which does not conform to the required type of the function result, it is not possible to catch this error within the function body itself; it can only be caught by the caller of the function. Similarly, if an expression used to compute an argument to a function returns a value of the wrong type for the function signature, this is not considered an error in this expression, but an error in evaluating the function call as a whole.

    A consequence of these rules is that when a type error occurs while initializing a global variable (because the initializer returns a value of the wrong type, given the declared type of the variable), then this error cannot be caught.

    Note:

    Because processors are permitted to report type errors during static analysis, it is unwise to attempt to recover from type errors dynamically. The best strategy is generally to prevent their occurrence. For example, rather than writing $p + 1 where $p is a parameter of unknown type, and then catching the type error that occurs if $p is not numeric, it is better first to test whether $p is numeric, perhaps by means of an expression such as $p instance of my:numeric, where my:numeric is a union type with xs:double, xs:float, and xs:decimal as its member types.

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

8.3.1 Recovery of Result Trees

The XSLT language is designed so that a processor that chooses to execute instructions in document order will always append nodes to the result tree in document order, and never needs to update a result tree in situ. As a result, it is normal practice for XSLT processors to stream the result tree directly to its final destination (for example, a serializer) without ever holding the tree in memory. This applies whether or not the processor is streamable, and whether or not source documents are streamed.

The language specification states (see 2.12 Error Handling) that when a transformation terminates with a dynamic error, the state of persistent resources affected by the transformation (for example, serialized result documents) is implementation-defined, so processors are not required to take any special steps to recover such resources to their pre-transformation state; at the same time, there is no guarantee that secondary result documents produced before the failure occurs will be in a usable state.

The situation becomes more complicated when dynamic errors occur while writing to a result tree, and the dynamic error is caught by an xsl:try/xsl:catch instruction. The semantics of these instructions requires that when an error occurring during the evaluation of xsl:try is caught, the result of the xsl:try instruction is the result of the relevant xsl:catch. To achieve this, any output written to the result tree during the execution of xsl:try until the point where the error occurs must effectively be undone. There are two basic strategies for achieving this: either the updates are not committed to persistent storage until the xsl:try instruction is completed, or the updates are written in such a way that they can be rolled back in the event of a failure.

Both these strategies are potentially expensive, and both have an adverse effect on streaming, in that they affect the amount of memory needed to transform large amounts of data. XSLT 3.0 therefore provides an option to relax the requirement to recover result trees when failures occur in the course of evaluating an xsl:try instruction. This option is invoked by specifying rollback-output="no" on the xsl:try instruction.

The default value of the attribute is rollback-output="yes".

The effect of specifying rollback-output="no" on xsl:try is as follows: if a dynamic error occurs in the course of evaluating the xsl:try instruction, and if the failing construct is evaluated in final output state while writing to some result document, then it is implementation-dependent whether an attempt to catch this error using xsl:catch will be successful. If the attempt is successful, then the xsl:try instruction succeeds, delivering the result of evaluating the xsl:catch clause, and the transformation proceeds as normal. If the attempt is unsuccessful (typically, because non-recoverable updates have already been made to the result tree), then the xsl:try instruction as a whole fails with a dynamic error. The state of this result document will then be undefined, but the transformation can ignore the failure and continue to produce other result documents, for example by wrapping the xsl:result-document instruction in an xsl:try instruction that catches the relevant error.

[ERR XTDE3530] It is a dynamic error if an xsl:try instruction is unable to recover the state of a final result tree because recovery has been disabled by use of the attribute rollback-output="no".

For example, consider the following:

<xsl:result-document href="out.xml">     
  <xsl:try rollback-output="no">
    <xsl:stream href="in.xml">
      <xsl:copy-of select="."/>
    </xsl:stream>
    <xsl:catch errors="*">
       <error code="{$err:code}" message="{$err:description}" file="in.xml"/>
    </xsl:catch>
  </xsl:try>
</xsl:result-document>

The most likely failure to occur here is a failure to read the streamed input file in.xml. In the common case where this failure is detected immediately, for example if the file does not exist or the network connection is down, no output will have been written to the result document, and the attempt to catch the error is likely to be successful. If however a failure is detected after several megabytes of data have been copied to out.xml, for example an XML well-formedness error in the input file, or a network failure that occurs while reading the file, recovery of the output file may be impossible. In this situation the xsl:result-document instruction will fail with a dynamic error. It is possible to catch this error, but the state of the file out.xml will be unpredictable.

Note that adding an xsl:try instruction as a child of xsl:stream does not help. Any error reading the input file (such as a well-formedness error) is an error in the xsl:stream instruction and can only be caught at that level.

When rollback-output="no" is specified, it is still possible to ensure recovery of errors happens predictably by evaluating the potentially-failing code in temporary output state: typically, within an xsl:variable. In effect the variable acts as an explicit buffer for temporary results, which is only copied to the final output if evaluation succeeds.

Note:

An application might wish to ensure that when a fatal error occurs while reading an input stream, data written to persistent storage up to the point of failure is available after the transformation terminates. Setting rollback-output="no" does not guarantee this, but a processor might choose to interpret this as the intent.

Changing the attribute to rollback-output="yes" makes the stylesheet more robust and able to handle error conditions predictably, but the cost may be substantial; for example it may be necessary to buffer the whole of the result document in memory.

8.3.2 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:FOAR0001" 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>

8.4 Conditional Content Construction

The facilities described in this section are designed to make it easier to generate result trees conditionally depending on what is found in the input, without violating the rules for streamability. These facilities are available whether or not streaming is in use, but they are introduced to the language specifically to make streaming easier.

The facilities are introduced first by example:

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, because it processes the child event elements more than once. To make it streamable, it can be rewritten as:

<xsl:where-populated>
  <events>
    <xsl:copy-of select="event"/>
  </events>
</xsl:where-populated>

The effect of the xsl:where-populated instruction, as explained later, is to avoid outputting the events element if it would have no children. A streaming implementation will typically hold the start tag of the events element in a buffer, to be sent to the output destination only if and when a child node is generated.

 

Example: Generating a Header and Footer only if there is Content

The following example generates an h3 element and a summary paragraph only if a list of items is non-empty. The code could be written like this:

<xsl:if test="exists(item-for-sale)">
  <h1>Items for Sale</h1>
</xsl:if>  
<xsl:apply-templates select="item-for-sale"/>
<xsl:if test="exists(item-for-sale)">
  <p>Total value: {accumulator-before('total-value')}</p>
</xsl:if>

However, the above code would not be guaranteed-streamable, because it processes the child item-for-sale elements more than once. To make it streamable, it can be rewritten as:

<xsl:sequence>
  <xsl:on-non-empty>
    <h1>Items for Sale</h1>
  </xsl:on-non-empty>  
  <xsl:apply-templates select="item-for-sale"/>
  <xsl:on-non-empty>
    <p>Total value: {accumulator-before('total-value')}</p>
  </xsl:on-non-empty>  
</xsl:sequence>

The effect of the xsl:on-non-empty instruction, as explained later, is to output the enclosed content only if the containing sequence constructor also generates “ordinary” content, that is, if there is content generated by instructions other than xsl:on-empty and xsl:on-non-empty instructions.

 

Example: Generating Substitute Text when there is no Content

The following example generates a summary paragraph only if a list of items is empty. The code could be written like this:

<xsl:apply-templates select="item-for-sale"/>
<xsl:if test="empty(item-for-sale)">
  <p>There are no items for sale.</p>
</xsl:if>

However, the above code would not be guaranteed-streamable, because it processes the child item-for-sale elements more than once (the fact that the list is empty is irrelevant, because streamability is determined statically). To make the code streamable, it can be rewritten as:

<xsl:sequence>
  <xsl:apply-templates select="item-for-sale"/>
  <xsl:on-empty>
    <p>There are no items for sale.</p>
  </xsl:on-empty>
</xsl:sequence>

The effect of the xsl:on-empty instruction, as explained later, is to output the enclosed content only if the containing sequence constructor generates no “ordinary” content, that is, if there is no content generated by instructions other than xsl:on-empty and xsl:on-non-empty instructions.

Note:

In some cases, similar effects can be achieved by using the has-childrenFO30 function, which tests whether an element has child nodes without consuming the children. However, use of has-childrenFO30 has the drawback that the function is unselective: it cannot be used to test whether there are any children of relevance to the application. In particular, it returns true if an element contains comments or whitespace text nodes that the application might consider to be insignificant.

Note:

There are no special streamability rules for the three instructions xsl:where-populated, xsl:on-empty, or xsl:on-non-empty. The general streamability rules apply. In many cases the xsl:on-empty and xsl:on-non-empty instructions will generate content that does not depend on the source document, and they will therefore be motionless, but this is not required.

8.4.1 The xsl:where-populated instruction

<!-- Category: instruction -->
<xsl:where-populated>
  <!-- Content: sequence-constructor -->
</xsl:where-populated>

The xsl:where-populated instruction encloses a sequence constructor. The result of the instruction is established as follows:

  1. The sequence constructor is evaluated in the usual way (taking into account any xsl:on-empty and xsl:on-non-empty instructions) to produce a result $R.

  2. The result of the instruction is the value of the expression $R[not(deemed-empty(.))] where the function deemed-empty($item as item()) returns true if and only if $item is one of the following:

    • A document or element node that has no children.

      Note:

      If an element has attributes or namespaces, these do not prevent the element being deemed empty.

      If a document or element node has children, the node is not deemed empty, even if the children are empty. For example, a document node created using an xsl:variable instruction in the form <xsl:variable name="temp"><a/></xsl:variable> is not deemed empty, even though the contained <a/> element is empty.

    • A node, other than a document or element node, whose string value is zero-length.

      Note:

      A whitespace-only text node is not deemed empty.

    • An atomic value such that the result of casting the atomic value to a string is zero-length.

      Note:

      This can happen only when the atomic value is of type xs:string, xs:anyURI, xs:untypedAtomic, xs:hexBinary, or xs:base64Binary.

    • A map whose size (number of key/value pairs) is zero.

    • An array (see 27.7.1 Arrays) with no members.

Example: Generating an HTML list

The following example generates an HTML unnumbered list, if and only if the list is non-empty. Note that the presence of the class attribute does not make the list non-empty. The code is written to be streamable.

<xsl:where-populated>
  <ul class="my-list">
    <xsl:for-each select="source-item">
       <li><xsl:value-of select="."/></li>
    </xsl:for-each>
  </ul>
</xsl:where-populated>

8.4.2 The xsl:on-empty instruction

<!-- Category: instruction -->
<xsl:on-empty
  select? = expression >
  <!-- Content: sequence-constructor -->
</xsl:on-empty>

The xsl:on-empty instruction has the same content model as xsl:sequence, and when it is evaluated, the same rules apply. In particular, the select attribute and the contained sequence constructor are mutually exclusive [see ERR XTSE3185].

When an xsl:on-empty instruction appears in a sequence constructor, then:

  1. It must be the only xsl:on-empty instruction in the sequence constructor, and

  2. It must not be followed in the sequence constructor by any other instruction, other than xsl:fallback, or by a significant text node (that is, a text node that has not been discarded under the provisions of 4.3 Stripping Whitespace from the Stylesheet), or by a literal result element. It may, however, be followed by non-instructions such as xsl:catch where appropriate.

An xsl:on-empty instruction is evaluated only if every preceding sibling instruction, text node, and literal result element in the same sequence constructor returns either an empty sequence, or a sequence consisting entirely of zero-length text nodes and/or document nodes with no children.

Note:

The xsl:on-empty instruction will often be used as part of a sequence constructor used to construct the content of an element. In such case the rules of 5.7.1 Constructing Complex Content apply. Those rules eliminate zero-length text nodes and childless document nodes from the result of the sequence constructor. For that reason, xsl:on-empty also ignores such nodes.

If xsl:on-empty is the only instruction in a sequence constructor then it is always evaluated.

If xsl:on-empty and xsl:on-non-empty appear in the same sequence constructor, then the rules ensure that only one of them will be evaluated.

8.4.3 The xsl:on-non-empty instruction

<!-- Category: instruction -->
<xsl:on-non-empty
  select? = expression >
  <!-- Content: sequence-constructor -->
</xsl:on-non-empty>

The xsl:on-non-empty instruction has the same content model as xsl:sequence, and when it is evaluated, the same rules apply. In particular, the select attribute and the contained sequence constructor are mutually exclusive [see ERR XTSE3185].

An xsl:on-non-empty instruction is evaluated only if there is at least one sibling node in the same sequence constructor, excluding xsl:on-empty and xsl:on-non-empty instructions, whose evaluation yields a sequence containing an item other than a zero-length text node or a document node with no children. If this condition applies, then all xsl:on-non-empty instructions in the containing sequence constructor are evaluated, and their results are included in the result of the containing sequence constructor in their proper positions.

Note:

Unlike xsl:on-empty, the xsl:on-non-empty instruction can appear anywhere in a sequence constructor, and can appear more than once.

8.4.4 Evaluating xsl:on-empty and xsl:on-non-empty Instructions

The following non-normative algorithm explains one possible strategy for streamed evaluation of a sequence constructor containing xsl:on-empty and/or xsl:on-non-empty instructions.

The algorithm makes use of the following mutable variables:

  • L : a list of instructions awaiting evaluation. Initially empty.

  • R : a list of items to act as the result of the evaluation. Initially empty.

  • F : a boolean flag, initially false, to indicate whether any significant items have been written to R by ordinary instructions. The term significant item here means any item other than a zero-length text node or childless document node, and the term ordinary instruction means any node in the sequence constructor other than an xsl:on-empty or xsl:on-non-empty instruction.

The algorithm is as follows:

  1. The nodes in the sequence constructor are evaluated in document order.

  2. When an xsl:on-non-empty instruction is encountered, then:

    1. If F is true, the instruction is evaluated and the result is appended to R.

    2. Otherwise, the instruction is appended to L.

  3. When an ordinary instruction is evaluated:

    1. The results of the evaluation are appended to R, in order.

    2. When a significant item is about to be appended to R, and F is false, then before appending the item to R, the following actions are taken:

      1. Any xsl:on-non-empty instructions in L are evaluated, in order, and their results are appended to R.

      2. F is set to true.

  4. When an xsl:on-empty instruction is encountered, then:

    1. If F is true, the instruction is ignored.

    2. Otherwise, the instruction is evaluated and its results are appended to R.

  5. The result of the sequence constructor is the list of items in R.

8.4.5 A More Complex Example

This example shows how the three instructions xsl:where-populated, xsl:on-empty, and xsl:on-non-empty may be combined.

Example: Generating a Table only if there is Content

The following example generates a table containing the names and ages of a set of students; if there are no students, it substitutes a paragraph explaining this.

<div id="students">
<xsl:where-populated>
   <table>
      <xsl:on-non-empty>
         <thead>
            <tr><th>Name</th><th>Age</th></tr>
         </thead>
      </xsl:on-non-empty>
      <xsl:where-populated>
         <tbody>
            <xsl:for-each select="student/copy-of()">
               <tr>
                  <td><xsl:value-of select="name"/></td>
                  <td><xsl:value-of select="age"/></td>
               </tr>
            </xsl:for-each>
         </tbody>
      </xsl:where-populated>
   </table>
</xsl:where-populated>
<xsl:on-empty>
   <p>There are no students</p>
</xsl:on-empty>
</div>

Explanation:

  • The xsl:where-populated around the table element ensures that if there is no thead and no tbody, then there will be no table.

  • The xsl:on-non-empty surrounding the thead element ensures that the thead element is not output unless the tbody element is output.

  • The xsl:where-populated around the tbody element ensures that the tbody element is not output unless there is at least one table row (tr).

  • The xsl:on-empty around the p element ensures that if no table is output, then the paragraph There are no students is output instead.

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

9.1 Variables

<!-- Category: declaration -->
<!-- Category: instruction -->
<xsl:variable
  name = eqname
  select? = expression
  as? = sequence-type
  static? = boolean
  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.1 Qualified Names.

The xsl:variable element has an optional as attribute, which specifies the required type of the variable. The value of the as attribute is a SequenceType.

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

For the effect of the static attribute, see 9.6 Static Variables and Parameters.

The visibility attribute must not be specified for a local variable: that is, it is allowed only when the parent element is xsl:stylesheet, xsl:transform, 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? = boolean
  tunnel? = boolean
  static? = boolean >
  <!-- Content: sequence-constructor -->
</xsl:param>

The xsl:param element may be used:

The attributes applicable to xsl:param depend on its parent element in the stylesheet, as defined by the following table:

Elementnameselectasrequiredtunnelstatic
xsl:packagemandatoryoptionaloptionalyes|nonoyes|no
xsl:stylesheetmandatoryoptionaloptionalyes|nonoyes|no
xsl:templatemandatoryoptionaloptionalyes|noyes|nono
xsl:functionmandatorydisallowedoptionalyesnono
xsl:iteratemandatorymandatoryoptionalnonono

In the table, the entries for the name, select, and as attributes indicate whether the attribute must appear, is optional, or must be absent; the entries for the required, tunnel, and static attributes indicate the values that are permitted if the attribute is present, with the default value shown in bold. (The value yes can also be written true or 1, while no can also be written false or 0.)

The name attribute is mandatory: it specifies the name of the parameter. The value of the name attribute is an EQName, which is expanded as described in 5.1.1 Qualified Names.

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

If the xsl:param element has a select attribute, then the sequence constructor must be empty.

The static attribute can take the value yes only on stylesheet parameters, and is explained in 9.5 Global Variables and Parameters.

Note:

Local variables may shadow template parameters and function parameters: see 9.9 Scope of Variables.

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

9.2.1 The Required Type of a Parameter

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 SequenceType. If the as attribute is omitted, then the required type is item()*.

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 default value is used as the supplied value as described in 9.2.2 Default Values of Parameters.

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.

9.2.2 Default Values of Parameters

The optional required attribute of xsl:param may be used to indicate that a stylesheet parameter or template parameter is mandatory. The only value permitted for a function parameter is yes (these are always mandatory), and the only value permitted for a parameter to xsl:iterate is no (these are always initialized to a default value).

[Definition: A parameter is explicitly mandatory if it is a function parameter, or if the required attribute is present and has the value yes.] If a parameter is explicitly mandatory, then the xsl:param element must be empty and must not have a select attribute.

If a parameter is not explicitly mandatory, then it may have a default value. The default value is obtained by evaluating the expression given in the select attribute or the contained sequence constructor, as described in 9.3 Values of Variables and Parameters.

Note:

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

[Definition: An explicit default for a parameter is indicated by the presence of either a select attribute or a non-empty sequence constructor.]

[Definition: If a parameter that is not explicitly mandatory has no explicit default value, then it has an implicit default value, which is the empty sequence if there is an as attribute, or a zero-length string if not.]

[Definition: If a parameter has an implicit default value which cannot be converted to the required type (that is, if it has an as attribute which does not permit the empty sequence), then the parameter is implicitly mandatory.]

Note:

The effect of these rules is that specifying <xsl:param name="p" as="xs:date" select="2"/> is an error, but if the default value of the parameter is never used, then the processor has discretion whether or not to 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.

Various errors can arise with regard to mandatory parameters when no value is supplied. In the rules below, non-tunnel means: not having a tunnel attribute with the value yes.

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 attributeas attributecontentEffect
presentabsentemptyValue is obtained by evaluating the select attribute
presentpresentemptyValue is obtained by evaluating the select attribute, adjusted to the type required by the as attribute
presentabsentpresentStatic error
presentpresentpresentStatic error
absentabsentemptyValue is a zero-length string
absentpresentemptyValue is an empty sequence, provided the as attribute permits an empty sequence
absentabsentpresentValue is a document node whose content is obtained by evaluating the sequence constructor
absentpresentpresentValue 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 this newly constructed document node. The content of the document node is formed from the result of evaluating the sequence constructor contained within the variable-binding element, as described in 5.7.1 Constructing Complex Content.

Note:

The construct:

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

can be regarded as a shorthand for:

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

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

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

Note:

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

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

A temporary tree is available for processing in exactly the same way as any source document. For example, its nodes are accessible using path expressions, and they can be processed using instructions such as xsl:apply-templates and xsl:for-each. Also, the key and 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:package or xsl:stylesheet element.

[Definition: A top-level variable-binding element declares a global variable that is visible everywhere (except within its own declaration, and 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 package contains more than one non-hidden binding of a global variable with the same name and same import precedence, unless it also contains another binding with the same name and higher import precedence.

For a global variable or the default value of a stylesheet parameter, the expression or sequence constructor specifying the variable value is evaluated with a singleton focus as follows:

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 the focus is absent. The values of other components of the dynamic context are the initial values as defined in 5.3.3 Initializing the Dynamic Context and 5.3.4 Additional Dynamic Context Components used by XSLT.

The visibility of a stylesheet parameter is always (implicitly) private if the parameter is static, or public if the parameter is non-static.

Note:

This rule has the effect that after combining all the packages making up a stylesheet, the non-static stylesheet parameters whose values are required necessarily have distinct names, which simplifies the design of APIs.

For the effect of the static attribute, see 9.6 Static Variables and Parameters.

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

If the visibility attribute is present with the value abstract then the select attribute must be absent and the contained sequence 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.

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 Static Variables and Parameters

Static variables and parameters are global variables and can be used in the same way as other global variables. In addition, they can be used in [xsl:]use-when expressions and in shadow attributes.

[Definition: A top-level variable-binding element having the attribute static="yes" declares a static variable: that is, a global variable whose value is known during static analysis of the stylesheet.]

[Definition: A static variable declared using an xsl:param element is referred to as a static parameter.]

The static attribute must not take the value yes on an xsl:variable or xsl:param element unless it is a top-level element.

When the static attribute is present with the value yes, the visibility attribute must not have a value other than private.

Note:

This rule prevents static variables being overridden in another package. Since the values of such variables may be used at compile time (for example, during processing of [xsl:]use-when expressions), the rule is necessary to ensure that packages can be independently compiled.

It is possible to make the value of a static variable or parameter available in a using package by binding a non-static public variable to its value, for example:

     <xsl:param name="DEBUG" static="yes" select="true()"/>
     <xsl:variable name="tracing" static="no" visibility="public" select="$DEBUG"/>
     
                 

When the attribute static="yes" is specified, the xsl:variable or xsl:param element must have empty content. In the case of xsl:variable the select attribute must be present to define the value of the variable.

If the select attribute is present, then it is evaluated using the rules for static expressions.

The rules for the scope of static variables, and the handling of duplicate declarations, are similar to the rules for non-static variables, but with additional constraints designed to disallow forwards references. The reason for disallowing forwards references is to ensure that use-when attributes can always be evaluated as early as possible, and in particular to ensure that the value of a use-when attribute never has circular dependencies. The additional constraints are as follows:

  1. The static context for evaluation of a static expression only contains those static variables visible within the containing package whose declarations occur prior to the element containing the static expression in stylesheet tree order. Stylesheet tree order is the order that results when all xsl:import and xsl:include declarations are replaced by the declarations in the imported or included stylesheet module. A static variable is not in scope within its own declaration.

  2. If two static variables declared within the same package have the same name, the one that has higher import precedence is used (it is a consequence of rules defined elsewhere that there cannot be more than one declaration with highest import precedence). However, if the declaration with higher import precedence occurs after the one with lower import precedence in stylesheet tree order, then the two declarations must be consistent. For this purpose two declarations are consistent if (a) they are either both xsl:variable elements, or both xsl:param elements, and (b) if the variables are initialized (that is, if the elements are xsl:variable elements, or if they are xsl:param elements and no value for the parameter is externally supplied) then the values of both variables must be identicalFO30, and must not contain function items.

    Note:

    This rule ensures that when a static variable reference is encountered, the value of the most recently declared static variable with that name can be used, knowing that this value cannot be overridden by a subsequent declaration having higher import precedence.

    [ERR XTSE3450] It is a static error if a variable declared with static="yes" is inconsistent with another static variable of the same name that is declared earlie