![]() |
![]() | ![]() | ![]() | XSL Transformations (XSLT) Version 2.0XSL Transformations (XSLT) Version 2.0W3C Recommendation 23 January 2007
Please refer to the errata for this document, which may include some normative corrections. See also translations. Copyright © 2007 W3C® (MIT, ERCIM, Keio), All Rights Reserved. W3C liability, trademark and document use rules apply. AbstractThis specification defines the syntax and semantics of XSLT 2.0, a language for transforming XML documents into other XML documents. XSLT 2.0 is a revised version of the XSLT 1.0 Recommendation [XSLT 1.0] published on 16 November 1999. XSLT 2.0 is designed to be used in conjunction with XPath 2.0, which is defined in [XPath 2.0]. XSLT shares the same data model as XPath 2.0, which is defined in [Data Model], and it uses the library of functions and operators defined in [Functions and Operators]. XSLT 2.0 also includes optional facilities to serialize the results of a transformation, by means of an interface to the serialization component described in [XSLT and XQuery Serialization]. This document contains hyperlinks to specific sections or definitions within other documents in this family of specifications. These links are indicated visually by a superscript identifying the target specification: for example XP for XPath, DM for the XDM data model, FO for Functions and Operators. Status of this DocumentThis 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 Recommendation builds on the success of [XSLT 1.0], which was published on 16 November 1999. Many new features have been added to the language (see J.2 New Functionality) while retaining a high level of backwards compatibility (see J.1 Incompatible Changes). The changes have been designed to meet the requirements for XSLT 2.0 described in [XSLT 2.0 Requirements]. The way in which each requirement has been addressed is outlined in I Checklist of Requirements. XSLT 2.0 depends on a number of other specifications that have progressed to Recommendation status at the same time: see [XPath 2.0], [Data Model], [Functions and Operators], and [XSLT and XQuery Serialization]. These subsidiary documents are also referenced in the specification of XQuery 1.0. This document has been produced by the XSL Working Group, which is part of the XML Activity. The document has been reviewed by W3C Members and other interested parties, and is endorsed by the Director. It is a stable document and may be used as reference material or cited as a normative reference from another document. W3C's role in making the Recommendation is to draw attention to the specification and to promote its widespread deployment. This enhances the functionality and interoperability of the Web. A small number of editorial corrections and clarifications have been made to the document since it was published as a Proposed Recommendation on 21 November 2006. These changes are listed at J.2.4 Changes since Proposed Recommendation. Please record any comments about this document in 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 is helpful to include the string [XSLT] in the subject line of your comment, whether made in Bugzilla or in email. Each Bugzilla entry and email message should contain only one comment. Archives of the comments and responses are available at http://lists.w3.org/Archives/Public/public-qt-comments/. General public discussion of XSLT takes place on the XSL-List forum. 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 Contents1 Introduction AppendicesA References 1 Introduction1.1 What is XSLT?This specification defines the syntax and semantics of the XSLT 2.0 language. [Definition: A transformation in the XSLT language is expressed in the form of a stylesheet, whose syntax is well-formed XML [XML 1.0] conforming to the Namespaces in XML Recommendation [Namespaces in XML 1.0].] A stylesheet generally includes elements that are
defined by XSLT as well as elements that are not defined by
XSLT. XSLT-defined elements are distinguished by use of the
namespace 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 [Extensible Stylesheet Language (XSL)]), or into another presentation-oriented format such as HTML, XHTML, or SVG. However, XSLT is used for a wide range of transformation tasks, not exclusively for formatting and presentation applications. A transformation expressed in XSLT describes rules for transforming zero or more source trees into one or more result trees. The structure of these trees is described in [Data Model]. The transformation is achieved by a set of template rules. A template rule associates a pattern, which matches nodes in the source document, with a sequence constructor. In many cases, evaluating the sequence constructor will cause new nodes to be constructed, which can be used to produce part of a result tree. The structure of the result trees can be completely different from the structure of the source trees. In constructing a result tree, nodes from the source trees can be filtered and reordered, and arbitrary structure can be added. This mechanism allows a stylesheet to be applicable to a wide class of documents that have similar source tree structures. [Definition: A stylesheet may consist of several
stylesheet modules, contained
in different XML documents. For a given transformation, one
of these functions as the principal stylesheet
module. The complete stylesheet is assembled by finding the
stylesheet modules referenced
directly or indirectly from the principal stylesheet module
using 1.2 What's New in XSLT 2.0?XSLT 1.0 was published in November 1999, and version 2.0 represents a significant increase in the capability of the language. A detailed list of changes is included in J Changes from XSLT 1.0. XSLT 2.0 has been developed in parallel with XPath 2.0 (see [XPath 2.0]), so the changes to XPath must be considered alongside the changes to XSLT. 2 Concepts2.1 TerminologyFor 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 result tree is used to refer to any tree constructed by instructions in the stylesheet. A result tree is either a final result tree or a temporary tree.] [Definition: A final result tree is a
result
tree that forms part of the final output of a
transformation. Once created, the contents of a final
result tree are not accessible within the stylesheet
itself.] The [Definition: The term source tree means any
tree provided as input to the transformation. This includes
the document containing the initial context node if
any, documents containing nodes supplied as the values of
stylesheet parameters,
documents obtained from the results of functions such as
[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. In this specification the phrases must, must not, should, should not, may, required, and recommended 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 21 Conformance. Where the phrase must, must not, or required relates to a stylesheet, then the processor must enforce this constraint on stylesheets by reporting an error if the constraint is not satisfied. Where the phrase should, should not, or recommended relates to a stylesheet, then a processor may produce warning messages if the constraint is not satisfied, but must not treat this as an error. [Definition: In this specification, the term implementation-defined refers to a feature where the implementation is allowed some flexibility, and where the choices made by the implementation must be described in documentation that accompanies any conformance claim.] [Definition: The term implementation-dependent refers to a feature where the behavior may vary from one implementation to another, and where the vendor is not expected to provide a full specification of the behavior.] (This might apply, for example, to limits on the size of source documents that can be transformed.) In all cases where this specification leaves the behavior implementation-defined or implementation-dependent, the implementation has the option of providing mechanisms that allow the user to influence the behavior. A paragraph labeled as a Note or described as an example is non-normative. Many terms used in this document are defined in the XPath specification [XPath 2.0] or the XDM specification [Data Model]. Particular attention is drawn to the following:
[Definition: The term core function means a function that is specified in [Functions and Operators] and that is in the standard function namespace.] 2.2 Notation[Definition: An XSLT element is an element in the XSLT namespace whose syntax and semantics are defined in this specification.] For a non-normative list of XSLT elements, see 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 syntax summary notation is as follows:
This example illustrates the notation used to describe XSLT elements.
This example defines a (non-existent) element
The content of an [ERR XTSE0010] A static error is signaled if an XSLT-defined element is used in a context where it is not permitted, if a required attribute is omitted, or if the content of the element does not correspond to the content that is allowed for the element. Attributes are validated as follows. These rules apply to the value of the attribute after removing leading and trailing whitespace.
Special rules apply if the construct appears in part of the stylesheet that is processed with forwards-compatible behavior: see 3.9 Forwards-Compatible Processing. [Definition: Some constructs defined in this specification are described as being deprecated. The use of this term implies that stylesheet authors should not use the construct, and that the construct may be removed in a later version of this specification.] All constructs that are deprecated in this specification are also (as it happens) optional features that implementations are not required to provide. Note: This working draft includes a non-normative XML Schema for XSLT stylesheet modules (see G Schema for XSLT Stylesheets). The syntax summaries described in this section are normative. XSLT defines a set of standard functions which are additional to those defined in [Functions and Operators]. The signatures of these functions are described using the same notation as used in [Functions and Operators]. The names of these functions are all in the standard function namespace. 2.3 Initiating a TransformationThis document does not specify any application programming interfaces or other interfaces for initiating a transformation. This section, however, describes the information that is supplied when a transformation is initiated. Except where otherwise indicated, the information is required. Implementations may allow a transformation to run as two or more phases, for example parsing, compilation and execution. Such a distinction is outside the scope of this specification, which treats transformation as a single process controlled using a set of stylesheet modules, supplied in the form of XML documents. The following information is supplied to execute a transformation:
[ERR XTDE0040] It is a non-recoverable dynamic error if the invocation of the stylesheet specifies a template name that does not match the expanded-QName of a named template defined in the stylesheet. [ERR XTDE0045] It is a non-recoverable dynamic
error if the invocation of the stylesheet specifies an initial
mode (other than the
default mode) that does not match the expanded-QName in the
[ERR XTDE0047] It is a non-recoverable dynamic error if the invocation of the stylesheet specifies both an initial mode and an initial template. [ERR XTDE0050] It is a non-recoverable dynamic
error if the stylesheet that is invoked declares a
visible stylesheet parameter with
[Definition: The transformation is performed by
evaluating an initial template. If a named
template is supplied when the transformation is
initiated, then this is the initial template;
otherwise, the initial template is the template rule
selected according to the rules of the Parameters passed to the transformation by the client application are matched against stylesheet parameters (see 9.5 Global Variables and Parameters), not against the template parameters declared within the initial template. All template parameters within the initial template to be executed will take their default values. [ERR XTDE0060] It is a non-recoverable dynamic
error if the initial template defines a
template parameter that
specifies 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 2.4 Executing a Transformation[Definition: A stylesheet contains a set of template rules (see 6 Template Rules). A template rule has three parts: a pattern that is matched against nodes, a (possibly empty) set of template parameters, and a sequence constructor that is evaluated to produce a sequence of items.] In many cases these items are newly constructed nodes, which are then written to a result tree. A transformation as a whole is executed by evaluating the sequence constructor of the initial template as described in 5.7 Sequence Constructors. If the initial template has an
<xsl:template name="IMPLICIT">
<xsl:result-document href="">
<xsl:call-template name="T"/>
</xsl:result-document>
</xsl:template>
An implicit result tree is also created when the result
sequence is empty, provided that no Note: This means that there is always at least one result
tree. It also means that if the content of the initial
template is a single If the result of the initial template is non-empty,
and an explicit 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 Extension instructions are described in 18.2 Extension Instructions. The main categories of XSLT instruction are as follows:
Often, a sequence constructor will
include an 2.5 The Evaluation ContextThe results of some expressions and instructions in a stylesheet may depend on information provided contextually. This context information is divided into two categories: the static context, which is known during static analysis of the stylesheet, and the dynamic context, which is not known until the stylesheet is evaluated. Although information in the static context is known at analysis time, it is sometimes used during stylesheet evaluation. Some context information can be set by means of declarations within the stylesheet itself. For example, the namespace bindings used for any XPath expression are determined by the namespace declarations present in containing elements in the stylesheet. Other information may be supplied externally or implicitly: an example is the current date and time. The context information used in processing an XSLT
stylesheet includes as a subset all the context information
required when evaluating XPath expressions. The XPath 2.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 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 (it may be a node or an
atomic value) currently being processed. The value of the
context item can be referenced within an XPath expression
using the expression Full details of the static and dynamic context are provided in 5.4 The Static and Dynamic Context. 2.6 Parsing and SerializationAn XSLT stylesheet describes a process that constructs a set of final result trees from a set of source trees. The stylesheet does not describe how a source tree is constructed. Some possible ways of constructing source trees are described in [Data Model]. Frequently an implementation will operate in conjunction with an XML parser (or more strictly, in the terminology of [XML 1.0], an XML processor), to build a source tree from an input XML document. An implementation may also provide an application programming interface allowing the tree to be constructed directly, or allowing it to be supplied in the form of a DOM Document object (see [DOM Level 2]). This is outside the scope of this specification. Users should be aware, however, that since the input to the transformation is a tree conforming to the XDM data model as described in [Data Model], constructs that might exist in the original XML document, or in the DOM, but which are not within the scope of the data model, cannot be processed by the stylesheet and cannot be guaranteed to remain unchanged in the transformation output. Such constructs include CDATA section boundaries, the use of entity references, and the DOCTYPE declaration and internal DTD subset. [Definition: A frequent requirement is to output a final result tree as an XML document (or in other formats such as HTML). This process is referred to as serialization.] Like parsing, serialization is not part of the
transformation process, and it is not required that an XSLT processor must be able to perform serialization.
However, for pragmatic reasons, this specification
describes declarations (the 2.7 ExtensibilityXSLT 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 18.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 18.2
Extension Instructions. A stylesheet that uses
extension instructions must declare that it is doing so by
using the 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 18 Extensibility and Fallback. The XSLT language can also be extended by the use of extension attributes (see 3.3 Extension Attributes), and by means of user-defined data elements (see 3.6.2 User-defined Data Elements). 2.8 Stylesheets and XML SchemasAn XSLT stylesheet can make use of information from a schema. An XSLT transformation can take place in the absence of a schema (and, indeed, in the absence of a DTD), but where the source document has undergone schema validity assessment, the XSLT processor has access to the type information associated with individual nodes, not merely to the untyped text. Information from a schema can be used both statically (when the stylesheet is compiled), and dynamically (during evaluation of the stylesheet to transform a source document). There are places within a stylesheet, and within XPath expressions and patterns in a stylesheet, where it is possible to refer to named type definitions in a schema, or to element and attribute declarations. For example, it is possible to declare the types expected for the parameters of a function. This is done using the SequenceType XP syntax defined in [XPath 2.0]. [Definition: Type definitions and element and attribute declarations are referred to collectively as schema components.] [Definition: The schema components that may be referenced by name in a stylesheet are referred to as the in-scope schema components. This set is the same throughout all the modules of a stylesheet.] The conformance rules for XSLT 2.0, defined in 21 Conformance, distinguish
between a basic XSLT processor and a
schema-aware XSLT
processor. As the names suggest, a basic XSLT processor
does not support the features of XSLT that require access
to schema information, either statically or dynamically. A
stylesheet
that works with a basic XSLT processor will 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
There is a standard set of type definitions that are always available as in-scope schema components in every stylesheet. These are defined in 3.13 Built-in Types. The set of built-in types varies between a basic XSLT processor and a schema-aware XSLT processor. 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 The 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. Further, importing a schema does not of itself say anything about the type of the source document that the stylesheet is expected to process. The imported type definitions can be used for temporary nodes or for nodes on 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: <xsl:template match="document-node(schema-element(my:invoice))" priority="2"> . . . </xsl:template> <xsl:template match="document-node()" priority="1"> <xsl:message terminate="yes">Source document is not an invoice</xsl:message> </xsl:template> This example will cause the transformation to fail
with an error message unless the document element of the
source document is valid against the top-level element
declaration 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
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.9 Error Handling) type errors that are detected early may be reported as static errors. In addition an implementation may report any condition found during static analysis as a warning, provided that this does not prevent the stylesheet being evaluated as described by this specification. A stylesheet can also control the type annotations of nodes that it constructs in a final result tree, or in temporary trees. This can be done in a number of ways.
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 19.2 Validation. 2.9 Error Handling[Definition: An error that is detected by examining a stylesheet before execution starts (that is, before the source document and values of stylesheet parameters are available) is referred to as a static error.] Errors classified in this specification as static errors must be signaled by all implementations: that is, the processor must indicate that the error is present. A static error must be signaled even if it occurs in a part of the stylesheet that is never evaluated. Static errors are never recoverable. After signaling a static error, a processor may continue for the purpose of signaling additional errors, but it must eventually terminate abnormally without producing any final result tree. There is an exception to this rule when the stylesheet specifies forwards-compatible behavior (see 3.9 Forwards-Compatible Processing). Generally, errors in the structure of the stylesheet, or in the syntax of XPath expressions contained in the stylesheet, are classified as static errors. Where this specification states that an element in the stylesheet must or must not appear in a certain position, or that it must or must not have a particular attribute, or that an attribute must or must not have a value satisfying specified conditions, then any contravention of this rule is a static error unless otherwise specified. [Definition: An error that is not detected until a source document is being transformed is referred to as a dynamic error.] [Definition: Some dynamic errors are classed as recoverable errors. When a recoverable error occurs, this specification allows the processor either to signal the error (by reporting the error condition and terminating execution) or to take a defined recovery action and continue processing.] It is implementation-defined whether the error is signaled or the recovery action is taken. [Definition: If an implementation chooses to recover from a recoverable dynamic error, it must take the optional recovery action defined for that error condition in this specification.] When the implementation makes the choice between signaling a dynamic error or recovering, it is not restricted in how it makes the choice; for example, it may provide options that can be set by the user. When an implementation chooses to recover from a dynamic error, it may also take other action, such as logging a warning message. [Definition: A dynamic error that is not recoverable is referred to as a non-recoverable dynamic error. When a non-recoverable dynamic error occurs, the processor must signal the error, and 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 the final result trees without evaluating a particular construct, the implementation is never required to evaluate that construct solely in order to determine whether doing so causes a dynamic error. For example, if a variable is declared but never referenced, an implementation may choose whether or not to evaluate the variable declaration, which means that if evaluating the variable declaration causes a dynamic error, some implementations will signal this error and others will not. There are some cases where this specification requires
that a construct must not be
evaluated: for example, the content of an An implementation may signal a dynamic error before any source document is available, but only if it can determine that the error would be signaled for every possible source document and every possible set of parameter values. For example, some circularity errors fall into this category: see 9.8 Circular Definitions. The XPath specification states (see Section 2.3.1 Kinds of ErrorsXP) 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. An XPath processor may report statically that the
expression
<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 processor. (An XSLT 1.0 processor will execute this code successfully, returning positive infinity, because it uses double arithmetic rather than decimal arithmetic.) [Definition: Certain errors are classified as type errors. A type error occurs when the value supplied as input to an operation is of the wrong type for that operation, for example when an integer is supplied to an operation that expects a node.] If a type error occurs in an instruction that is actually evaluated, then it must be signaled in the same way as a non-recoverable dynamic error. Alternatively, an implementation may signal a type error during the analysis phase in the same way as a static error, even if it occurs in part of the stylesheet that is never evaluated, provided it can establish that execution of a particular construct would never succeed. It is implementation-defined whether type errors are signaled statically. The following construct contains a type error, because
<xsl:if test="false()"> <xsl:apply-templates select="42"/> </xsl:if> On the other hand, in the following example it is not
possible to determine statically whether the operand of
<xsl:template match="para"> <xsl:param name="p" as="item()"/> <xsl:apply-templates select="$p"/> </xsl:template> If more than one error arises, an implementation is not required to signal any errors other than the first one that it detects. It is implementation-dependent which of the several errors is signaled. This applies both to static errors and to dynamic errors. An implementation is allowed to signal more than one error, but if any errors have been signaled, it must not finish as if the transformation were successful. When a transformation signals one or more dynamic errors, the final state of any persistent resources updated by the transformation is implementation-dependent. Implementations are not required to restore such resources to their initial state. In particular, where a transformation produces multiple result documents, it is possible that one or more serialized result documents may be written successfully before the transformation terminates, but the application cannot rely on this behavior. Everything said above about error handling applies equally to errors in evaluating XSLT instructions, and errors in evaluating XPath expressions. Static errors and dynamic errors may occur in both cases. [Definition: If a transformation has successfully produced a final result tree, it is still possible that errors may occur in serializing the result tree. For example, it may be impossible to serialize the result tree using the encoding selected by the user. Such an error is referred to as a serialization error.] If the processor performs serialization, then it must do so as specified in 20 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
These error codes are used to label error conditions in this specification, and are summarized in E Summary of Error Conditions). They are provided primarily for ease of reference. Implementations may use these codes when signaling errors, but they are not required to do so. An API specification, however, may require the use of error codes based on these QNames. 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. Errors defined in the [XPath 2.0] and [Functions and Operators] specifications 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. 3 Stylesheet Structure[Definition: A stylesheet consists of one or more stylesheet modules, each one forming all or part of an XML document.] Note: A stylesheet module is represented by an XDM
element node (see [Data
Model]). In the case of a standard stylesheet
module, this will be an Although stylesheet modules will commonly be maintained in the form of documents conforming to XML 1.0 or XML 1.1, this specification does not mandate such a representation. As with source trees, the way in which stylesheet modules are constructed, from textual XML or otherwise, is outside the scope of this specification. A stylesheet module is either a standard stylesheet module or a simplified stylesheet module:
Both forms of stylesheet module (standard and simplified) can exist either as an entire XML document, or embedded as part of another XML document, typically but not necessarily a source document that is to be processed using the stylesheet. [Definition: A standalone stylesheet module is a stylesheet module that comprises the whole of an XML document.] [Definition: An embedded stylesheet module is a stylesheet module that is embedded within another XML document, typically the source document that is being transformed.] (see 3.11 Embedded Stylesheet Modules). There are thus four kinds of stylesheet module:
3.1 XSLT Namespace[Definition: The XSLT namespace has the URI
Note: The XSLT processors must use the XML namespaces mechanism [Namespaces in XML 1.0] to recognize elements and attributes from this namespace. Elements from the XSLT namespace are recognized only in the stylesheet and not in the source document. The complete list of XSLT-defined elements is specified in 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 18.2 Extension Instructions. This specification uses a prefix of Note: Throughout this specification, an element or attribute that is in no namespace, or an expanded-QName whose namespace part is an empty sequence, is referred to as having a null namespace URI. Note: The conventions used for the names of XSLT elements,
attributes and functions are that names are all
lower-case, use hyphens to separate words, and use
abbreviations only if they already appear in the syntax
of a related language such as XML or HTML. Names of types
defined in XML Schema however, are regarded as single
words and are capitalized exactly as in XML Schema. This
sometimes leads to composite function names such as
3.2 Reserved Namespaces[Definition: The XSLT namespace, together with certain other namespaces recognized by an XSLT processor, are classified as reserved namespaces and must be used only as specified in this and related specifications.] The reserved namespaces are those listed below.
Reserved namespaces may be used without restriction to refer to the names of elements and attributes in source documents and result documents. As far as the XSLT processor is concerned, reserved namespaces other than the XSLT namespace may be used without restriction in the names of literal result elements and user-defined data elements, and in the names of attributes of literal result elements or of XSLT elements: but other processors may impose restrictions or attach special meaning to them. Reserved namespaces must not be used, however, in the names of stylesheet-defined objects such as variables and stylesheet functions. Note: With the exception of the XML namespace, any of the above namespaces that are used in a stylesheet must be explicitly declared with a namespace declaration. Although conventional prefixes are used for these namespaces in this specification, any prefix may be used in a user stylesheet. [ERR XTSE0080] It is a static error to use a reserved namespace in the name of a named template, a mode, an attribute set, a key, a decimal-format, a variable or parameter, a stylesheet function, a named output definition, or a character map. 3.3 Extension Attributes[Definition: An element from the XSLT namespace may have any attribute not from the XSLT namespace, provided that the expanded-QName (see [XPath 2.0]) of the attribute has a non-null namespace URI. These attributes are referred to as extension attributes.] The presence of an extension attribute must not cause the final result trees produced by the transformation to be different from the result trees that a conformant XSLT 2.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 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
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
The following code might be used to indicate to a
particular implementation that the
<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
[ERR XTSE0090] It is a static error for an element from the XSLT namespace to have an attribute whose namespace is either null (that is, an attribute with an unprefixed name) or the XSLT namespace, other than attributes defined for the element in this document. 3.4 XSLT Media TypeThe media type The proposed definition of the media type is at B The XSLT Media Type This media type should be used for an XML document containing a standard stylesheet module at its top level, and it may also be used for a simplified stylesheet module. It should not be used for an XML document containing an embedded stylesheet module. 3.5 Standard Attributes[Definition: There are a number of standard
attributes that may appear on any XSLT element:
specifically 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
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 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 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
The effect of the 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 Note that the effect of these attributes does
not extend to stylesheet modules referenced
by For the detailed effect of each attribute, see the following sections:
3.6 Stylesheet Element
A stylesheet module is represented by an An [ERR XTSE0110] The value of the
If a stylesheet that specifies
When the value of the Note: XSLT 1.0 allowed the When developing a stylesheet that is designed to
execute under either XSLT 1.0 or XSLT 2.0, the
recommended practice is to create two alternative
stylesheet modules, one
specifying The effect of the The [ERR XTSE0120] An [Definition: An
element occurring as a child of an [Definition: Top-level elements fall into two categories: declarations, and user-defined data elements. Top-level elements whose names are in the XSLT namespace are declarations. Top-level elements in any other namespace are user-defined data elements (see 3.6.2 User-defined Data Elements)]. The declaration elements permitted in the
Note that the If there are 3.6.1 The
| ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| Component | Value |
|---|---|
| XPath 1.0 compatibility mode | false |
| In scope namespaces | determined by the in-scope namespaces for the containing element in the stylesheet |
| Default element/type namespace | determined by the
xpath-default-namespace attribute if
present (see 5.2
Unprefixed QNames in Expressions and
Patterns); otherwise the null namespace |
| Default function namespace | The standard function namespace |
| In scope type definitions | The type definitions that would be available in
the absence of any xsl:import-schema
declaration |
| In scope element declarations | None |
| In scope attribute declarations | None |
| In scope variables | None |
| In scope functions | The core functions defined in
[Functions and
Operators], together with the functions element-available,
function-available,
type-available,
and system-property
defined in this specification, plus the set of
extension functions that are present in the static
context of every XPath expression (other than a
use-when expression) within the content of the
element that is the parent of the
use-when attribute. Note that
stylesheet functions
are not included in the context, which means
that the function function-available
will return false in respect of such
functions. The effect of this rule is to ensure
that function-available
returns true in respect of functions that can be
called within the scope of the use-when
attribute. It also has the effect that these
extensions functions will be recognized within the
use-when attribute itself; however, the
fact that a function is available in this sense gives
no guarantee that a call on the function will
succeed. |
| In scope collations | Implementation-defined |
| Default collation | The Unicode Codepoint Collation |
| Base URI | The base URI of the containing element in the stylesheet |
| Statically known documents | None |
| Statically known collections | None |
| Component | Value |
|---|---|
| Context item, position, and size | Undefined |
| Dynamic variables | None |
| Current date and time | Implementation-defined |
| Implicit timezone | Implementation-defined |
| Available documents | None |
| Available collections | None |
Within a stylesheet module, all
expressions contained in [xsl:]use-when
attributes are evaluated in a single execution
scopeFO. This need not be the
same execution scope as that used for
[xsl]:use-when expressions in other stylesheet
modules, or as that used when evaluating XPath expressions
appearing elsewhere in the stylesheet module. This means
that a function such as
current-dateFO will
return the same result when called in different
[xsl:]use-when expressions within the same
stylesheet module, but will not necessarily return the same
result as the same call in an [xsl:]use-when
expression within a different stylesheet module, or as a
call on the same function executed during the
transformation proper.
The use of [xsl:]use-when is illustrated in
the following examples.
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.
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'"/>
Every XSLT 2.0 processor includes the following named type definitions in the in-scope schema components:
All the primitive atomic types defined in [XML Schema Part 2], with the
exception of xs:NOTATION. That is:
xs:string, xs:boolean,
xs:decimal, xs:double,
xs:float, xs:date,
xs:time, xs:dateTime,
xs:duration, xs:QName,
xs:anyURI, xs:gDay,
xs:gMonthDay, xs:gMonth,
xs:gYearMonth, xs:gYear,
xs:base64Binary, and
xs:hexBinary.
The derived atomic type xs:integer
defined in [XML Schema Part
2].
The types xs:anyType and
xs:anySimpleType.
The following types defined in [XPath 2.0]:
xs:yearMonthDuration,
xs:dayTimeDuration,
xs:anyAtomicType,
xs:untyped, and
xs:untypedAtomic.
A schema-aware XSLT processor additionally supports:
All other built-in types defined in [XML Schema Part 2]
User-defined types, and element and attribute
declarations, that are imported using an xsl:import-schema
declaration as described in 3.14 Importing Schema
Components. These may include both simple and
complex types.
Note:
The names that are imported from the XML Schema
namespace do not include all the names of top-level types
defined in either the Schema for Schemas or the Schema
for Datatypes. The Schema for Datatypes, as well as
defining built-in types such as xs:integer
and xs:double, also defines types that are
intended for use only within the Schema for DataTypes,
such as xs:derivationControl. A stylesheet that is
designed to process XML Schema documents as its input or
output may import the Schema for Schemas.
An implementation may define mechanisms that allow additional schema components to be added to the in-scope schema components for the stylesheet. For example, the mechanisms used to define extension functions (see 18.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.
For a Basic XSLT Processor, schema built-in types that
are not included in the static context (for example,
xs:NCName) are "unknown types" in the sense of
Section
2.5.4 SequenceType
MatchingXP. In the language
of that section, a Basic XSLT Processor must be able to determine whether these
unknown types are derived from known schema types such as
xs:string. The purpose of this rule is to
ensure that system functions such as
local-name-from-QNameFO,
which is defined to return an xs:NCName,
behave correctly. A stylesheet that uses a Basic XSLT
Processor will not be able to test whether the returned
value is an xs:NCName, but it will be able to
use it as if it were an xs:string.
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 21 Conformance.
schema-location? =
uri-reference>
The xsl:import-schema
declaration is used to identify schema components (that is,
top-level type definitions and top-level element and
attribute declarations) that need to be available
statically, that is, before any source document is
available. Names of such components used statically within
the stylesheet must refer to an in-scope schema
component, which means they must either be built-in
types as defined in 3.13
Built-in Types, or they must be imported using an
xsl:import-schema
declaration.
The xsl:import-schema
declaration identifies a namespace containing the names of
the components to be imported (or indicates that components
whose names are in no namespace are to be imported). The
effect is that the names of top-level element and attribute
declarations and type definitions from this namespace (or
non-namespace) become available for use within XPath
expressions in the stylesheet, and within other
stylesheet constructs such as the type and
as attributes of various XSLT
elements.
The same schema components are available in all stylesheet modules; importing components in one stylesheet module makes them available throughout the stylesheet.
The namespace and
schema-location attributes are both
optional.
If the xsl:import-schema
element contains an xs:schema element, then
the schema-location attribute must be absent,
and the namespace attribute must either have
the same value as the targetNamespace
attribute of the xs:schema element (if
present), or must be absent, in which case its effective
value is that of the targetNamespace attribute
of the xs:schema element if present or the
zero-length string otherwise.
[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.
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://localhost/ns/yes-no"
<xsl:import-schema>
<xs:schema targetNamespace="http://localhost/ns/yes-no"
xmlns:xs="http://www.w3.org/2001/XMLSchema">
<xs:simpleType name="local:yes-no">
<xs:restriction base="xs:string">
<xs:enumeration value="yes"/>
<xs:enumeration value="no"/>
</xs:restriction>
</xs:simpleType>
</xs:schema>
</xsl:import-schema>
<xs:variable name="condition" select="'yes'" as="local:yes-no"/>
The data model used by XSLT is the XPath 2.0 and XQuery 1.0 data model (XDM), as defined in [Data Model]. XSLT operates on source, result and stylesheet documents using the same data model.
This section elaborates on some particular features of XDM as it is used by XSLT:
The rules in 4.2 Stripping Whitespace from the Stylesheet and 4.4 Stripping Whitespace from a Source Tree make use of the concept of a whitespace text node.
[Definition: A whitespace text node is a text node whose content consists entirely of whitespace characters (that is, #x09, #x0A, #x0D, or #x20).]
Note:
Features of a source XML document that are not represented in the XDM tree will have no effect on the operation of an XSLT stylesheet. Examples of such features are entity references, CDATA sections, character references, whitespace within element tags, and the choice of single or double quotes around attribute values.
The XDM data model defined in [Data Model] is capable of representing either an XML 1.0 document (conforming to [XML 1.0] and [Namespaces in XML 1.0]) or an XML 1.1 document (conforming to [XML 1.1] and [Namespaces in XML 1.1]), and it makes no distinction between the two. In principle, therefore, XSLT 2.0 can be used with either of these XML versions.
Construction of the XDM tree is outside the scope of this specification, so XSLT 2.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 20 Serialization), though from a conformance point of view it is an optional feature. Although facilities are described for serializing the XDM tree as either XML 1.0 or XML 1.1 (and controlling the choice), there is again no formal requirement on an XSLT processor to support either or both of these XML versions as serialization targets.
Because the XDM tree is the same whether the original document was XML 1.0 or XML 1.1, the semantics of XSLT processing do not depend on the version of XML used by the original document. There is no reason in principle why all the input and output documents used in a single transformation must conform to the same version of XML.
Some of the syntactic constructs in XSLT 2.0 and XPath 2.0, for example the productions Char XML and NCName Names, 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. Implementations may support either version; it is recommended that an XSLT 2.0 processor that implements the 1.1 versions should also provide a mode that supports the 1.0 versions. It is thus implementation-defined whether the XSLT processor supports XML 1.0 with XML Namespaces 1.0, or XML 1.1 with XML Namespaces 1.1, or supports both versions at user option.
Note:
The specification referenced as [Namespaces in XML 1.0] was actually published without a version number.
At the time of writing there is no published version of
[XML Schema Part 2] that
references the XML 1.1 specifications. This means that data
types such as xs:NCName and xs:ID
are constrained by the XML 1.0 rules, and do not allow the
full range of values permitted by XML 1.1. This situation
will not be resolved until a new version of [XML Schema Part 2] becomes available;
in the meantime, it is recommended that implementers wishing to
support XML 1.1 should consult [XML Schema 1.0 and XML 1.1] for
guidance. An XSLT 2.0 processor that supports XML 1.1
should implement the rules in
later versions of [XML Schema Part
2] as they become available.
The tree representing the stylesheet is preprocessed as follows:
All comments and processing instructions are removed.
Any text nodes that are now adjacent to each other are merged.
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.
Any whitespace text node
whose parent is one of the following elements is
removed from the tree, regardless of any
xml:space attributes:
xsl:analyze-string
xsl:apply-imports
xsl:apply-templates
xsl:attribute-set
xsl:call-template
xsl:character-map
xsl:choose
xsl:next-match
xsl:stylesheet
xsl:transform
Any whitespace text node
whose following-sibling node is an xsl:param or xsl:sort element is
removed from the tree, regardless of any
xml:space attributes.
[ERR XTSE0260] Within an XSLT element
that is required to be empty, any
content other than comments or processing instructions,
including any whitespace text node
preserved using the xml:space="preserve"
attribute, is a static error.
Note:
Using xml:space="preserve" in parts of
the stylesheet that contain sequence constructors will
cause all text nodes in that part of the stylesheet,
including those that contain whitespace only, to be
copied to the result of the sequence constructor. When
the result of the sequence constructor is used to form
the content of an element, this can cause errors if such
text nodes are followed by attribute nodes generated
using xsl:attribute.
Note:
If an xml:space attribute is specified on
a literal result element,
it will be copied to the result tree in the same way as
any other attribute.
[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
AccessorDM.]
There is sometimes a requirement to write stylesheets
that produce the same results whether or not the source
documents have been validated against a schema. To achieve
this, an option is provided to remove any type
annotations on element and attribute nodes in a
source
tree, replacing them with an annotation of
xs:untyped in the case of element
nodes, and xs:untypedAtomic in
the case of attribute nodes.
Such stripping of type annotations can be requested by
specifying input-type-annotations="strip" on
the xsl:stylesheet
element. This attribute has three permitted values:
strip, preserve, and
unspecified. The default value is
unspecified. Stripping of type annotations
takes place if at least one stylesheet module in the
stylesheet
specifies input-type-annotations="strip".
[ERR XTSE0265] It is a static error if
there is a stylesheet module in the
stylesheet
that specifies input-type-annotations="strip"
and another stylesheet module that
specifies
input-type-annotations="preserve".
The source
trees to which this applies are the same as those
affected by xsl:strip-space and
xsl:preserve-space:
see 4.4 Stripping Whitespace from a
Source Tree.
When type annotations are stripped, the following changes are made to the source tree:
The type annotation of every element node is changed
to xs:untyped
The type annotation of every attribute node is
changed to xs:untypedAtomic
The typed value of every element and attribute node
is set to be the same as its string value, as an
instance of xs:untypedAtomic.
The is-nilled property of every element
node is set to false.
The values of the is-id and
is-idrefs properties are not changed.
Note:
Stripping type annotations does not necessarily return
the document to the state it would be in had validation
not taken place. In particular, any defaulted elements
and attributes that were added to the tree by the
validation process will still be present , and
elements and attributes validated as IDs will still be
accessible using the id
FO function.
A source tree supplied as input to the transformation process may contain whitespace text nodes that are of no interest, and that do not need to be retained by the transformation. Conceptually, an XSLT processor makes a copy of the source tree from which unwanted whitespace text nodes have been removed. This process is referred to as whitespace stripping.
For the purposes of this section, the term source
tree means the document containing the initial context node, and
any document returned by the functions document, doc
FO, or
collectionFO. It does
not include documents passed as the values of stylesheet parameters or
returned from extension functions.
The stripping process takes as input a set of element
names whose child whitespace text nodes are to
be preserved. The way in which this set of element names is
established using the xsl:strip-space and
xsl:preserve-space
declarations is described later in this section.
A whitespace text node is preserved if either of the following apply:
The element name of the parent of the text node is in the set of whitespace-preserving element names.
An ancestor element of the text node has an
xml:space attribute with a value of
preserve, and no closer ancestor element
has xml:space with a value of
default.
Otherwise, the whitespace text node is stripped.
The xml:space attributes are not removed
from the tree.
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 NameTests
XP; an element name matches an
xsl:strip-space
or xsl:preserve-space
element if it matches one of the NameTests
XP. An element matches a NameTest
XP if and only if the NameTest
XP would be true for the element as an
XPath node test. When more than one xsl:strip-space and
xsl:preserve-space
element matches, the best matching element is determined by
the best matching NameTest
XP. This is determined in the same way
as with 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.
[ERR XTRE0270] It is a recoverable dynamic error if
this leaves more than one match, unless all the
matched declarations are equivalent (that is, they are all
xsl:strip-space or
they are all xsl:preserve-space).
The optional recovery action
is to select, from the matches that are left, the one that
occurs last in declaration order.
If an element in a source document has a type annotation
that is a simple type or a complex type with simple
content, then any whitespace text nodes among its children
are preserved, regardless of any xsl:strip-space
declarations. The reason for this is that stripping a
whitespace text node from an element with simple content
could make the element invalid: for example, it could cause
the minLength facet to be violated.
Stripping of type annotations happens before
stripping of whitespace text nodes, so this
situation will not occur if
input-type-annotations="strip" is
specified.
Note:
In [Data Model],
processes are described for constructing an XDM
tree from an Infoset or from a PSVI. Those
processes deal with whitespace according to their own
rules, and the provisions in this section apply to the
resulting tree. In practice this means that elements that
are defined in a DTD or a Schema to contain element-only
content will have whitespace text nodes
stripped, regardless of the xsl:strip-space
and xsl:preserve-space
declarations in the stylesheet.
However, source trees are not necessarily constructed using those processes; indeed, they are not necessarily constructed by parsing XML documents. Nothing in the XSLT specification constrains how the source tree is constructed, or what happens to whitespace text nodes during its construction. The provisions in this section relate only to whitespace text nodes that are present in the tree supplied as input to the XSLT processor. The XSLT processor cannot preserve whitespace text nodes unless they were actually present in the supplied tree.
The mapping from the Infoset to the XDM
data model, described in [Data
Model], does not retain attribute types. This means,
for example, that an attribute described in the DTD as
having attribute type NMTOKENS will be
annotated in the XDM tree as
xs:untypedAtomic rather than
xs:NMTOKENS, and its typed value will consist
of a single xs:untypedAtomic
value rather than a sequence of xs:NMTOKEN
values.
Attributes with a DTD-derived type of ID, IDREF, or
IDREFS will be marked in the XDM tree as
having the is-id or is-idrefs
properties. It is these properties, rather than any
type
annotation, that are examined by the functions id
FO and idref
FO described in [Functions and Operators].
The XDM data model (see [Data Model]) leaves it to the host language to define limits. This section describes the limits that apply to XSLT.
Limits on some primitive data types are defined in [XML Schema Part 2]. Other limits, listed below, are implementation-defined. Note that this does not necessarily mean that each limit must be a simple constant: it may vary depending on environmental factors such as available resources.
The following limits are implementation-defined:
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.)
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.
For the xs:duration type: the maximum
absolute values of the years, months, days, hours,
minutes, and seconds components.
For the
xs:yearMonthDuration type:
the maximum absolute value, expressed as an integer
number of months.
For the xs:dayTimeDuration
type: the maximum absolute value, expressed as a
decimal number of seconds.
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.
For sequences, the maximum number of items in a sequence.
For backwards compatibility reasons, XSLT 2.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 20.1 Character
Maps) is 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
20.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
&) in respect of this character or
attribute node.
Note:
In practice, the nodes in a final
result tree will often be streamed directly from the
XSLT processor to the serializer. In such an
implementation, disable-output-escaping can
be viewed not so much a property stored with nodes in the
tree, but rather as additional information passed across
the interface between the XSLT processor and the
serializer.
The name of a stylesheet-defined object, specifically a named template, a mode, an attribute set, a key, a decimal-format, a variable or parameter, a stylesheet function, a named output definition, or a character map is specified as a QName using the syntax for QName Names as defined in [Namespaces in XML 1.0].
[Definition: A QName is always
written in the form (NCName ":")? NCName, that
is, a local name optionally preceded by a namespace prefix.
When two QNames are compared, however, they are considered
equal if the corresponding expanded-QNames are the same, as
described below.]
Because an atomic value of type xs:QName is
sometimes referred to loosely as a QName, this
specification also uses the term lexical QName to emphasize
that it is referring to a QName
Names in its lexical form rather than
its expanded form. This term is used especially when
strings containing lexical QNames are manipulated as
run-time values.
[Definition: A lexical QName is a string
representing a QName
in the form (NCName ":")? NCName, that is, a
local name optionally preceded by a namespace
prefix.]
[Definition: A string in the form of a lexical QName may occur as the value of an attribute node in a stylesheet module, or within an XPath expression contained in such an attribute node, or as the result of evaluating an XPath expression contained in such an attribute node. The element containing this attribute node is referred to as the defining element of the QName.]
[Definition: An expanded-QName contains a pair of values, namely a local name and an optional namespace URI. It may also contain a namespace prefix. Two expanded-QNames are equal if the namespace URIs are the same (or both absent) and the local names are the same. The prefix plays no part in the comparison, but is used only if the expanded-QName needs to be converted back to a string.]
If the QName has a prefix, then the prefix is expanded into a URI reference using the namespace declarations in effect on its defining element. The expanded-QName consisting of the local part of the name and the possibly null URI reference is used as the name of the object. The default namespace of the defining element (see Section 6.2 Element NodesDM) is not used for unprefixed names.
There are three cases where the default namespace of the defining element is used when expanding an unprefixed QName:
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).
The default namespace is used when expanding the
first argument of the function element-available.
The default namespace applies to any unqualified
element names appearing in the
cdata-section-elements attribute of
xsl:output
or xsl:result-document
In the case of an unprefixed QName used as a
NameTest within an XPath expression (see 5.3 Expressions) , and in
certain other contexts, the namespace to be used in
expanding the QName may be specified by means of the
[xsl:]xpath-default-namespace attribute, as
specified in 5.2 Unprefixed
QNames in Expressions and Patterns.
[ERR XTSE0280] In the case of a prefixed QName used as the value of an attribute in the stylesheet, or appearing within an XPath expression in the stylesheet, it is a static error if the defining element has no namespace node whose name matches the prefix of the QName.
[ERR XTDE0290] Where the result of evaluating an XPath expression (or an attribute value template) is required to be a lexical QName, then unless otherwise specified it is a non-recoverable dynamic error if the defining element has no namespace node whose name matches the prefix of the lexical QName. This error may be signaled as a static error if the value of the expression can be determined statically.
The attribute [xsl:]xpath-default-namespace
(see 3.5 Standard
Attributes) may be used on an element in the
stylesheet
to define the namespace that will be used for an unprefixed
element name or type name within an XPath
expression, and in certain other contexts listed below.
The value of the attribute is the namespace URI to be used.
For any element in the stylesheet, this attribute has an
effective value, which is the value of the
[xsl:]xpath-default-namespace on that element
or on the innermost containing element that specifies such
an attribute, or the zero-length string if no containing
element specifies such an attribute.
For any element in the stylesheet, the effective value of this attribute determines the value of the default namespace for element and type names in the static context of any XPath expression contained in an attribute of that element (including XPath expressions in attribute value templates). The effect of this is specified in [XPath 2.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:
any unprefixed element name or type name used in a pattern
any unprefixed element name used in the
elements attribute of the xsl:strip-space
or xsl:preserve-space
instructions
any unprefixed element name or type name used in the
as attribute of an XSLT element
any unprefixed type name used in the
type attribute of an XSLT
element
any unprefixed type name used in the
xsl:type attribute of a literal result
element.
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 NodesDM) 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.
XSLT uses the expression language defined by XPath 2.0 [XPath 2.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 Expr XP defined in [XPath 2.0].]
An XPath expression may occur as the value of certain attributes on XSLT-defined elements, and also within curly brackets in attribute value templates.
Except where forwards-compatible behavior is enabled (see 3.9 Forwards-Compatible Processing), it is a static error if the value of such an attribute, or the text between curly brackets in an attribute value template, does not match the XPath production Expr XP, or if it fails to satisfy other static constraints defined in the XPath specification, for example that all variable references must refer to variables that are in scope. Error codes are defined in [XPath 2.0].
The transformation fails with a non-recoverable dynamic error if any XPath expression is evaluated and raises a dynamic error. Error codes are defined in [XPath 2.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 2.0].
[Definition: The context within a stylesheet where an
XPath expression appears may
specify the required type of the expression.
The required type indicates the type of the value that the
expression is expected to return.] If no required type is specified, the
expression may return any value: in effect, the required
type is then item()*.
[Definition: Except where otherwise
indicated, the actual value of an expression is converted to the
required
type using the function conversion rules. These
are the rules defined in [XPath 2.0]
for converting the supplied argument of a function call to
the required type of that argument, as defined in the
function signature. The relevant rules are those that apply
when XPath 1.0 compatibility mode
is set to false.]
This specification also invokes the XPath 2.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.
XPath defines the concept of an expression contextXP which contains all the information that can affect the result of evaluating an expression. The expression context has two parts, the static contextXP, and the dynamic contextXP. The components that make up the expression context are defined in the XPath specification (see Section 2.1 Expression ContextXP). This section describes the way in which these components are initialized when an XPath expression is contained within an XSLT stylesheet.
As well as providing values for the static and dynamic
context components defined in the XPath specification, XSLT
defines additional context components of its own. These
context components are used by XSLT instructions (for
example, xsl:next-match and
xsl:apply-imports),
and also by the functions in the extended function library
described in this specification.
The following four sections describe:
5.4.1 Initializing the Static Context
5.4.2 Additional Static Context Components used by XSLT
5.4.3 Initializing the Dynamic Context
5.4.4 Additional Dynamic Context Components used by XSLT
The static contextXP of an XPath expression appearing in an XSLT stylesheet is initialized as follows. In these rules, the term containing element means the element within the stylesheet that is the parent of the attribute whose value contains the XPath expression in question, and the term enclosing element means the containing element or any of its ancestors.
XPath 1.0 compatibility mode is set to true if and only if the containing element occurs in part of the stylesheet where backwards compatible behavior is enabled (see 3.8 Backwards-Compatible Processing).
The statically known namespacesXP are the namespace declarations that are in scope for the containing element.
The default
element/type
namespaceXP is the
namespace defined by the
[xsl:]xpath-default-namespace attribute
on the innermost enclosing element that has such an
attribute, as described in 5.2 Unprefixed QNames in
Expressions and Patterns. The value of this
attribute is a namespace URI. If there is no
[xsl:]xpath-default-namespace attribute
on an enclosing element, the default namespace for
element names and type names is the null
namespace.
The default
function namespaceXP is
the standard function
namespace, defined in [Functions and Operators].
This means that it is not necessary to declare this
namespace in the stylesheet, nor is it necessary
to use the prefix fn (or any other
prefix) in calls to the core functions.
The in-scope schema definitionsXP for the XPath expression are the same as the in-scope schema components for the stylesheet, and are as specified in 3.13 Built-in Types.
The in-scope variablesXP are defined by the variable binding elements that are in scope for the containing element (see 9 Variables and Parameters).
The function signaturesXP are the core functions defined in [Functions and Operators], the constructor functions for all the atomic types in the in-scope schema definitionsXP, the additional functions defined in this specification, the stylesheet functions defined in the stylesheet, plus any extension functions bound using implementation-defined mechanisms (see 18 Extensibility and Fallback).
Note:
It follows from the above that a conformant XSLT processor must implement the entire library of core functions defined in [Functions and Operators].
The statically known collationsXP are implementation-defined. However, the set of in-scope collations must always include the Unicode codepoint collation, defined in Section 7.3 Equality and Comparison of StringsFO.
The default
collationXP is defined
by the value of the
[xsl:]default-collation attribute on the
innermost enclosing element that has such an
attribute. For details, see 3.6.1 The
default-collation attribute.
[Definition: In this specification
the term default collation means the collation
that is used by XPath operators such as
eq and lt appearing in
XPath expressions within the stylesheet.]
This collation is also used by default when
comparing strings in the evaluation of the xsl:key and xsl:for-each-group
elements. This may also
(but need not necessarily) be the same as the default
collation used for xsl:sort elements
within the stylesheet. Collations used by xsl:sort are
described in 13.1.3
Sorting Using Collations.
The base URIXP is the base URI of the containing element. The concept of the base URI of a node is defined in Section 5.2 base-uri AccessorDM
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 set of named decimal formats, used by the
format-number
function
The values of system properties, used by the
system-property
function
The set of available instructions, used by the
element-available
function
For convenience, the dynamic context is described in two parts: the focus, which represents the place in the source document that is currently being processed, and a collection of additional context variables.
A number of functions specified in [Functions and Operators] are
defined to be stable
FO, meaning that if they are called
twice during the same execution
scopeFO, with the same
arguments, then they return the same results (see
Section 1.7 TerminologyFO).
In XSLT, the execution of a stylesheet defines the
execution scope. This means, for example, that if the
function
current-dateTimeFO
is called repeatedly during a transformation, it produces
the same result each time. By implication, the components
of the dynamic context on which these functions depend
are also stable for the duration of the transformation.
Specifically, the following components defined in
Section
2.1.2 Dynamic ContextXP
must be stable: function implementations,
current dateTime, implicit timezone,
available documents, available
collections, and default collection. The
values of global variables and stylesheet parameters are
also stable for the duration of a transformation. The
focus is not stable; the additional dynamic
context components defined in 5.4.4 Additional Dynamic
Context Components used by XSLT are also
not stable.
As specified in [Functions
and Operators], implementations may provide user
options that relax the requirement for the doc
FO and
collectionFO
functions (and therefore, by implication, the document function)
to return stable results. By default, however, the
functions must be stable. The manner in which such user
options are provided, if at all, is implementation-defined.
XPath expressions contained in
[xsl:]use-when attributes are not considered
to be evaluated "during the transformation" as defined
above. For details see 3.12 Conditional Element
Inclusion.
[Definition: When a sequence constructor is evaluated, the processor keeps track of which items are being processed by means of a set of implicit variables referred to collectively as the focus.] More specifically, the focus consists of the following three values:
[Definition: The context item is the
item currently being processed. An item (see
[Data Model]) is
either an atomic value (such as an integer, date,
or string), or a node. The context item is
initially set to the initial context node
supplied when the transformation is invoked (see
2.3 Initiating a
Transformation). It changes whenever
instructions such as xsl:apply-templates
and xsl:for-each
are used to process a sequence of items; each item
in such a sequence becomes the context item while
that item is being processed.] The context item is returned
by the XPath expression .
(dot).
[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, there is no context
node.] The context node
is returned by the XPath expression
self::node(), and it is used as the
starting node for all relative path expressions.
Where the containing element of an XPath expression is an instruction or a literal result element, the initial context item, context position, and context size for the XPath expression are the same as the context item, context position, and context size for the evaluation of the containing instruction or literal result element.
In other cases (for example, where the containing
element is xsl:sort, xsl:with-param,
or xsl:key),
the rules are given in the specification of the
containing element.
The current function
can be used within any XPath expression to select the item
that was supplied as the context item to the XPath
expression by the XSLT processor. Unlike .
(dot) this is unaffected by changes to the context item
that occur within the XPath expression. The current function
is described in 16.6.1
current.
On completion of an instruction that changes the
focus (such as
xsl:apply-templates
or xsl:for-each), the
focus reverts to its previous value.
When a stylesheet function is called, the focus within the body of the function is initially undefined. The focus is also undefined on initial entry to the stylesheet if no initial context node is supplied.
When the focus is undefined, evaluation of any expression that references the context item, context position, or context size results in a non-recoverable dynamic error [XPDY0002]
The description above gives an outline of the way the focus works. Detailed rules for the effect of each instruction are given separately with the description of that instruction. In the absence of specific rules, an instruction uses the same focus as its parent instruction.
[Definition: A singleton focus based on a node N has the context item (and therefore the context node) set to N, and the context position and context size both set to 1 (one).]
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 contextXP of an XPath expression are initialized.
The dynamic variablesXP 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 timezoneXP is implementation-defined.
The available documentsXP, and the available collectionsXP are determined as part of the process for initiating a transformation (see 2.3 Initiating a Transformation).
The available
documentsXP are
defined as part of the XPath 2.0 dynamic context to
support the
docFO
function, but this component is also referenced by
the similar XSLT document
function: see 16.1 Multiple
Source Documents. This variable defines a
mapping between URIs passed to the
docFO or
document
function and the document nodes that are
returned.
Note:
Defining this as part of the evaluation context is a formal way of specifying that the way in which URIs get turned into document nodes is outside the control of the language specification, and depends entirely on the run-time environment in which the transformation takes place.
The XSLT-defined document
function allows the use of URI references
containing fragment identifiers. The interpretation
of a fragment identifier depends on the media type
of the resource representation. Therefore, the
information supplied in available
documentsXP 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 collectionXP is implementation-defined. This allows options such as setting the default collection to be an empty sequence, or to be undefined.
In addition to the values that make up the focus, an XSLT processor maintains a number of other dynamic context components that reflect aspects of the evaluation context. These components are fully described in the sections of the specification that maintain and use them. They are:
The current template
rule, which is the template rule most recently
invoked by an xsl:apply-templates,
xsl:apply-imports,
or xsl:next-match
instruction: see 6.7
Overriding Template Rules;
The current mode, which is the
mode set by the
most recent call of xsl:apply-templates
(for a full definition see 6.5
Modes);
The current group and current grouping key,
which provide information about the collection of
items currently being processed by an xsl:for-each-group
instruction: see 14.1 The
Current Group and 14.2 The Current Grouping
Key;
The current captured
substrings: this is a sequence of strings, which
is maintained when a string is matched against a
regular expression using the xsl:analyze-string
instruction, and which is accessible using the
regex-group
function: see 15.2 Captured
Substrings.
The output state: this is a flag
whose two possible values are final output state and
temporary output
state. This flag indicates whether instructions
are currently writing to a final result tree or to
an internal data structure. The initial setting is
final output state, and
it is switched to temporary output
state by instructions such as xsl:variable.
For more details, see 19.1 Creating Final
Result Trees.
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.
A template rule identifies the nodes 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 16.3 Keys).
[Definition: A pattern specifies a set of conditions on a node. A node that satisfies the conditions matches the pattern; a node that does not satisfy the conditions does not match the pattern. The syntax for patterns is a subset of the syntax for expressions.] As explained in detail below, a node matches a pattern if the node can be selected by deriving an equivalent expression, and evaluating this expression with respect to some possible context.
Here are some examples of patterns:
para matches any para
element.
* matches any element.
chapter|appendix matches any
chapter element and any
appendix element.
olist/entry matches any
entry element with an
olist parent.
appendix//para matches any
para element with an
appendix ancestor element.
schema-element(us:address) matches
any element that is annotated as an instance of the
type defined by the schema element declaration
us:address, and whose name is either
us:address or the name of another
element in its substitution group.
attribute(*, xs:date) matches any
attribute annotated as being of type
xs:date.
/ matches a document node.
document-node() matches a document
node.
document-node(schema-element(my:invoice))
matches the document node of a document whose
document element is named
my:invoice and matches the type
defined by the global element declaration
my:invoice.
text() matches any text node.
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.
[ERR XTSE0340] Where an attribute is
defined to contain a pattern, it is a static error
if the pattern does not match the production Pattern. Every pattern is a legal XPath
expression, but the converse is not
true: 2+2 is an example of a legal XPath
expression that is not a pattern. The XPath expressions
that can be used as patterns are those that match the
grammar for Pattern, given
below.
Informally, a Pattern is a
set of path expressions separated by |,
where each step in the path expression is constrained to
be an AxisStep
XP that uses only the
child or attribute axes.
Patterns may also use the // operator. A
Predicate
XP within the PredicateList
XP in a pattern can contain
arbitrary XPath expressions (enclosed between square
brackets) in the same way as a predicate
XP in a path expression.
Patterns may start with an id
FO or key function call,
provided that the value to be matched is supplied as
either a literal or a reference to a variable or parameter, and the key name (in
the case of the key function) is
supplied as a string literal. These patterns will
never match a node in a tree whose root is not a document
node.
If a pattern occurs in part of the stylesheet where backwards compatible behavior is enabled (see 3.8 Backwards-Compatible Processing), then the semantics of the pattern are defined on the basis that the equivalent XPath expression is evaluated with XPath 1.0 compatibility mode set to true.
| [1] | Pattern |
::= | PathPattern |
| Pattern '|'
PathPattern |
|||
| [2] | PathPattern |
::= | RelativePathPattern |
| '/' RelativePathPattern? |
|||
| '//' RelativePathPattern |
|||
| IdKeyPattern (('/' | '//')
RelativePathPattern)? |
|||
| [3] | RelativePathPattern |
::= | PatternStep
(('/' | '//') RelativePathPattern)? |
| [4] | PatternStep |
::= | PatternAxis? NodeTest
XP
PredicateListXP |
| [5] | PatternAxis |
::= | ('child' '::' | 'attribute' '::' |
'@') |
| [6] | IdKeyPattern |
::= | 'id' '(' IdValue ')' |
| 'key' '('
StringLiteralXP ','
KeyValue ')' |
|||
| [7] | IdValue |
::= |
StringLiteralXP |
VarRef
XP |
| [8] | KeyValue |
::= | Literal
XP | VarRef
XP |
The constructs NodeTest XP, PredicateList XP, VarRef XP, Literal XP, and StringLiteral XP are part of the XPath expression language, and are defined in [XPath 2.0].
The meaning of a pattern is defined formally as follows.
First we define the concept of an equivalent
expression. In general, the equivalent expression is
the XPath expression that takes the same lexical form as
the pattern as written. However, if the pattern contains
a PathPattern that is a
RelativePathPattern, then the first
PatternStep PS of this
RelativePathPattern is adjusted to allow it
to match a parentless element or attribute node, as
follows:
If the NodeTest in PS is
document-node() (optionally with
arguments), and if no explicit axis is specified,
then the axis in step PS is taken as
self rather than child.
If PS uses the child axis (explicitly
or implicitly), and if the NodeTest in
PS is not document-node()
(optionally with arguments), then the axis in step
PS is replaced by
child-or-top, which is defined as
follows. If the context node is a parentless element,
comment, processing-instruction, or text node then
the child-or-top axis selects the
context node; otherwise it selects the children of
the context node. It is a forwards axis whose
principal node kind is element.
If PS uses the attribute axis, 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.
The axes child-or-top and
attribute-or-top are introduced only for
definitional purposes. They cannot be used explicitly in
a user-written pattern or expression.
Note:
The purpose of these adjustments is to ensure that a
pattern such as person matches any element
named person, even if it has no parent;
and similarly, that the pattern @width
matches any attribute named width, even a
parentless attribute. The rule also ensures that a
pattern using a NodeTest of the form
document-node(...) matches a document
node. The pattern node() will match any
element, text node, comment, or processing instruction,
whether or not it has a parent. For backwards
compatibility reasons, the pattern node(),
when used without an explicit axis, does not match
document nodes, attribute nodes, or namespace nodes.
The rules are also phrased to ensure that positional
patterns of the form para[1] continue to
count nodes relative to their parent, if they have
one.
Let the equivalent expression, calculated according to these rules, be EE.
To determine whether a node N matches the
pattern, evaluate the expression
root(.)//(EE) with a singleton
focus based on N. If the result is a
sequence of nodes that includes N, then node
N matches the pattern; otherwise node
N does not match the pattern.
The 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 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.
Although the semantics of patterns are specified
formally in terms of expression evaluation, it is
possible to understand pattern matching using a different
model. In a pattern, | indicates
alternatives; a pattern with one or more |
separated alternatives matches if any one of the
alternatives matches. A 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.
Any dynamic error or type error that occurs during the evaluation of a pattern against a particular node is treated as a recoverable error even if the error would not be recoverable under other circumstances. The optional recovery action is to treat the pattern as not matching that node.
Note:
The reason for this provision is that it is difficult for the stylesheet author to predict which predicates in a pattern will actually be evaluated. In the case of match patterns in template rules, it is not even possible to predict which patterns will be evaluated against a particular node. Making errors in patterns recoverable enables an implementation, if it chooses to do so, to report such errors while stylesheets are under development, while masking them if they occur during production running.
One particular optimization is required by this specification: for a
PathPattern that starts
with / or // or with an
IdKeyPattern, the result
of testing this pattern against a node in a tree whose
root is not a document node must be a non-match, rather
than a dynamic error. This rule applies to each PathPattern within a Pattern.
Note:
Without the above rule, any attempt to apply
templates to a parentless element node would create the
risk of a dynamic error if the stylesheet has a
template rule specifying match="/".
[Definition: In an attribute that is
designated as an attribute value template, such as
an attribute of a literal result element, an
expression
can be used by surrounding the expression with curly
brackets ({})].
An attribute value template consists of an alternating
sequence of fixed parts and variable parts. A variable part
consists of an XPath expression enclosed in curly brackets
({}). A fixed part may contain any characters,
except that a left curly bracket must be written as {{ and a
right curly bracket must be
written as }}.
Note:
An expression within a variable part may contain an unescaped curly bracket within a StringLiteral XP or within a comment.
[ERR XTSE0350] It is a static error if an unescaped left curly bracket appears in a fixed part of an attribute value template without a matching right curly bracket.
It is a static error if the string contained between matching curly brackets in an attribute value template does not match the XPath production Expr XP, or if it contains other XPath static errors. The error is signaled using the appropriate XPath error code.
[ERR XTSE0370] It is a static error if an unescaped right curly bracket occurs in a fixed part of an attribute value template.
[Definition: The result of evaluating an attribute value template is referred to as the effective value of the attribute.] The effective value is the string obtained by concatenating the expansions of the fixed and variable parts:
The expansion of a fixed part is obtained by
replacing any double curly brackets ({{ or
}}) by the corresponding single curly
bracket.
The expansion of a variable part is obtained by evaluating the enclosed XPath expression and converting the resulting value to a string. This conversion is done using the rules given in 5.7.2 Constructing Simple Content.
Note:
This process can generate dynamic errors, for example if the sequence contains an element with a complex content type (which cannot be atomized).
If backwards compatible behavior is enabled for the attribute, the rules for converting the value of the expression to a string are modified as follows. After atomizing the result of the expression, all items other than the first item in the resulting sequence are discarded, and the effective value is obtained by converting the first item in the sequence to a string. If the atomized sequence is empty, the result is a zero-length string.
Curly brackets are not treated specially in an attribute value in an XSLT stylesheet unless the attribute is specifically designated as one that permits an attribute value template; in an element syntax summary, the value of such attributes is surrounded by curly brackets.
Note:
Not all attributes are designated as attribute value
templates. Attributes whose value is an expression or
pattern,
attributes of declaration elements and attributes
that refer to named XSLT objects are
generally not designated as attribute value
templates (an exception is the format
attribute of xsl:result-document).
Namespace declarations are not XDM attribute
nodes and are therefore never treated as attribute
value templates.
The following example creates an img
result element from a photograph element in
the source; the value of the src and
width attributes are computed using XPath
expressions enclosed in attribute value templates:
<xsl:variable name="image-dir" select="'/images'"/>
<xsl:template match="photograph">
<img src="{$image-dir}/{href}" width="{size/@width}"/>
</xsl:template>
With this source
<photograph> <href>headquarters.jpg</href> <size width="300"/> </photograph>
the result would be
<img src="/images/headquarters.jpg" width="300"/>
The following example shows how the values in a sequence are output as a space-separated list. The following literal result element:
<temperature readings="{10.32, 5.50, 8.31}"/>
produces the output node:
<temperature readings="10.32 5.5 8.31"/>
Curly brackets are not recognized recursively inside expressions.
[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 and atomic values. 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:
Text nodes appearing in the stylesheet (if they have not been removed in the process of whitespace stripping: see 4.2 Stripping Whitespace from the Stylesheet) are copied to create a new parentless text node in the result sequence.
Literal result elements are evaluated to create a new parentless element node, having the same expanded-QName as the literal result element, which is added to the result sequence: see 11.1 Literal Result Elements
XSLT instructions produce a sequence
of zero, one, or more items as their result. These
items are added to the result sequence. For most XSLT
instructions, these items are nodes, but some
instructions (xsl:sequence and
xsl:copy-of) can
also produce atomic values. 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, or existing
nodes.
Extension instructions (see 18.2 Extension Instructions) also produce a sequence of items as their result. The items in this sequence are added to the result sequence.
There are several ways the result of a sequence constructor may be used.
The sequence may be bound to a variable or returned
from a stylesheet function, in which case it becomes
available as a value to be manipulated in arbitrary
ways by XPath expressions. The sequence is bound to a
variable when the sequence constructor appears within
one of the elements xsl:variable,
xsl:param, or
xsl:with-param,
when this instruction has an as attribute.
The sequence is returned from a stylesheet function
when the sequence constructor appears within the
xsl:function
element.
Note:
This will typically expose to the stylesheet
elements, attributes, and other nodes that have not
yet been attached to a parent node in a result tree.
The semantics of XPath expressions when applied to
parentless nodes are well-defined; however, such
expressions should be used with care. For example,
the expression / causes a type
error if the root of the tree containing the context
node is not a document node..
Parentless attribute nodes require particular care because they have no namespace nodes associated with them. A parentless attribute node is not permitted to contain namespace-sensitive content (for example, a QName or an XPath expression) because there is no information enabling the prefix to be resolved to a namespace URI. Parentless attributes can be useful in an application (for example, they provide an alternative to the use of attribute sets: see 10.2 Named Attribute Sets) but they need to be handled with care.
The sequence may be returned as the result of the
containing element. This happens when the instruction
containing the sequence constructor is xsl:analyze-string,
xsl:apply-imports,
xsl:apply-templates,
xsl:call-template,
xsl:choose,
xsl:fallback,
xsl:for-each,
xsl:for-each-group,
xsl:if, xsl:matching-substring,
xsl:next-match,
xsl:non-matching-substring,
xsl:otherwise,
xsl:perform-sort,
xsl:sequence, or
xsl:when
The sequence may be used to construct the content of
a new element or document node. This happens when the
sequence constructor appears as the content of a
literal result
element, or of one of the instructions xsl:copy, xsl:element,
xsl:document,
xsl:result-document,
or xsl:message. It
also happens when the sequence constructor is contained
in one of the elements xsl:variable,
xsl:param, or
xsl:with-param,
when this instruction has no as attribute.
For details, see 5.7.1 Constructing
Complex Content.
The sequence may be used to construct the string value
of an attribute node, text node, namespace
node, comment node, or processing instruction node.
This happens when the sequence constructor is contained
in one of the elements xsl:attribute,
xsl:value-of,
xsl:namespace,
xsl:comment, or
xsl:processing-instruction.
For details, see 5.7.2 Constructing
Simple Content.
Note:
The term sequence constructor replaces template as used in XSLT 1.0. The change is made partly for clarity (to avoid confusion with template rules and named templates), but also to reflect a more formal definition of the semantics. Whereas XSLT 1.0 described a template as a sequence of instructions that write to the result tree, XSLT 2.0 describes a sequence constructor as something that can be evaluated to return a sequence of items; what happens to these items depends on the containing instruction.
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):
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.
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.
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.
Any document node within the result sequence is replaced by a sequence containing each of its children, in document order.
Zero-length text nodes within the result sequence are removed.
Adjacent text nodes within the result sequence are merged into a single text node.
Invalid namespace and attribute nodes are detected as follows.
[ERR XTDE0410] It is a non-recoverable dynamic error if the result sequence used to construct the content of an element node contains a namespace node or attribute node that is preceded in the sequence by a node that is neither a namespace node nor an attribute node.
[ERR XTDE0420] It is a non-recoverable dynamic error if the result sequence used to construct the content of a document node contains a namespace node or attribute node.
[ERR XTDE0430] It is a non-recoverable dynamic error if the result sequence contains two or more namespace nodes having the same name but different string values (that is, namespace nodes that map the same prefix to different namespace URIs).
[ERR XTDE0440] It is a non-recoverable dynamic error if the result sequence contains a namespace node with no name and the element node being constructed has a null namespace URI (that is, it is an error to define a default namespace when the element is in no namespace).
If the result sequence contains two or more namespace nodes with the same name (or no name) and the same string value (that is, two namespace nodes mapping the same prefix to the same namespace URI), then all but one of the duplicate nodes are discarded.
Note:
Since the order of namespace nodes is undefined, it is not significant which of the duplicates is retained.
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.
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.
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.
If the newly constructed node is an element node, and if namespaces are inherited, then each namespace node of the newly constructed element (including any produced as a result of the namespace fixup process) is copied to each descendant element of the newly constructed element, unless that element or an intermediate element already has a namespace node with the same name (or absence of a name) or that descendant element or an intermediate element is in no namespace and the namespace node has no name.
Consider the following stylesheet fragment:
<td> <xsl:attribute name="valign">top</xsl:attribute> <xsl:value-of select="@description"/> </td>
This fragment consists of a literal result element
td, containing a sequence constructor that
consists of two instructions: xsl:attribute and
xsl:value-of. The
sequence constructor is evaluated to produce a sequence
of two nodes: a parentless attribute node, and a
parentless text node. The td instruction
causes a td element to be created; the new
attribute therefore becomes an attribute of the new
td element, while the text node created by
the xsl:value-of
instruction becomes a child of the td
element (unless it is zero-length, in which case it is
discarded).
Consider the following stylesheet fragment:
<doc>
<e><xsl:sequence select="1 to 5"/></e>
<f>
<xsl:for-each select="1 to 5">
<xsl:value-of select="."/>
</xsl:for-each>
</f>
</doc>
This produces the output (when indented):
<doc> <e>1 2 3 4 5</e> <f>12345</f> </doc>
The difference between the two cases is that for the
e element, the sequence constructor
generates a sequence of five atomic 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.
The xsl:attribute,
xsl:comment,
xsl:processing-instruction,
xsl:namespace,
and xsl:value-of
elements create nodes that cannot have children.
Specifically, the xsl:attribute
instruction creates an attribute node, xsl:comment creates a
comment node, xsl:processing-instruction
creates a processing instruction node, xsl:namespace
creates a namespace node, and xsl:value-of creates
a text node. The string value of the new node is
constructed using either the select
attribute of the instruction, or the sequence constructor that
forms the content of the instruction. The
select attribute allows the content to be
specified by means of an XPath expression, while the
sequence constructor allows it to be specified by means
of a sequence of XSLT instructions. The
select attribute or sequence constructor is
evaluated to produce a result sequence, and the
string
value of the new node is derived from this result
sequence according to the rules below.
These rules are also used to compute the effective value of an attribute value template. In this case the sequence being processed is the result of evaluating an XPath expression enclosed between curly brackets, and the separator is a single space character.
Zero-length text nodes in the sequence are discarded.
Adjacent text nodes in the sequence are merged into a single text node.
The sequence is atomized.
Every value in the atomized sequence is cast to a string.
The strings within the resulting sequence are
concatenated, with a (possibly zero-length) separator
inserted between successive strings. The
default separator is a single space. In the
case of xsl:attribute
and xsl:value-of, a
different separator can be specified using the
separator attribute of the instruction;
it is permissible for this to be a zero-length
string, in which case the strings are concatenated
with no separator. In the case of xsl:comment,
xsl:processing-instruction,
and xsl:namespace
, and when expanding an attribute value
template, the default separator cannot be
changed.
In the case of xsl:processing-instruction,
any leading spaces in the resulting string are
removed.
The resulting string forms the string value of the new attribute, namespace, comment, processing-instruction, or text node.
Consider the following stylesheet fragment:
<doc>
<xsl:attribute name="e" select="1 to 5"/>
<xsl:attribute name="f">
<xsl:for-each select="1 to 5">
<xsl:value-of select="."/>
</xsl:for-each>
</xsl:attribute>
</doc>
This produces the output:
<doc e="1 2 3 4 5" f="12345"/>
The difference between the two cases is that for the
e attribute, the sequence constructor
generates a sequence of five atomic values, which are
therefore separated by spaces. For the f
attribute, the content is supplied as a sequence of
five text nodes, which are concatenated without space
separation.
Specifying separator="" on the first
xsl:attribute
instruction would cause the attribute value to be
e="12345". A separator
attribute on the second xsl:attribute
instruction would have no effect, since the separator
only affects the way adjacent atomic values are
handled: separators are never inserted between adjacent
text nodes.
Note:
If an attribute value template contains a sequence
of fixed and variable parts, no additional whitespace
is inserted between the expansions of the fixed and
variable parts. For example, the effective
value of the attribute a="chapters{4 to
6}" is a="chapters4 5 6".
In a tree supplied to or constructed by an XSLT processor, the constraints relating to namespace nodes that are specified in [Data Model] must be satisfied. For example
If an element node has an expanded-QName with a non-null namespace URI, then that element node must have at least one namespace node whose string value is the same as that namespace URI.
If an element node has an attribute node whose expanded-QName has a non-null namespace URI, then the element must have at least one namespace node whose string value is the same as that namespace URI and whose name is non-empty.
Every element must have
a namespace node whose expanded-QName has
local-part xml and whose string
value is
http://www.w3.org/XML/1998/namespace.
The namespace prefix xml must not be
associated with any other namespace URI, and the
namespace URI
http://www.w3.org/XML/1998/namespace
must not be associated with any other prefix.
A namespace node must
not have the name xmlns.
[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.
[ERR XTDE0485] It is a non-recoverable dynamic
error if namespace fixup is performed on an element
that contains among the typed values of the element and
its attributes two values of type xs:QName
or xs:NOTATION containing conflicting
namespace prefixes, that is, two values that use the same
prefix to refer to different namespace URIs.
Namespace fixup is applied to every element that is
constructed using a literal result
element, or one of the instructions xsl:element, xsl:copy, or xsl:copy-of. An
implementation is not required
to perform namespace fixup for elements in any source
document, that is, for a document in the initial input
sequence, documents loaded using the document, doc
FO or
collectionFO
function, documents supplied as the value of a stylesheet parameter, or
documents returned by an extension function or
extension
instruction.
Note:
A source document (an input document, a document
returned by the document,
docFO or
collectionFO
functions, a document returned by an extension function
or extension instruction, or a document supplied as a
stylesheet parameter) is required to satisfy the
constraints described in [Data Model], including the
constraints imposed by the namespace fixup process. The
effect of supplying a pseudo-document that does not
meet these constraints is undefined.
In an Infoset (see [XML
Information Set]) created from a document conforming
to [Namespaces in XML 1.0],
it will always be true that if a parent element has an
in-scope namespace with a non-empty namespace prefix,
then its child elements will also have an in-scope
namespace with the same namespace prefix, though possibly
with a different namespace URI. This constraint is
removed in [Namespaces in XML
1.1]. XSLT 2.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, xmlms:foo="") to prevent
this inheritance taking place.
[Definition: Within this specification, the term
URI Reference, unless otherwise stated, refers to a
string in the lexical space of the xs:anyURI
data type as defined in [XML Schema
Part 2].] Note that
this is a wider definition than that in [RFC3986]: in particular, it is
designed to accommodate Internationalized Resource
Identifiers (IRIs) as described in [RFC3987], and thus allows the use of
non-ASCII characters without escaping.
URI References are used in XSLT with three main roles:
As namespace URIs
As collation URIs
As identifiers for resources such as stylesheet modules; these resources are typically accessible using a protocol such as HTTP. Examples of such identifiers are the URIs used in thehrefattributes ofxsl:import,xsl:include, andxsl:result-document.
The rules for namespace URIs are given in [Namespaces in XML 1.0] and [Namespaces in XML 1.1]. Those specifications deprecate the use of relative URIs as namespace URIs.
The rules for collation URIs are given in [Functions and Operators].
URI references used to identify external resources must
conform to the same rules as the locator attribute
(href) defined in section 5.4 of [XLink]. If the URI reference is relative,
then it is resolved (unless otherwise specified) against
the base URI of the containing element node, according to
the rules of [RFC3986],
after first escaping all characters that need to be escaped
to make it a valid RFC3986 URI reference. (But a relative
URI 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.
Template rules define the processing that can be applied to nodes that match a particular pattern.
name? = qname
priority? = number
mode? = tokens
as? = sequence-type>
[Definition: An xsl:template
declaration defines a template, which contains a
sequence constructor
for creating nodes and/or atomic values. A template can
serve either as a template rule, invoked by matching
nodes against a pattern, or as a named
template, invoked explicitly by name. It is also
possible for the same template to serve in both
capacities.]
[ERR XTSE0500] An xsl:template element
must have either a
match attribute or a name
attribute, or both. An xsl:template element
that has no match attribute must have no mode attribute and
no priority attribute.
If an xsl:template element
has a match attribute, then it is a template rule.
If it has a name attribute, then it is a
named
template.
A template
may be invoked in a number of ways, depending on whether it
is a template rule, a named
template, or both. The result of invoking the template
is the result of evaluating the sequence constructor
contained in the xsl:template element
(see 5.7 Sequence
Constructors).
If an as attribute is present, the
as attribute defines the required type of the
result. The result of evaluating the sequence constructor is then
converted to the required type using the function conversion
rules. If no as attribute is specified,
the default value is item()*, which permits
any value. No conversion then takes place.
[ERR XTTE0505] It is a type error if the result of evaluating the sequence constructor cannot be converted to the required type.
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 node or nodes
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 node used as the context node.
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 a node 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 node, only one of them is
evaluated, as described in 6.4
Conflict Resolution for Template Rules.
mode? = token>
The xsl:apply-templates
instruction takes as input a sequence of nodes (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 node in the input sequence is processed by finding
a template rule whose pattern matches that node.
If there is more than one, 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 node, a built-in
template rule is used (see 6.6
Built-in Template Rules). The chosen template rule
is evaluated. The rule that matches the Nth node
in the sorted sequence is evaluated with that node 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 node in the sorted sequence) are then
concatenated, to form a single sequence. They are
concatenated retaining the order of the nodes in the sorted
sequence. The final concatenated sequence forms the result
of the xsl:apply-templates
instruction.
Suppose the source document is as follows:
<message>Proceed <emph>at once</emph> to the exit!</message>
This can be processed using the two template rules shown below.
<xsl:template match="message">
<p>
<xsl:apply-templates select="child::node()"/>
</p>
</xsl:template>
<xsl:template match="emph">
<b>
<xsl:apply-templates select="child::node()"/>
</b>
</xsl:template>
There is no template rule for the document node; the
built-in template rule for this node will cause the
message element to be processed. The
template rule for the message element causes
a p element to be written to the result tree; the
contents of this p element are constructed
as the result of the xsl:apply-templates
instruction. This instruction selects the three child
nodes of the message element (a text node
containing the value "Proceed ", an
emph element node, and a text node
containing the value " to the exit!"). The
two text nodes are processed using the built-in template
rule for text nodes, which returns a copy of the text
node. The emph element is processed using
the explicit template rule that specifies
match="emph".
When the emph element is processed, this
template rule constructs a b element. The
contents of the b element are constructed by
means of another xsl:apply-templates
instruction, which in this case selects a single node
(the text node containing the value "at
once"). This is again processed using the built-in
template rule for text nodes, which returns a copy of the
text node.
The final result of the match="message"
template rule thus consists of a p element
node with three children: a text node containing the
value "Proceed ", a b element
that is the parent of a text node containing the value
"at once", and a text node containing the
value " to the exit!". This result tree
might be serialized as:
<p>Proceed <b>at once</b> to the exit!</p>
The default value of the select attribute
is child::node(), which causes all the
children of 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
nodes selected by an expression instead of processing all
children. The value of the select attribute is
an expression. The expression
must evaluate to a sequence of
nodes (it can contain zero, one, or more nodes).
[ERR XTTE0520] It is a type error if the
sequence returned by the select expression
contains an item that is not a node.
Note:
In XSLT 1.0, the select attribute
selected a set of nodes, which by default were processed
in document order. In XSLT 2.0, it selects a sequence of
nodes. In cases that would have been valid in XSLT 1.0,
the expression will return a sequence of nodes in
document order, so the effect is the same.
The following example processes all of the
given-name children of the
author elements that are children of
author-group:
<xsl:template match="author-group">
<fo:wrapper>
<xsl:apply-templates select="author/given-name"/>
</fo:wrapper>
</xsl:template>
It is also possible to process elements that are not
descendants of the context node. This example assumes
that a department element has
group children and employee
descendants. It finds an employee's department and then
processes the group children of the
department.
<xsl:template match="employee">
<fo:block>
Employee <xsl:apply-templates select="name"/> belongs to group
<xsl:apply-templates select="ancestor::department/group"/>
</fo:block>
</xsl:template>
It is possible to write template rules that are matched according to the schema-defined type of an element or attribute. The following example applies different formatting to the children of an element depending on their type:
<xsl:template match="product">
<table>
<xsl:apply-templates select="*"/>
</table>
</xsl:template>
<xsl:template match="product/*" priority="3">
<tr>
<td><xsl:value-of select="name()"/></td>
<td><xsl:next-match/></td>
</tr>
</xsl:template>
<xsl:template match="product/element(*, xs:decimal) |
product/element(*, xs:double)" priority="2">
<xsl:value-of select="format-number(xs:double(.), '#,###0.00')"/>
</xsl:template>
<xsl:template match="product/element(*, xs:date)" priority="2">
<xsl:value-of select="format-date(., '[Mn] [D], [Y]')"/>
</xsl:template>
<xsl:template match="product/*" priority="1.5">
<xsl:value-of select="."/>
</xsl:template>
The xsl:next-match
instruction is described in 6.7 Overriding Template
Rules.
Multiple xsl:apply-templates
elements can be used within a single template to do
simple reordering. The following example creates two HTML
tables. The first table is filled with domestic sales
while the second table is filled with foreign sales.
<xsl:template match="product">
<table>
<xsl:apply-templates select="sales/domestic"/>
</table>
<table>
<xsl:apply-templates select="sales/foreign"/>
</table>
</xsl:template>
It is possible for there to be two matching descendants where one is a descendant of the other. This case is not treated specially: both descendants will be processed as usual.
For example, given a source document
<doc><div><div></div></div></doc>
the rule
<xsl:template match="doc"> <xsl:apply-templates select=".//div"/> </xsl:template>
will process both the outer div and inner
div elements.
This means that if the template rule for the
div element processes its own children, then
these grandchildren will be processed more than once,
which is probably not what is required. The solution is
to process one level at a time in a recursive descent, by
using select="div" in place of
select=".//div"
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.
It is possible for a node in a source document to match more than one template rule. When this happens, only one template rule is evaluated for the node. The template rule to be used is determined as follows:
First, only the matching template rule or rules with the highest import precedence are considered. Other matching template rules with lower precedence are eliminated from consideration.
Next, of the remaining matching rules, only those
with the highest priority are considered. Other
matching template rules with lower priority are
eliminated from consideration. The priority of a
template rule is specified by the priority
attribute on the xsl:template
declaration.
[ERR
XTSE0530] The value of this attribute
must conform to the
rules for the xs:decimal type defined in
[XML Schema Part 2].
Negative values are permitted..
[Definition: If no priority
attribute is specified on the xsl:template
element, a default priority is computed, based
on the syntax of the pattern supplied in the
match attribute.] The rules are as follows:
If the pattern contains multiple alternatives
separated by | , then the template
rule is treated equivalently to a set of template
rules, one for each alternative. However, it is not
an error if a node matches more than one of the
alternatives.
If the pattern has the form /, then
the priority is −0.5.
If the pattern has the form of a QName optionally
preceded by a PatternAxis or has the form
processing-instruction(
StringLiteralXP)
or processing-instruction(NCName
Names) optionally
preceded by a PatternAxis, then the
priority is 0.
If the pattern has the form of an
ElementTestXP or
AttributeTestXP,
optionally preceded by a PatternAxis, then the
priority is as shown in the table below. In this
table, the symbols E, A, and
T represent an arbitrary element name,
attribute name, and type name respectively, while
the symbol