Book HomeWebmaster in a Nutshell, 3rd EditionSearch this book

10.8. XSLT Elements

The following list is an enumeration of XSLT elements.

<xsl:apply-imports>

This styles the current node and each of its children using the imported style sheet rules, ignoring those in the style sheet that performed the import. Note that the rules don't apply to the current node's siblings or ancestors.

<xsl:apply-imports/>
<xsl:apply-templates>

This specifies that the immediate children (default) or the selected nodes of the source element should be processed further. For example:

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

This example processes the children of the selected <section> element after applying a bold tag. The optional select attribute determines which nodes should be processed:

<xsl:template match="section">
   <HR>
   <xsl:apply-templates
      select="paragraph (@indent)//sidebar"/>
   <HR>
   <xsl:apply-templates
      select="paragraph (@indent)/quote"/>
   <HR>
</xsl:template>

This example processes only specific children of the selected <section> element. In this case, the first target is a <sidebar> element that is a descendant of a <paragraph> element that has defined an indent attribute. The second target is a <quote> element that is the direct child of a <paragraph> element that has defined an indent attribute. The optional mode attribute causes only templates with a matching mode to be applied.

<xsl:apply-templates
   [select="node-set-expression"]>
[mode="mode"]/>
<xsl:attribute>

This adds an attribute with the given name to an element in the result tree. Only one attribute with a particular name can be added to a specific element. The contents of the <xsl:attribute> element form the value of the attribute:

<xsl:element name="book">
<xsl:attribute name="title">Moby Dick</xsl:attribute>
<xsl:text>This is about a whale</xsl:text>
</xsl:element>

This creates the following element in the result tree:

<book title="Moby Dick">This is about a whale</book>

The optional namespace attribute specifies a namespace for the new attribute.

<xsl:attribute name="name"
   [namespace="namespace"]>
   ...
</xsl:attribute>
<xsl:attribute set>

This allows the naming of a collection of attributes that can be applied to elements.

The following example creates an attribute set for images and applies them with a template:

<xsl:attribute-set name="image">
 <xsl:attribute name="border">0</xsl:attribute>
   <xsl:attribute name="width">120</xsl:attribute>
   <xsl:attribute name="height">60</xsl:attribute>
</xsl:attribute-set>
<xsl:template match="image">
   <img src="{@url}" xsl:use-attribute-sets="image"/>
</xsl:template>

The use-attribute-sets option allows you to include a list of other attribute sets in the one being defined.

<xsl:attribute-set
   name="name"
   [use-attribute-sets="list"]/>
<xsl:calltemplate>

This function invokes a template by its name. It is possible to specify parameters in the body of this element. The following example calls the template image while passing the parameters width and height:

<xsl:call-template name="image">
   <xsl:with-param name="width">120</xsl:with-param>
   <xsl:with-param name="height">60</xsl:with-param>
</xsl:call-template>
<xsl:call-template 
   name="name">
   ...
</xsl:call-template>
<xsl:choose>

The <xsl:choose> element, in conjunction with the elements <xsl:when> and <xsl:otherwise>, offers the ability to perform multiple condition tests. For example:

<xsl:template match="chapter/title">
   <xsl:choose>
      <xsl:when test="[position( )=1]">
          Start Here:
      </xsl:when>
      <xsl:otherwise>
          Then Read:
       </xsl:otherwise>
   </xsl:choose>
   <xsl:apply-templates/>
</xsl:template>

This example matches against each of the qualifying <title> elements, but it must test each <title> element to determine how to format it. Here, formatting depends on whether the element is first. The string Start Here: is applied before the first <title> element, and the string Then Read: is placed before the others.

<xsl:choose>
   ...
</xsl:choose>
<xsl:comment>

This inserts a comment into the XML document. For example:

<xsl:comment>English material below</xsl:comment>

is translated into a comment in the XML result tree when it is processed:

<!-- English material below -->
<xsl:comment>
   ...
</xsl:comment>
<xsl:copy>

This element copies the current node from the source document into the output document. This copies the node itself, as well as any namespace nodes the node possesses. However, it does not copy the node's content or attributes.

The &use-attribute-sets; attribute contains a whitespace-separated list with names of <xsl:attribute-set> elements. These attribute sets are merged, and all attributes in the merged set are added to the copied element. The &use-attribute-sets; attribute can only be used when the node copied is an element node.

<xsl:copy
   [use-attribute-sets="list"]>
   ...
</xsl:copy>
<xsl:copy-of>

The <xsl:copy-of> instruction inserts the result tree fragment identified by the select attribute into the output document. This copies not only the specific node or nodes identified by the expression, but also all those nodes' children, attributes, namespaces, and descendants. (This is how it differs from xsl:copy.) If the expression selects something other than a node set or a result tree fragment (e.g., a number), then the expression is converted to its string value, and the string is output.

<xsl:copy-of
   select="expression"/>
<xsl:decimalformat>

The <xsl:decimal-format> element defines a pattern by which the XPath format-number( ) function can convert floating-point numbers into text strings. The attributes are specified as follows:

name
The string by which the format-number( ) function identifies which <xsl:decimal-format> element to use. If this attribute is omitted, then the element establishes the default decimal format used by the format-number( ) function.

decimal-separator
The character that separates the integer part from the fractional part in a floating-point number. This is a period (decimal point) in English and a comma in French. It may be something else again in other languages.

grouping-separator
The character that separates groups of digits (e.g., the comma that separates every three digits in English).

infinity
The string that represents IEEE 754 infinity; infinity by default.

minus-sign
The character prefixed to negative numbers; a hyphen by default.

NaN
The string that represents IEEE 754 Not a Number; NaN by default.

percent
The character that represents a percent; % by default.

per-mille
The character that represents a per mille; #x2030 by default.

zero-digit
The character that represents zero in a format pattern; 0 by default.

digit
The character that represents a digit in a format pattern; # by default.

pattern-separator
The character that separates positive and negative subpatterns in a format pattern; a semicolon (;) by default.

<xsl:decimal-format
   [name ="name"]
   [decimal-separator = "char"]
   [grouping-separator = "char"]
   [infinity = "string"]
   [minus-sign = "char"]
   [NaN = "string"]
   [percent = "char"]
   [per-mille = "char"]
   [zero-digit = "char"]
   [digit = "char"]
   [pattern-separator = "char"]/>
<xsl:element>

This inserts the element <name> into the result document. For example:

<xsl:element name="book">
   <xsl:element name="chapter">
      <xsl:text>The Opening of Pandoras Box</xsl:text>
   </xsl:element>
</xsl:element>

This creates the following in the result tree:

<book>
   <chapter>The Opening of Pandoras Box</chapter>
</book>

Elements without explicit namespaces use the default namespace of their current context. Also, you can create a namespace for the element yourself:

<xsl:element name="OReilly:Book"
   namespace="http://www.oreilly.com">

This employs the namespace associated with the URI http://www.oreilly.com with the element. If no namespaces are associated with the URI, it becomes the default namespace.

The &use-attribute-sets; attribute contains a whitespace-separated list with names of <xsl:attribute-set> elements. These attribute sets are merged, and all attributes in the merged set are added to the element.

<xsl:element
   name="name"
   [namespace="URI"]
   [use-attribute-sets="list"]>
   ...
</xsl:element>
<xsl:fallback>

This element is used in conjunction with extension elements that aren't a part of XSLT 1.0. <xsl:fallback> defines a template to be invoked if the enclosing element is undefined. It's possible to test the availability of an element with element-available( ).

<xsl:fallback> ... </xsl:fallback>
<xsl:for-each>

The <xsl:for-each> directive allows you to select any number of nodes in an XML document that match the same expression given by select. For example, consider the following XML document:

<book>
   <chapter>
      <title>A Mystery Unfolds</title>
      <paragraph>
      It was a dark and stormy night...
      </paragraph>
   </chapter>
   <chapter>
      <title>A Sudden Visit</title>
      <paragraph>
      Marcus found himself sleeping...
      </paragraph>
   </chapter>
</book>

Note there are two <chapter> siblings in the document. Let's assume we want to provide an HTML numbered list for each <title> element that is the direct child of a <chapter> element, which in turn has a <book> element as a parent. The following template performs the task:

<xsl:template match="book>
   <ol>
   <xsl:for-each select="chapter">
      <li><xsl:process select="title"></li>
   </xsl:for-each>
   </ol>
</xsl:template>

After formatting, here is what the result looks like:

<ol>
<li>A Mystery Unfolds</li>
<li>A Sudden Visit</li>
</ol>

The XSLT processor processes a <title> element in each <chapter> element that is the child of a <book> element. The result is a numbered list of chapters that could be used for a table of contents.

<xsl:for-each select="node-set-expression"/>
<xsl:if>

You can use the <xsl:if> conditional to select a specific element while inside a template. The <xsl:if> element uses the test attribute to determine whether to include the contents of an element. The test attribute takes an expression that tests for a specific element or attribute. For example:

<xsl:template match="chapter/title">
   <xsl:apply-templates/>
   <xsl:if test="not([last( )])">, </xsl:if>
</xsl:template>

This template matches each qualifying <title> element but inserts commas only after those that are not the last <title> element. The result is a standard comma-separated list.

<xsl:if
   test="expression">
   ...
</xsl:if>
<xsl:import>

This specifies the URI of an XSL style sheet whose rules should be imported into this style sheet. The import statement must occur before any other elements in the style sheet. If a conflict arises between matching rules, rules in the XSL style sheet performing the import take precedence over rules in the imported style sheet. In addition, if more than one style sheet is imported into this document, the most recently imported style sheet takes precedence over stylesheets imported before it:

<xsl:import href="webpage.xsl"/>

This example imports the style sheet found in the webpage.xsl file.

<xsl:import href="address"/>
<xsl:include>

This specifies the name of an XSL style sheet that is to be included in the document. The include processing will replace the <xsl:include> statement with the contents of the file. Because the included document has been inserted in the referring style sheet, any included rules have the same preference as those in the referring style sheet (compare to <xsl:import>):

<xsl:include href="chapterFormats.xsl"/>
<xsl:include href="address"/>
<xsl:key>

Keys are comparable to identifiers in XML. This element is used in <xsl:stylesheet> to create a reference to elements specified by the pattern and expression values. For example:

<xsl:key name="chap" match="chapter" use="@title"/>

This element creates a key named chap to identify chapters by title. You can then reference a chapter with an XPath function such as:

key("chap", "The XSL Language")
<xsl:key name="name" 
   match="pattern" 
   use="expression"/>
<xsl:message>

The <xsl:message> instruction asks the XSLT processor to send a message to the user or calling program. Exactly what it does with those messages depends on the processor. One common use of <xsl:message> is to print debugging information.

If the terminate attribute is present and has the value yes, then the XSLT processor should halt after the message has been delivered and acted on.

<xsl:message [terminate="yes|no"]>
   ...
</xsl:message>
<xsl:namespace-alias>

The <xsl:namespace-alias> element declares that one namespace URI (prefix1) in the style sheet should be replaced by a different namespace URI (prefix2) in the result tree. Either attribute value can be set to #default to indicate that the nonprefixed default namespace is to be used.

<xsl:namespace-alias 
   stylesheet-prefix="prefix1" 
   result-prefix="prefix2"/>
<xsl:number>

This element inserts a formatted integer into the result tree. The value of this number can be determined by the attributes or generated by the XSLT processor. The attributes are described as follows:

value
This attribute contains an XPath expression returning the number to be formatted. If necessary, the number is rounded to the nearest integer. Most commonly, the value attribute is omitted, in which case the number is calculated from the position of the current node in the source document. The position is calculated as specified by the level, count, and from attributes.

count
This attribute contains a pattern that specifies which nodes should be counted at those levels. The default is to count all nodes of the same node type (element, text, attribute, etc.) and name as the current node.

from
This attribute contains a pattern identifying the node from which counting starts; that is, it says which node is number 1.

level
This attribute can be set to single (all preceding siblings of the ancestor of the current node that match the count pattern), multiple (for nested counting of each type of ancestor of the current node that match the count pattern), or any (count all nodes in the document that match the count pattern and precede the current node). The default is single.

format
This attribute determines how the list will be numbered. Format tokens include:

  • 1, 2, 3, 4, 5, 6

  • 01, 02, 03, 04, 05, 06, 07, 08, 09, 10, 11, 12

  • A, B, C, D...Z, AA, AB, AC...

  • a, b, c, d...z, aa, ab, ac...

  • i, ii, iii, iv, v, vi, vii, viii, ix, x, xi...

  • I, II, III, IV, V, VI, VII, VIII, IX, X, XI, XII...

You can change the starting point as well. For instance, setting the format token to 5 would create the sequence 5, 6, 7, 8, 9.

lang
This contains the RFC 1766 language code describing the language in which the number should be formatted (e.g., en or fr).

letter-value
The default is traditional. However, you can set this to alphabetic to indicate that a format of I should start the sequence I, J, K, L, M, N rather than I, II, III, IV, V, VI.

grouping-separator
This specifies the character that separates groups of digits. For instance, in English this is customarily the comma that separates every three digits, as in 2,987,667,342. In French a space is used instead so this number would be written as 2 987 667 342.

grouping-size
This specifies the number of digits in each group. In most languages, including English, digits are divided into groups of three. However, a few languages use groups of four instead.

<xsl:number
   [value = "expression"]
   [count = "pattern"]
   [from = "pattern"]
   [level = "single|multiple|any"]
   [format = "letter/digit"]
   [lang = "langcode"]
   [letter-value = "alphabetic|traditional"]
   [grouping-separator = "char"]
   [grouping-size = "number"] />
<xsl:otherwise>

This attribute specifies the default case in an <xsl:choose> element. See <xsl:choose> entry earlier in this reference section.

<xsl:otherwise>...</xsl:otherwise>
<xsl:output>

The <xsl:output> element helps determine the exact formatting of the XML document produced when the result tree is stored in a file, written onto a stream, or otherwise serialized into a sequence of bytes. It has no effect on the production of the result tree itself. The following attributes are defined:

method
The default method is xml, which simply implies that the serialized output document will be a well-formed parsed entity or XML document. If method is set to html, or if the method attribute is not present and the root element of the output tree is <html>, then empty element tags such as <br/> are converted to <br> when output, and a variety of other changes are to attempt to generate HTML that is more compatible with existing browsers. The text method only outputs the contents of the text nodes in the output tree. It strips all markup. XSLT processors are also allowed to recognize and support other values such as TeX or RTF.

version
This contains a name token that identifies the version of the output method. In practice, this has no effect on the output.

encoding
This contains the name of the encoding the outputter should use, such as ISO-8859-1 or UTF-16.

omit-xml-declaration
If this has the value yes, then no XML declaration is included. If it has the value no or is not present, then an XML declaration is included.

standalone
This sets the value of the standalone attribute in the XML declaration. Like that attribute, it must have the value yes or no.

doctype-public
This specifies the public identifier used in the document type declaration.

doctype-system
This specifies the system identifier used in the document type declaration.

cdata-section-elements
This is a whitespace-separated list of the qualified element names in the result tree whose contents should be emitted using a CDATA section rather than a character reference.

indent
If this has the value yes, the processor is allowed (but not required) to insert extra whitespace to attempt to "pretty-print" the output tree. The default is no.

media-type
This specifies the media type of the output, such as text/html or text/xml.

<xsl:output
   [method = "xml|html|text"]
   [version = "nmtoken"]
   [encoding = "encoding_name"]
   [omit-xml-declaration = "yes|no"]
   [standalone = "yes|no"]
   [doctype-public = "public_id"]
   [doctype-system = "system_id"]
   [cdata-section-elements = "element1 element2 ..."]
   [indent = "yes|no"]
   [media-type = "string"]/>
<xsl:param>

An <xsl:param> element binds its contents to the specified name, which can be called from and included in a template. As a top-level element, <xsl:param> provides a default value used if the named parameter is not supplied when a style sheet is called. An <xsl:param> element may also appear inside an <xsl:template> element to receive the values of the parameters passed in with <xsl:with-param>, and to provide a default value good only inside that template for the case where a proper <xsl:with-param> element is not used. If the select attribute is included, its value becomes the default value of the parameter, in which case the value of the content should be empty.

<xsl:param
   name="name"
   [select="expression"]>
   ...
</xsl:param>
<xsl:preserve-space>

This declares one or more XML elements in which all whitespace located between the opening and closing tags is preserved; hence, the XML processor will not remove it. By default, whitespace is not removed from elements; <xsl:preserve-space> can override any elements declared in the <xsl:strip-space> directive:

<xsl:preserve-space elements="title"/>
<xsl:preserve-space
   elements="element1 element2 ..."/>
<xsl:processing-instruction>

The <xsl:processing-instruction> element inserts a processing instruction into the result tree. This element cannot be used to generate an XML declaration; use <xsl:output> for that. The name attribute specifies the target of the processing instruction.

<xsl:processing-instruction
   name="name">
   ...
<xsl:processing-instruction>
<xsl:sort>

The <xsl:sort> instruction appears as a child of either <xsl:apply-templates> or <xsl:for-each>. It changes the order of the context node list from document order to some other order, such as alphabetic. Multiple-key sorts (for example, sort by last name, then by first name, then by middle name) can be performed with multiple <xsl:sort> elements in descending order of importance of the keys. The following attributes are defined:

select
This contains the key to sort by.

data-type
By default, sorting is purely alphabetic. However, alphabetic sorting leads to strange results with numbers. For instance, 10, 100, and 1000 all sort before 2, 3, and 4. You can specify numeric sorting by setting the data-type attribute to number.

lang
Sorting is language dependent. The language can be adjusted by setting the lang attribute to an RFC 1766 language code. The default language is system dependent.

order
This specifies the order by which strings are sorted. The value can be either descending or ascending. The default is ascending.

case-order
The case-order attribute can be set to upper-first or lower-first to specify whether uppercase letters sort before lowercase letters or vice versa. The default depends on the language.

<xsl:sort
   select = "expression"
   [data-type = "text|number"]
   [lang = "langcode"]
   [order = "ascending|descending"]
   [case-order = "upper-first|lower-first"]/>
<xsl:strip-space>

This declares an XML element or list of elements in which all whitespace located between the opening and closing tags is insignificant and should be removed by the XSL processor:

<xsl:strip-space elements="title"/>

Note that this is not necessarily the same as the xml:space="default" attribute, which allows the XSL processor more freedom to decide how to handle whitespace.

<xsl:strip-space
   elements="element1 element2 ..."/>
<xsl:stylesheet>

The <xsl:stylesheet> element is the root element for XSLT stylesheets. The contents of this element must first contain any <xsl:import> elements, followed by any other top-level elements in any order. <xsl:stylesheet> uses the following attributes:

version
The version number of XSLT used by the style sheet.

xmlns:xsl
This attribute contains a standard namespace declaration that maps the prefix xsl to the namespace URI http://www.w3.org/1999/XSL/Transform. The prefix can be changed if necessary. This attribute is technically optional, but de facto required.

id
Any XML name that's unique within the style sheet and is of type ID.

extension-element-prefixes
A whitespace-separated list of namespace prefixes used by extension elements in this document.

exclude-result-prefixes
A whitespace-separated list of namespace prefixes whose declarations should not be copied into the output document. If a namespace is needed in the output, it will be copied regardless.

<xsl:stylesheet
   version = "number"
   xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
   [id = "id"]
   [extension-element-prefixes = "prefix1 prefix2..."]
   [exclude-result-prefixes = "prefixa prefixb..."]>
   ...
</xsl:stylesheet>
<xsl:template>

The <xsl:template> top-level element is the key to all of XSLT. The match attribute contains a pattern against which nodes are compared as they're processed. If the pattern is the best match for a node, then the contents are instantiated and inserted into the output tree. This element uses the following attributes:

match
A pattern against which nodes can be compared. This pattern is a location path that uses the abbreviated XPath syntax. Only the child and attribute axes may be used. The // separator may also be used.

priority
A number. In the event that more than one template matches a given node, the one that most specifically matches the node is chosen. If several templates match a node with the same level of specificity, then the template with the highest value of the priority attribute is instantiated. If several matching templates have equal priorities, then the last one in the style sheet is chosen (the processor may also throw an error in this situation).

name
A name by which this template can be invoked from an <xsl:call-template> element rather than by node matching.

mode
The template's mode. If the <xsl:template> element has a mode, then this template is only matched when the mode attribute of the calling instruction matches the value of this mode attribute.

<xsl:template
   [match = "pattern"]
   [priority = "number"]
   [name = "name"]
   [mode = "mode"]>
   ...
</xsl:template>
<xsl:text>

This inserts text verbatim into the document. For example:

<xsl:text>The price is $20.00.</xsl:text>

is inserted into the XML document as:

The price is $20.00.

XML special characters (such as & and <) included in the content of this element are escaped (i.e., replaced by character entities) in the output by default. The attribute disable-output-escaping can be set to yes to disable this behavior.

<xsl:text>
   [disable-output-escaping="yes|no"]>
   ...
</xsl:text>
<xsl:value-of>

This extracts a specific value from a source tree. The select attribute is a single pattern-matching expression that resolves to the value of a string, an element, or an attribute:

<xsl:template match="index">
   This index is <xsl:value-of select="@(type)">
   <xsl:apply-templates/>
</xsl:template>

The select attribute extracts the value of an element or attribute in the source tree and prints it verbatim in the result tree. XML special characters (such as & and <) included in the content of this element are escaped (i.e., replaced by character entities) in the output by default. The attribute disable-output-escaping can be set to yes to disable this behavior.

<xsl:value-of select="expression">
   [disable-output-escaping="yes|no"]/>
<xsl:variable>

The top-level <xsl:variable> element binds a name to a value of any type (string, number, node set, etc.). The value can then be dereferenced elsewhere in the style sheet using the form $name in attribute value templates. Once a variable name has been assigned a value, it cannot change. The select attribute is an optional expression that sets the value of the variable. If <xsl:variable> has a select attribute, then it must be an empty element.

<xsl:variable
   name="name"
   [select="expression"]>
   ...
</xsl:variable>
<xsl:when>

This is a conditional for testing in an <xsl:choose> element. See <xsl:choose> entry earlier in this reference section.

<xsl:when
   test="expression">
   ...
</xsl:when>
<xsl:with-param>

The <xsl:with-param> element passes a named parameter to a template that expects it. It can be a child either of <xsl:apply-templates> or <xsl:call-template>. The parameter is received in the <xsl:template> by an <xsl:param> element with the same name. If a template expects to receive a particular parameter and doesn't get it, then it can take the default from the value of the <xsl:param> element instead.

<xsl:with-param
   name="name"
   [select="expression"]>
   ...
</xsl:with-param>


Library Navigation Links

Copyright © 2003 O'Reilly & Associates. All rights reserved.