5 Features of the XSLT Language

5.1 Names

5.1.1 Qualified Names

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

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

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

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

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

Note:

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

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

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

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

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

The following rules are used when interpreting a lexical QName:

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

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

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

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

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

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

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

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

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

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

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

5.1.2 Unprefixed Lexical QNames in Expressions and Patterns

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

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

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

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

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

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

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

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

5.1.3 Reserved Namespaces

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

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

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

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

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

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

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

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

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

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

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

Note:

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

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

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

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

Note:

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

5.2 Expressions

XSLT uses the expression language defined by XPath 3.0 [XPath 3.0]. Expressions are used in XSLT for a variety of purposes including:

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

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

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

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

Except where forwards compatible behavior is enabled (see 3.10 Forwards Compatible Processing), it is a static error if the value of such an attribute, or the text between curly brackets in an attribute value template or text value template, does not match the XPath production ExprXP30, or if it fails to satisfy other static constraints defined in the XPath specification, for example that all variable references must refer to variables that are in scope. Error codes are defined in [XPath 3.0].

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

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

[Definition: The context within a stylesheet where an XPath expression appears may specify the required type of the expression. The required type indicates the type of the value that the expression is expected to return.] If no required type is specified, the expression may return any value: in effect, the required type is then item()*.

[Definition:  When used in this specification without further qualification, the term function conversion rules means the function conversion rules defined in [XPath 3.0], applied with XPath 1.0 compatibility mode set to false.]

Note:

These are the rules defined in [XPath 3.0] for converting the supplied argument of a function call to the required type of that argument, as defined in the function signature. The same rules are used in XSLT for converting the value of a variable to the declared type of the variable, or the result of evaluating a function or template body to the declared type of the function or template. They are also used when parameters are supplied to a template using xsl:with-param. In all such cases, the rules that apply are the XPath 3.0 rules without XPath 1.0 compatibility mode. The rules with XPath 1.0 compatibility mode set to true are used only for XPath function calls, and for the operands of certain XPath operators.

This specification also invokes the XPath 3.0 function conversion rules to convert the result of evaluating an XSLT sequence constructor to a required type (for example, the sequence constructor enclosed in an xsl:variable, xsl:template, or xsl:function element).

Any dynamic error or type error that occurs when applying the function conversion rules to convert a value to a required type results in the transformation failing, in the same way as if the error had occurred while evaluating an expression.

Note:

Note the distinction between the two kinds of error that may occur. Attempting to convert an integer to a date is a type error, because such a conversion is never possible. Type errors can be reported statically if they can be detected statically, whether or not the construct in question is ever evaluated. Attempting to convert the string 2003-02-29 to a date is a dynamic error rather than a type error, because the problem is with this particular value, not with its type. Dynamic errors are reported only if the instructions or expressions that cause them are actually evaluated.

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

Note:

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

5.3 The Static and Dynamic Context

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

As well as providing values for the static and dynamic context components defined in the XPath specification, XSLT defines additional context components of its own. These context components are used by XSLT instructions (for example, xsl:next-match and xsl:apply-imports), and also by the functions in the extended function library described in this specification.

The following four sections describe:

5.3.1 Initializing the Static Context
5.3.2 Additional Static Context Components used by XSLT
5.3.3 Initializing the Dynamic Context
5.3.4 Additional Dynamic Context Components used by XSLT

5.3.1 Initializing the Static Context

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

5.3.2 Additional Static Context Components used by XSLT

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

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

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

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

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

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

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

Note:

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

5.3.3 Initializing the Dynamic Context

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

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

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

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

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

5.3.3.1 Maintaining Position: the Focus

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

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

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

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

[Definition: If the context item is a node (as distinct from an atomic value such as an integer), then it is also referred to as the context node. The context node is not an independent variable, it changes whenever the context item changes. When the context item is an atomic value or a function item, there is no context node.] The context node is returned by the XPath expression self::node(), and it is used as the starting node for all relative path expressions.

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

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

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

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

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

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

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

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

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

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

5.3.3.2 Other Components of the XPath Dynamic Context

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

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

  • The named functionsXP30 (representing the functions accessible using function-available or function-lookupFO30) include all the functions available in the static context, and may also include an additional implementation-defined set of functions that are available dynamically but not statically.

    Note:

    This set therefore includes some functions that are not available for dynamic calling using xsl:evaluate, for example stylesheet functions whose visibility is private, and XSLT-defined functions such as current and key.

    Note:

    The rule that all functions present in the static context must always be present in the dynamic context is a consistency constraint. The effect of violating a consistency constraint is implementation-defined: it does not necessarily lead to an error. For example, if the version of a used package that is available at evaluation time does not include all public user-defined functions that were available in the version that was used at analysis time, then a processor may recover by signaling an error only if the function is actually called. Conversely, if the evaluation-time version of the package includes additional public functions, these may be included in the dynamic context even though they were absent from the static context. Dynamic calling of functions using function-lookupFO30 may therefore be an effective strategy for coping with variations between versions of a library package on which a stylesheet depends.

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

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

    Note:

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

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

  • All other aspects of the dynamic context (for example, the current date and time, the implicit timezone, the default language, calendar, and place, the available documents, text resources, and collections, and the default collection — details vary slightly between XPath 3.0 and XPath 3.1) are implementation-defined, and do not change in the course of a single transformation, except to the extent that they may be different from one package to another.

5.3.4 Additional Dynamic Context Components used by XSLT

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

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

Components of the Dynamic Evaluation Context
Component Initial Setting Set by Cleared by
focus See 2.3 Initiating a Transformation. xsl:apply-templates, xsl:for-each, xsl:for-each-group, xsl:analyze-string, evaluation of patterns Calls to stylesheet functions
current template rule If apply-templates invocation is used (see 2.3.3 Apply-Templates Invocation), then for each item in the initial match selection, the current template rule is initially set to the template rule chosen for processing that item. Otherwise, absent. xsl:apply-templates, xsl:apply-imports, xsl:next-match See 6.8 Overriding Template Rules.
current mode the initial mode xsl:apply-templates Calls to stylesheet functions. Also cleared while evaluating global variables and stylesheet parameters, patterns, and the sequence constructor contained in xsl:key or xsl:sort. Clearing the current mode causes the current mode to be set to the default (unnamed) mode.
current group absent xsl:for-each-group See 14.2.1 fn:current-group.
current grouping key absent xsl:for-each-group See 14.2.2 fn:current-grouping-key.
current merge group absent xsl:merge See 15.6.1 fn:current-merge-group.
current merge key absent xsl:merge See 15.6.2 fn:current-merge-key.
current captured substrings empty sequence xsl:matching-substring xsl:non-matching-substring; Calls to stylesheet functions, dynamic function calls, evaluation of global variables, stylesheet parameters, and patterns
output state final output state Set to temporary output state by instructions such as xsl:variable, xsl:attribute, etc., and by calls on stylesheet functions None
current output URI base output URI xsl:result-document Calls to stylesheet functions, dynamic function calls, evaluation of global variables, stylesheet parameters, and patterns.

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

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

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

5.4 Defining a Decimal Format

The definition of the format-numberFO30 function is now in [Functions and Operators 3.0]. What remains here is the definition of the xsl:decimal-format declaration, which provides the context for this function when used in an XSLT stylesheet.

<!-- Category: declaration -->
<xsl:decimal-format
  name? = eqname
  decimal-separator? = char
  grouping-separator? = char
  infinity? = string
  minus-sign? = char
  exponent-separator? = char
  NaN? = string
  percent? = char
  per-mille? = char
  zero-digit? = char
  digit? = char
  pattern-separator? = char />

The xsl:decimal-format element sets the statically known decimal formats component of the static context for XPath expressions, which controls the interpretation of a picture string used by the format-numberFO30 function.

[Definition: The picture string is the string supplied as the second argument of the format-numberFO30 function.]

Note:

The format-numberFO30 function, previously defined in this specification, is now defined in [Functions and Operators 3.0].

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

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

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

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

The scope of an xsl:decimal-format name is the package in which it is declared; the name is available for use only in calls to format-numberFO30 that appear within the same package.

If a package does not contain a declaration of the unnamed decimal format, a declaration equivalent to an xsl:decimal-format element with no attributes is implied.

The attributes of the xsl:decimal-format declaration establish values for a number of variables used as input to the algorithm followed by the format-numberFO30 function. An outline of the purpose of each attribute is given below; however, the definitive explanations are given as part of the specification of format-numberFO30.

For any named decimal format, the effective value of each attribute is taken from an xsl:decimal-format declaration that has that name, and that specifies an explicit value for the required attribute. If there is no such declaration, the default value of the attribute is used. If there is more than one such declaration, the one with highest import precedence is used.

For any unnamed decimal format, the effective value of each attribute is taken from an xsl:decimal-format declaration that is unnamed, and that specifies an explicit value for the required attribute. If there is no such declaration, the default value of the attribute is used. If there is more than one such declaration, the one with highest import precedence is used.

[ERR XTSE1290] It is a static error if a named or unnamed decimal format contains two conflicting values for the same attribute in different xsl:decimal-format declarations having the same import precedence, unless there is another definition of the same attribute with higher import precedence.

The following attributes control the interpretation of characters in the picture string supplied to the format-numberFO30 function, and also specify characters that may appear in the result of formatting the number. In each case the value must be a single character [see ERR XTSE0020].

[ERR XTSE1295] It is a static error if the character specified in the zero-digit attribute is not a digit or is a digit that does not have the numeric value zero.

The following attributes control the interpretation of characters in the picture string supplied to the format-numberFO30 function. In each case the value must be a single character [see ERR XTSE0020].

The following attributes specify characters or strings that may appear in the result of formatting the number:

[ERR XTSE1300] It is a static error if, for any named or unnamed decimal format, the variables representing characters used in a picture string do not each have distinct values. These variables are decimal-separator-sign, grouping-sign, percent-sign, per-mille-sign, digit-zero-sign, digit-sign, and pattern-separator-sign.

Every (named or unnamed) decimal format defined in a package is added to the statically known decimal formatsXP30 in the static contextXP30 of every expression in the package, excluding expressions appearing in [xsl:]use-when attributes.

5.5 Patterns

In XSLT 3.0, patterns can match any kind of item: atomic values and function items as well as nodes.

A template rule identifies the items to which it applies by means of a pattern. As well as being used in template rules, patterns are used for numbering (see 12 Numbering), for grouping (see 14 Grouping), and for declaring keys (see 20.2 Keys).

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

There are two kinds of pattern: predicate patterns, and selection patterns:

Note:

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

5.5.1 Examples of Patterns

Example: Patterns

Here are some examples of patterns:

  • . matches any item.

  • * matches any element.

  • para matches any para element.

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

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

  • appendix//para matches any para element with an appendix ancestor element.

  • schema-element(us:address) matches any element that is annotated as an instance of the type defined by the schema element declaration us:address, and whose name is either us:address or the name of another element in its substitution group.

  • attribute(*, xs:date) matches any attribute annotated as being of type xs:date.

  • / matches a document node.

  • document-node() matches a document node.

  • document-node(schema-element(my:invoice)) matches the document node of a document whose document element is named my:invoice and matches the type defined by the global element declaration my:invoice.

  • text() matches any text node.

  • namespace-node() matches any namespace node.

  • node() matches any node other than an attribute node, namespace node, or document node.

  • id("W33") matches the element with unique ID W33.

  • para[1] matches any para element that is the first para child element of its parent. It also matches a parentless para element.

  • //para matches any para element in a tree that is rooted at a document node.

  • bullet[position() mod 2 = 0] matches any bullet element that is an even-numbered bullet child of its parent.

  • div[@class="appendix"]//p matches any p element with a div ancestor element that has a class attribute with value appendix.

  • @class matches any class attribute (not any element that has a class attribute).

  • @* matches any attribute node.

  • $xyz matches any node that is present in the value of the variable $xyz.

  • $xyz//* matches any element that is a descendant of a node that is present in the value of the variable $xyz.

  • doc('product.xml')//* matches any element within the document whose document URI is 'product.xml'.

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

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

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

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

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

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

5.5.2 Syntax of Patterns

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

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

The lexical rules for patterns are the same as the lexical rules for XPath expressions, as defined in Section A.2 Lexical structure XP30. Comments are permitted between tokens, using the syntax (: ... :). All other provisions of the XPath grammar apply where relevant, for example the rules for whitespace handling and extra-grammatical constraints.

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

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

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

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

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

Note:

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

5.5.3 The Meaning of a Pattern

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

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

Note:

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

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

Otherwise (the pattern is a selection pattern), the pattern is converted to an expression, called the equivalent expression. The equivalent expression to a Pattern is the XPath expression that takes the same lexical form as the Pattern as written, with the following adjustment:

  • If any PathExprP in the Pattern is a RelativePathExprP, then the first StepExprP PS of this RelativePathExprP is adjusted to allow it to match a parentless element, attribute, or namespace node. The adjustment depends on the axis used in this step, whether it appears explicitly or implicitly (according to the rules of Section 3.3.5 Abbreviated Syntax XP30), and is made as follows:

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

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

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

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

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

    Note:

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

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

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

  1. N is a node, and the result of evaluating the expression root(.)//(EE) with a singleton focus based on N is a sequence that includes the node N

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

Example: The Semantics of Selection Patterns

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

The selection pattern node() matches all nodes selected by the expression root(.)//(child-or-top::node()), that is, all element, text, comment, and processing instruction nodes, whether or not they have a parent. It does not match attribute or namespace nodes because the expression does not select nodes using the attribute or namespace axes. It does not match document nodes because for backwards compatibility reasons the child-or-top axis does not match a document node.

The selection pattern $V matches all nodes selected by the expression root(.)//($V), that is, all nodes in the value of $V (which will typically be a global variable, though when the pattern is used in contexts such as the xsl:number or xsl:for-each-group instructions, it can also be a local variable).

The selection pattern doc('product.xml')//product matches all nodes selected by the expression root(.)//(doc('product.xml')//product), that is, all product elements in the document whose URI is product.xml.

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

Although the semantics of selection patterns are specified formally in terms of expression evaluation, it is possible to understand pattern matching using a different model. A selection pattern such as book/chapter/section can be examined from right to left. A node will only match this pattern if it is a section element; and then, only if its parent is a chapter; and then, only if the parent of that chapter is a book. When the pattern uses the // operator, one can still read it from right to left, but this time testing the ancestors of a node rather than its parent. For example appendix//section matches every section element that has an ancestor appendix element.

The formal definition, however, is useful for understanding the meaning of a pattern such as para[1]. This matches any node selected by the expression root(.)//(child-or-top::para[1]): that is, any para element that is the first para child of its parent, or a para element that has no parent.

Note:

An implementation, of course, may use any algorithm it wishes for evaluating patterns, so long as the result corresponds with the formal definition above. An implementation that followed the formal definition by evaluating the equivalent expression and then testing the membership of a specific node in the result would probably be very inefficient.

5.5.4 Errors in Patterns

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

Note:

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

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

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

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

5.6 Value Templates

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

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

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

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

It is a static error if the string contained between matching curly brackets in a value template does not match the XPath production Expr?XP30, or if it contains other XPath static errors. The error is signaled using the appropriate XPath error code.

[ERR XTSE0370] It is a static error if an unescaped right curly bracket occurs in a fixed part of a value template.

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

Note:

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

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

5.6.1 Attribute Value Templates

[Definition: In an attribute that is designated as an attribute value template, such as an attribute of a literal result element, an expression can be used by surrounding the expression with curly brackets ({}), following the general rules for value templates].

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

Note:

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

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

Note:

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

Example: Attribute Value Templates

The following example creates an img result element from a photograph element in the source; the value of the src and width attributes are computed using XPath expressions enclosed in attribute value templates:

<xsl:variable name="image-dir" select="'/images'"/>

<xsl:template match="photograph">
  <img src="{$image-dir}/{href}" width="{size/@width}"/>
</xsl:template>

With this source

<photograph>
  <href>headquarters.jpg</href>
  <size width="300"/>
</photograph>

the result would be

<img src="/images/headquarters.jpg" width="300"/>

 

Example: Producing a Space-Separated List

The following example shows how the values in a sequence are output as a space-separated list. The following literal result element:

<temperature readings="{10.32, 5.50, 8.31}"/>

produces the output node:

<temperature readings="10.32 5.5 8.31"/>

Curly brackets are not recognized recursively inside expressions.

Example: Curly Brackets cannot be Nested

For example:

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

is not allowed. Instead, use simply:

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

5.6.2 Text Value Templates

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

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

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

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

Note:

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

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

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

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

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

 

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

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

Note:

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

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

5.7 Sequence Constructors

[Definition: A sequence constructor is a sequence of zero or more sibling nodes in the stylesheet that can be evaluated to return a sequence of nodes, atomic values, and function items. The way that the resulting sequence is used depends on the containing instruction.]

Many XSLT elements, and also literal result elements, are defined to take a sequence constructor as their content.

Four kinds of nodes may be encountered in a sequence constructor:

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

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

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

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

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

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

[Definition: The result of evaluating a sequence constructor is the sequence of items formed by concatenating the results of evaluating each of the nodes in the sequence constructor, retaining order. This is referred to as the immediate result of the sequence constructor.]

However:

The way that immediate result of a sequence constructor is used depends on the containing element in the stylesheet, and is specified in the rules for that element. It is typically one of the following:

5.7.1 Constructing Complex Content

Many instructions, for example xsl:copy, xsl:element, xsl:document, xsl:result-document, and literal result elements, create a new parent node, and evaluate a sequence constructor forming the content of the instruction to create the attributes, namespaces, and children of the new parent node. The immediate result of the sequence constructor is processed to create the content of the new parent node as described in this section.

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

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

  2. Any array item in the sequence (see 27.7.1 Arrays) is replaced by its members, recursively. This is equivalent to applying the array:flattenFO31 function defined in [Functions and Operators 3.1].

    Note:

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

  3. Any atomic value in the sequence is cast to a string.

    Note:

    Casting from xs:QName or xs:NOTATION to xs:string always succeeds, because these values retain a prefix for this purpose. However, there is no guarantee that the prefix used will always be meaningful in the context where the resulting string is used.

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

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

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

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

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

    [ERR XTDE0410] It is a dynamic error if the sequence used to construct the content of an element node contains a namespace node or attribute node that is preceded in the sequence by a node that is neither a namespace node nor an attribute node.

    [ERR XTDE0420] It is a dynamic error if the sequence used to construct the content of a document node contains a namespace node or attribute node.

    [ERR XTDE0430] It is a dynamic error if the sequence contains two or more namespace nodes having the same name but different string values (that is, namespace nodes that map the same prefix to different namespace URIs).

    [ERR XTDE0440] It is a dynamic error if the sequence contains a namespace node with no name and the element node being constructed has a null namespace URI (that is, it is an error to define a default namespace when the element is in no namespace).

    [ERR XTDE0450] It is a dynamic error if the result sequence contains a function item.

  9. If the sequence contains two or more namespace nodes with the same name (or no name) and the same string value (that is, two namespace nodes mapping the same prefix to the same namespace URI), then all but one of the duplicate nodes are discarded.

    Note:

    Since the order of namespace nodes is implementation-dependent, it is not significant which of the duplicates is retained.

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

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

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

    Note:

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

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

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

Example: A Sequence Constructor for Complex Content

Consider the following stylesheet fragment:

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

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

 

Example: Space Separators in Element Content

Consider the following stylesheet fragment:

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

This produces the output (when indented):

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

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

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

5.7.2 Constructing Simple Content

The instructions xsl:attribute, xsl:comment, xsl:processing-instruction, xsl:namespace, and xsl:value-of all create nodes that cannot have children. Specifically, the xsl:attribute instruction creates an attribute node, xsl:comment creates a comment node, xsl:processing-instruction creates a processing instruction node, xsl:namespace creates a namespace node, and xsl:value-of creates a text node. The string value of the new node is constructed using either the select attribute of the instruction, or the sequence constructor that forms the content of the instruction. The select attribute allows the content to be specified by means of an XPath expression, while the sequence constructor allows it to be specified by means of a sequence of XSLT instructions. The select attribute or sequence constructor is evaluated to produce a result sequence, and the string value of the new node is derived from this result sequence according to the rules below.

These rules are also used to compute the effective value of a value template. In this case the sequence being processed is the result of evaluating an XPath expression enclosed between curly brackets, and the separator is a single space character.

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

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

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

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

  5. The strings within the resulting sequence are concatenated, with a (possibly zero-length) separator inserted between successive strings. The default separator depends on the containing instruction; except where otherwise specified, it is a single space.

    In the case of xsl:attribute and xsl:value-of, the default separator is a single space when the select attribute is used, or a zero-length string otherwise; a different separator can be specified using the separator attribute of the instruction.

    In the case of xsl:comment, xsl:processing-instruction, and xsl:namespace, and when expanding a value template, the default separator cannot be changed.

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

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

Example: Space Separators in Attribute Content

Consider the following stylesheet fragment:

<doc>
  <xsl:attribute name="e" select="1 to 5"/>
  <xsl:attribute name="f">
    <xsl:for-each select="1 to 5">
      <xsl:value-of select="."/>
    </xsl:for-each>
  </xsl:attribute>
  <xsl:attribute name="g" expand-text="yes">{1 to 5}</xsl:attribute>
</doc>

This produces the output:

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

The difference between the three cases is as follows. For the e attribute, the sequence constructor generates a sequence of five atomic values, which are therefore separated by spaces. For the f attribute, the content is supplied as a sequence of five text nodes, which are concatenated without space separation. For the g attribute, the text value template constructs a text node using the rules for constructing simple content, which insert space separators between atomic values; the text node is then atomized to form the value of the attribute.

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

Note:

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

5.7.3 Namespace Fixup

In a tree supplied to or constructed by an XSLT processor, the constraints relating to namespace nodes that are specified in [XDM 3.0] must be satisfied. For example:

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

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

  • Every element must have a namespace node whose expanded QName has local-part xml and whose string value is http://www.w3.org/XML/1998/namespace. The namespace prefix xml must not be associated with any other namespace URI, and the namespace URI http://www.w3.org/XML/1998/namespace must not be associated with any other prefix.

  • A namespace node must not have the name xmlns or the string value http://www.w3.org/2000/xmlns/.

[Definition: The rules for the individual XSLT instructions that construct a result tree (see 11 Creating Nodes and Sequences) prescribe some of the situations in which namespace nodes are written to the tree. These rules, however, are not sufficient to ensure that the prescribed constraints are always satisfied. The XSLT processor must therefore add additional namespace nodes to satisfy these constraints. This process is referred to as namespace fixup.]

The actual namespace nodes that are added to the tree by the namespace fixup process are implementation-dependent, provided firstly, that at the end of the process the above constraints must all be satisfied, and secondly, that a namespace node must not be added to the tree unless the namespace node is necessary either to satisfy these constraints, or to enable the tree to be serialized using the original namespace prefixes from the source document or stylesheet.

Namespace fixup must not result in an element having multiple namespace nodes with the same name.

Namespace fixup may, if necessary to resolve conflicts, change the namespace prefix contained in the QName value that holds the name of an element or attribute node. This includes the option to add or remove a prefix. However, namespace fixup must not change the prefix component contained in a value of type xs:QName or xs:NOTATION that forms the typed value of an element or attribute node.

Note:

Namespace fixup is not used to create namespace declarations for xs:QName or xs:NOTATION values appearing in the content of an element or attribute.

Where values acquire such types as the result of validation, namespace fixup does not come into play, because namespace fixup happens before validation: in this situation, it is the user’s responsibility to ensure that the element being validated has the required namespace nodes to enable validation to succeed.

Where existing elements are copied along with their existing type annotations (validation="preserve") the rules require that existing namespace nodes are also copied, so that any namespace-sensitive values remain valid.

Where existing attributes are copied along with their existing type annotations, the rules of the XDM data model require that a parentless attribute node cannot contain a namespace-sensitive typed value; this means that it is an error to copy an attribute using validation="preserve" if it contains namespace-sensitive content.

Namespace fixup is applied to every element that is constructed using a literal result element, or one of the instructions xsl:element, xsl:copy, or xsl:copy-of. An implementation is not required to perform namespace fixup for elements in any source document, that is, for a document in the initial match selection, documents loaded using the document, docFO30 or collectionFO30 function, documents supplied as the value of a stylesheet parameter, or documents returned by an extension function or extension instruction.

Note:

A source document (an input document, a document returned by the document, docFO30 or collectionFO30 functions, a document returned by an extension function or extension instruction, or a document supplied as a stylesheet parameter) is required to satisfy the constraints described in [XDM 3.0], including the constraints imposed by the namespace fixup process. The effect of supplying a pseudo-document that does not meet these constraints is implementation-dependent.

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

Note:

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

5.8 URI References

[Definition: Within this specification, the term URI Reference, unless otherwise stated, refers to a string in the lexical space of the xs:anyURI datatype as defined in [XML Schema Part 2].] Note that this is a wider definition than that in [RFC3986]: in particular, it is designed to accommodate Internationalized Resource Identifiers (IRIs) as described in [RFC3987], and thus allows the use of non-ASCII characters without escaping.

URI References are used in XSLT with three main roles:

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

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

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

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

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