XML technologies / XSLT / Reference: XSLT 1.0 and 2.0 elements / template

(Excerpt from “XSLT 2.0 & XPath 2.0” by Frank Bongers, chapter 6.)

A | B | C | D | E | F | G | H | I | J | K | L | M | N | O | P | Q | R | S | T | U | V | W | X | Y | Z

 

The declaration xsl:template defines a template rule or named template. Its sequence constructor can generate arbitrary output in a result tree in connection with a processed node.

Classification

Declaration

Function group

Template rule of an XSLT stylesheet

Introduced in

XSLT 1.0

Stylesheet position and permitted contents:

The declaration xsl:template is one of XSL’s top-level elements and therefore appears only as a direct child of the root elements xsl:stylesheet or xsl:transform.

The declaration optionally contains a sequence constructor (called the template body in XSLT 1.0). Alternatively, it may be empty if no output is expressly wanted for the node, as with the implicit default rule for comment nodes.

Attributes:

The declaration xsl:template has several attributes: either match or name must be present, while mode and priority are optional in conjunction with match. XSLT 2.0 adds an optional as attribute.

as

Value

sequence-type

Usage

optional

Introduced in

XSLT 2.0

The value of the as attribute is an XPath 2.0 sequence type describing the datatype, form and content of the template rule’s output sequence.

The type specified by the as attribute governs the sequence constructor’s result type. The result sequence is converted to the required type. If conversion is impossible, a type error is reported.

Without the as attribute, the default sequence type is item()*, allowing any sequence of nodes and/or atomic values. Item conversion is then unnecessary and does not occur.

Note: The as attribute does not exist in XSLT 1.0.

match

Value

xpath-pattern

Usage

required or optional

Introduced in

XSLT 1.0

The match attribute is required if no name attribute is used; otherwise it is optional. If an xsl:template element has a match attribute, it is called a template rule.

The attribute value is an XPath pattern identifying which nodes offered in push processing (i.e. by xsl:apply-templates) the template rule should process. The pattern uses XPath 2.0 for XSLT 2.0 and XPath 1.0 for XSLT 1.0.

If several template rules match a pending node, the one with the highest priority or import precedence (see xsl:import) is selected. Priority is determined primarily by the priority attribute, or, if absent, the XPath pattern’s form (see the rules in the overview table below).

Note: If an xsl:template element has no match attribute, it must have a name attribute and may have neither a priority nor a mode attribute. A violation is an error (ERR XTSE0500).

mode

Value

tokenliste (in XSLT 1.0: qname)

Usage

optional

Introduced in

XSLT 1.0

Optional; forbidden if no match attribute is used. Its value is a token list of QNames identifying template modes. One must be the current mode (current mode) when the template rule is called.

Note — No token list for the mode attribute in XSLT 1.0:
XSLT 1.0 does not allow a token list: it requires a single QName, so a template rule can be called in at most one template mode. The wildcard * discussed below is not allowed either.

A template rule with a mode attribute can be activated only when the pending nodes are to be processed in the corresponding mode: the calling xsl:apply-templates must therefore use a mode attribute with an identical QName.

A call without a mode attribute can therefore be processed only by template rules without a mode attribute. This is the unnamed default mode.

XSLT 2.0 also allows the wildcard * instead of a token list or single QName. The rule can then always be activated, regardless of the current template mode—it “matches” every mode.

name

Value

qname

Usage

optional

Introduced in

XSLT 1.0

Required if there is no match attribute; otherwise optional. Its value must be a QName whose expanded form names the element. (If the identifier has no prefix, the default namespace is not used: the null namespace applies.) A template with a name attribute is a “named template”, not a “template rule”.

A named template is called exclusively with the instruction xsl:call-template. It cannot be activated by pending node lists in push processing. It is therefore neither meaningful nor permitted to use the priority or mode attribute for a named template.

Note: This last statement applies only if there is not also a match attribute allowing the template to serve as a template rule too.

priority

Value

numeric

Usage

optional

Introduced in

XSLT 1.0

This attribute is generally optional, but forbidden without a match attribute. Its value must be a number in the range ±9, determining the rule’s priority over rules with comparable match patterns.

This overrides the natural default priority derived from the pattern, whether higher or lower than the specified value. The priority attribute can therefore artificially lower a rule’s priority.

A template rule’s default priority is determined by the XPath pattern in its match attribute, following the rules in the table below.

Purpose:

The xsl:template declaration defines an XSLT stylesheet’s template rules and named templates for processing an input document. Instantiating these templates builds the result tree from their sequence constructors.

The template’s interior, its template body, consists of any sequence of XSLT instructions, literal result elements and text nodes. Instantiation executes the instructions and copies literal result elements and text nodes into the result tree.

The xsl:template declaration supports two kinds of templates: named templates and template rules.

Named templates with a name attribute:
A template can receive a qualified name through its name attribute. This QName may have a prefix bound to a namespace, in which case its expanded QName is used.

If the QName has no prefix, it is not in the default namespace established by the xmlns pseudoattribute (for example, on the stylesheet element), but in no namespace. Its expanded name therefore equals its local name.

Such a named template is not activated by a pending node list but must be called by name with xsl:call-template. In this sense, the call is independent of the current template rule, which remains unchanged, and resembles a subroutine.

A named template can contain parameters passed at the call through xsl:call-template (or required to be passed if they have the attribute required="yes" ). In XSLT 2.0, though not XSLT 1.0, addressing a parameter absent from the target template is an error.

Named templates can be distinguished only by name, not by template modes, for example. A stylesheet must therefore not contain two same-named templates at the same import precedence, including through included modules. An application may use the last declared template or report an error. Duplicates from imported modules are allowed, however, if one has higher import precedence than all others.

A named template may have an as attribute defining the returned sequence’s type, but neither a mode nor a priority attribute unless it also has a match attribute. In that case, the named template is also a template rule.

Template rules with a match pattern:
A template rule, often simply called a “template”, is an xsl:template declaration with a match attribute. (Note: A name attribute can also be present, allowing the rule to serve as a named template too; see above.)

The template rule’s match attribute defines an XPath matching pattern determining which pending nodes activate the template.

If several different rules can process a pending node, the highest-priority rule is chosen. This is usually the rule whose XPath pattern matches most precisely, potentially using the node’s context through descriptions of possible preceding nodes or predicates.

For example, the pattern match="beispiel/test" is more specific than match="test" or even match="element()". The natural priority resulting from a pattern’s structure is also called the default priority (explained in the table below). The priority attribute can additionally set a template rule’s priority to any value.

Two template rules with the same match pattern can be distinguished by processing mode. A template can then be activated by a pending node only if it is offered in a mode whose name appears in the token list of the mode attribute. Thus a template rule with a mode attribute requires a call with a matching mode, while a rule without a mode attribute requires a call without a mode.

Note — At most one mode at a time in XSLT 1.0:
Note that an XSLT 1.0 template rule can process at most one mode, since its mode attribute may contain only one mode QName.

Having several identical template rules in one stylesheet—with the same match pattern, import precedence and mode—is an error.

A template rule’s natural priority:
A rule’s natural priority (default priority) comes from the structure of its match pattern and ranges from +0.5 to -0.5. Patterns matching the pending node more precisely generally rank higher.

If a rule has two or more alternative patterns joined by the union operator (Note: This is the logical AND operator, not the Oder operator as often loosely stated.) “|”, for example match="pattern_a | pattern_b", it receives as many potentially different priorities, allowing comparison with rules whose patterns resemble each individual alternative.

The table below lists XPath patterns and their priorities. All are valid in XSLT 2.0; only those marked XPath 1.0 apply in XSLT 1.0.

Pattern form

Origin

Matches

Priority

Specifying ancestors, using predicates

XPath 1.0

Nodes in general

+0.5

element(qname, Schema-Typ)

XPath 2.0

Element nodes (fixed QName, fixed schema type)

+0.25

attribute(@qname, Schema-Typ)

XPath 2.0

Attribute nodes (fixed QName, fixed schema type)

+0.25

qname

XPath 1.0 

Element nodes (fixed QName, any schema type)

0

child::qname

XPath 1.0

element(qname)

XPath 2.0

element(qname, *)

XPath 2.0

@qname

XPath 1.0

Attribute nodes (fixed QName, any schema type)

0

attribute::qname

XPath 1.0

attribute(@qname)

XPath 2.0

attribute(@qname,*)

XPath 2.0

element(*, Schema-Typ)

XPath 2.0

Element nodes (any QName, fixed schema type)

0

attribute(@*, Schema-Typ)

XPath 2.0

Attribute nodes (any QName, fixed schema type)

0

processing-instruction('targetname')

XPath 1.0

PI nodes; target name as xs:string

0

präfix:*

XPath 1.0

Element nodes (fixed namespace)

-0.25

child::präfix:*

XPath 1.0

*:local-name

XPath 1.0

Element nodes (fixed local name)

-0.25

child::*:local-name

XPath 1.0

@präfix:*

XPath 1.0

Attribute nodes (fixed namespace)

-0.25

attribute::präfix:*

XPath 1.0

@*:local-name

XPath 1.0

Attribute nodes (fixed local name)

-0.25

attribute::*:local-name

XPath 1.0

*

XPath 1.0

Element nodes in general

-0.5

element()

XPath 2.0

element(*, *)

XPath 2.0

@*

XPath 1.0

Attribute nodes in general

-0.5

attribute()

XPath 2.0

attribute(@*, *)

XPath 2.0

/

XPath 1.0

Document node

-0.5

document-node()

XPath 2.0

comment()

XPath 1.0

Comment

-0.5

text()

XPath 1.0

Text nodes

-0.5

node()

XPath 1.0

Nodes in general

-0.5

Table: The natural priority of XPath patterns.

In both XSLT 1.0 and 2.0, natural (default) priority depends on the form of the pattern in the match attribute. In XSLT 1.0 this uses XPath 1.0: patterns marked XPath 2.0 above are unavailable, since the kind tests element() and attribute() as well as document-node() do not yet exist. XPath 1.0 also cannot test XML Schema types. Thus no XPath 1.0 equivalents exist for the type-related patterns marked +0.25. 

If a rule has a priority attribute, its value takes precedence regardless of a potentially higher default.

Note — No priority for named templates:
Priority does not apply to named templates called with xsl:call-template. A named template may also have a match attribute (and then possibly a priority attribute). Its priority then matters when it is activated as a template rule by other means, such as xsl:apply-templates.

Default template rules:
The stylesheet always implicitly contains the so-called default templates, which need not be defined explicitly. They apply when no matching rule is declared for a pending node. Their priority is correspondingly low, at -0.5. Any explicit rule ranks equally or higher; ties favor the explicit template. Default rules exist for all common node types:

Elements:
The implicit default template for elements is:

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

The asterisk wildcard activates this template whenever no other matching template is found. Apart from an xsl:apply-templates, it contains no instructions. It merely continues processing, which would otherwise stop here.

The assumption is that explicit templates may again exist for child elements. The template processes every mode and passes it to subsequent templates (sticky mode); for clarity, it could be written:

<xsl:template match="*" mode="*">    <xsl:apply-templa­tes/>
</xsl:template>

Document nodes:
A default template also exists for the document node:

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

This ensures XML document processing starts and eventually reaches an element with an explicit template.

Text nodes:
Another default template handles text nodes:

<xsl:template match="text()">    <xsl:value-of select="."/> </xsl:template>

The instruction xsl:value-of copies the current node’s string value—here the text node itself—into the result tree.

Attribute nodes:
The default template for attributes copies the string value of any attribute node @* into the result document. Switching to the attribute axis beforehand is required.

<xsl:template match="@*">    <xsl:value-of select="."/> </xsl:template>

Comment and PI nodes
Finally, two default templates handle comments and processing instructions:

<xsl:template match="comment()"/> <xsl:template match="processing-instructions()"/>

Both templates are empty and merely prevent unwanted processing of these node types. If processing is wanted, replace the default template with an explicit rule.

Note — Tunneling through default templates in XSLT 2.0:
In XSLT 2.0, default rules transparently pass parameters to subsequent templates. XSLT 1.0 has no equivalent tunneling through default rules.

Examples:

Example 1 — Using different template rules:

XML document (excerpt):

<?xml version="1.0" encoding="ISO-8859-1" ?>
<buch>
  <buchtitel>Der Buchtitel</buchtitel>
  <kapitel>
    <kapiteltitel>Kapitel Eins</kapiteltitel>
    <abschnitt>Der erste Abschnitt ...</abschnitt>
    <!-- mehr Abschnitte -->
  </kapitel>
  <!-- mehr Kapitel -->
</buch>

Stylesheet (excerpt):

...
<!-- Template-Regel für den Dokumentknoten (gekürzt) -->
<xsl:template match="/">
  <html>
    ...
    <xsl:apply-templates/>
    ...
  </html>
</xsl:template>
<!-- Template-Regel für das Wurzelelement -->
<xsl:template match="buch">
  <xsl:apply-templates select="buchtitel"/>
  ...
  <xsl:apply-templates select="kapitel"/>
</xsl:template>
<!-- Template-Regel für den Buchtitel -->
<xsl:template match="buchtitel">
  <h1><xsl:apply-templates/></h1>
</xsl:template>
<!-- Template-Regel für Kapitel -->
<xsl:template match="kapitel">
  <xsl:apply-templates select="kapitelueberschrift"/>
  <!-- den Kapiteltext verarbeiten -->
  ...
  <xsl:apply-templates/>
</xsl:template>
<!-- Template-Regel für Kapitelüberschrift -->
<xsl:template match="kapitelueberschrift">
  <h1><xsl:value-of select="."/></h1>
</xsl:template>

The stylesheet has a rule for each element in the simple XML document above. Processing starts with the document node’s rule (match="/"), which outputs the first nodes in the result sequence and calls subsequent templates without further restriction (since <buch> is the sole child, only its rule becomes active).

Using xsl:apply-templates, the rule for the <buch> element specifically creates node sequences that activate subsequent rules. There is no rule for the element <abschnitt>, so the built-in default element template processes it.

Example 2 — Named template with a name attribute

<xsl:template match="buch">
  <xsl:apply-templates select="buchtitel"/>
  <xsl:call-template name="inhalt"/>
  <xsl:apply-templates select="kapitel"/>
</xsl:template>
<xsl:template name="inhalt">
  <!-- Inhaltsverzeichnis generieren: -->
  <h2>Inhaltsverzeichnis:</h2>
  <ul>
    ...
  </ul>
</xsl:template>

The book’s HTML rendition also needs a table of contents. For this, xsl:call-template calls a template named "inhalt".

Example 3 — Template rules with a mode attribute:

<xsl:template name="inhalt">
  <!-- Inhaltsverzeichnis generieren: -->
  <h1>Inhaltsverzeichnis:</h1>
  <ul>
    <xsl:apply-templates select="//kapitelueberschrift" mode="inhalt"/>
  </ul>
</xsl:template>
<!-- mit mode für das Inhaltsverzeichnis -->
<xsl:template match="kapitelueberschrift" mode="inhalt">
  <li><xsl:value-of select="."/></li>
</xsl:template>
<!-- ohne mode für die Textausgabe des Buchs -->
<xsl:template match="kapitelueberschrift">
  <h1><xsl:value-of select="."/></h1>
</xsl:template>

The table of contents should output chapter headings, but their element <kapitelueberschrift> already has a rule intended to output the book’s body text.

The different formatting for the table of contents is handled by a rule with processing mode "inhalt", called by a corresponding mode attribute on an xsl:apply-templates instruction.

Example 4 — Template rules with use-when and priority attributes:

<xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <xsl:template match="/" priority="10" use-when="number(system-property('xsl:version')) = 1.0">
    <xsl:text>Dies läuft als XSLT 1.0</xsl:text>
    <!-- XSLT 1.0 Anweisungen -->
  </xsl:template>
  <xsl:template match="/" priority="9" use-when="number(system-property('xsl:version')) &gt;= 2.0">
    <xsl:text>Läuft als XSLT </xsl:text>
    <xsl:value-of select="system-property('xsl:version')"/>
    <xsl:for-each-group select="bla">
      <!-- XSLT 2.0 Anweisungen -->
    </xsl:for-each-group>
  </xsl:template>
</xsl:stylesheet>
  

To run a version 2.0 stylesheet on an XSLT 1.0 processor too, perhaps with different output but without an error, combine the use-when attribute, unknown to XSLT 1.0 processors, with the priority attribute, known to all processors. Both rules here have the same match attribute.

Because the stylesheet’s version is 2.0, an XSLT 1.0 processor operates in forwards-compatible mode. It ignores both rules’ unfamiliar use-when attributes. The first rule’s higher priority attribute makes it execute that rule and ignore the other.

An XSLT 2.0 processor would also favor the first rule according to its priority attribute. Since it would indeed take precedence, it must not be read in at all. The use-when attribute serves this purpose. Evaluation tells the XSLT 2.0 processor that the first rule is not intended for it, but the second is. Despite the priority attribute, it treats the first rule as nonexistent and uses the second one intended for it.

Element definition:

XSLT 1.0:

<!-- Category: top-level-element -->
<xsl:template 
     match = pattern 
     name = qname 
     priority = number 
     mode = qname>

     <!-- Content: (xsl:param*, template) -->
</xsl:template>

XSLT 2.0:

<!-- Category: declaration -->
<xsl:template
     match? = pattern
     name? = qname
     priority? = number
     mode? = tokens
     as? = sequence-type >

     <!-- Content: (xsl:param*, sequence-constructor) -->
</xsl:template>

   

  

back to top