XML technologies / XSLT / Java and XSLT / XSLT – Advanced techniques / Parameters and variables
(Excerpt from “Java und XSLT” by Eric M. Burke)
Like other languages, XSLT often needs values available at several places. Store a repeated book title in a variable instead of searching XML repeatedly. A variable can also be passed to templates as a parameter. These often use <xsl:if> or <xsl:choose> to vary output according to parameters.
<xsl:variable>
Variables are defined with <xsl:variable> globally or locally. Global variables are top-level, outside templates as direct children of <xsl:stylesheet>, and available throughout the stylesheet, even in templates preceding their declarations.
Local variables are declared inside templates and accessible only to elements following the declaration of <xsl:variable> and their descendants in that template. Example <xsl:choose> showed this use of <xsl:variable> for font definition.
Defining variables
Variables can be defined in three ways:
<xsl:variable name="homePage">index.html</xsl:variable>
<xsl:variable name="ersterTermin" select="termin [position() = first( )]/beginn"/>
<xsl:variable name="leer"/>In the first line, the content of <xsl:variable> specifies the variable name. Here text index.html is assigned to variable homePage. Content can be more complex, as in example <xsl:choose>. The second method uses attribute select containing an expression in XPath, here selecting the last appointment in a list. Finally, without attribute select or content, the variable is an empty string. The third line equals:
<xsl:variable name="leer" select="''"/>Using variables
Reference a variable name with a $ sign. Here an XPath location path retrieves the current federal president’s name and stores it in variable aktuellerBundespraesident:
<xsl:variable name="aktuellerBundespraesident" select="bundespraesident[position() = last( )]/name"/>Later in the same stylesheet, display variable aktuellerBundespraesident with this line:
<xsl:value-of select="$aktuellerBundespraesident"/>Because attribute select of <xsl:value-of> expects XPath, $aktuellerBundespraesident is dynamic rather than literal text. Inside HTML attribute values, use Attribute Value Template (AVT) syntax and surround references with braces:
<a href="{$homePage}">klicken Sie hier, um zur Homepage zu gelangen...</a>Without braces the reference would be interpreted as text, not dynamically.
Variables cannot be changed, so cannot serve as counters in <xsl:for-each> (loop ). Programmers used to mutable variables may find this frustrating. Usually pass a parameter to a template rather than use a global variable, then call it recursively with an increased parameter. An example follows.
Another trick combines initialization with <xsl:choose>. Values cannot be assigned later. Put the variable declaration inside <xsl:variable>, for example with <xsl:choose>:
<xsl:variable name="mittelName">
<xsl:choose>
<xsl:when test="mittelinitial">
<xsl:value-of select="mittelinitial"/>
</xsl:when>
<xsl:otherwise>
<xsl:text> </xsl:text>
</xsl:otherwise>
</xsl:choose>
</xsl:variable>This defines variable mittelName. If element <mittelinitial> exists, its value is assigned to mittelName. Otherwise a space is assigned.
<xsl:call-template> and named templates
So far templates have been tied to source XML. This one matches element <angestellter>, so <angestellter> must occur in your XML.
<xsl:template match="angestellter">
...Inhalt, beispielsweise Name und Sozialversicherungsnummer des Angestellten
</xsl:template>You may want to reuse it for elements other than <angestellter>. Besides elements <angestellter>, display the same information for a <programmierer> or <manager>. Use <xsl:call-template> to call a template by name rather than matching source XML. It takes this form:
<xsl:template name="formatiereSVNr">
...Inhalt
</xsl:template>Use it with these data; both <manager> and <programmierer> elements carry attribute svnr for social security numbers. A single named template, a template bearing attribute name, avoids separate templates for <manager> and <programmierer>. A complete stylesheet follows in the parameter discussion.
<?xml version="1.0" encoding="ISO-8859-1"?>
<team>
<manager svnr="4230568737">
<name>Daniel Bosen</name>
</manager>
<programmierer svnr="3593776766">
<name>Frank Moritz</name>
</programmierer>
<programmierer svnr="9953885777">
<name>Frank Müller</name>
</programmierer>
</team><xsl:param> and <xsl:with-param>
Named templates are difficult to use without parameters, which also work for ordinary templates. Parameters vary behavior by caller-supplied data, producing reusable code. They pass data such as a social security number to named templates. This complete stylesheet passes parameter svnr to a named template.
Example: NamedTemplate.xslt
<?xml version="1.0" encoding="ISO-8859-1"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="html"/>
<xsl:template match="/">
<html>
<body>
<h3>Team-Mitglieder</h3>
<ul>
<xsl:for-each select="team/manager|team/programmierer">
<xsl:sort select="name"/>
<li>
<xsl:value-of select="name"/>
<xsl:text>, svnr = </xsl:text>
<xsl:call-template name="formatiereSVNR">
<xsl:with-param name="svnr" select="@svnr"/>
</xsl:call-template>
</li>
</xsl:for-each>
</ul>
</body>
</html>
</xsl:template>
<!-- ein Named-Template, das die 10-stellige SVNr durch Einfügen von '-'-Zeichen formatiert -->
<xsl:template name="formatiereSVNR">
<xsl:param name="svnr"/>
<xsl:value-of select="substring($svnr, 1, 3)"/>
<xsl:text>-</xsl:text>
<xsl:value-of select="substring($svnr, 4, 2)"/>
<xsl:text>-</xsl:text>
<xsl:value-of select="substring($svnr, 6)"/>
</xsl:template>
</xsl:stylesheet>This lists managers and programmers by name. Element <xsl:for-each> selects the union of team/manager and team/programmierer, including everyone. The pipe operator (|) computes their union:
<xsl:for-each select="team/manager|team/programmierer">Each manager or programmer’s element <name> is printed, followed by attribute svnr passed to template formatiereSVNR. Pass parameters by adding <xsl:with-param> as a child of <xsl:call-template>. Add further <xsl:with-param> elements as children of <xsl:call-template> for more parameters. Finally, <xsl:param> is used as follows:
<xsl:template name="formatiereSVNR">
<xsl:param name="svnr"/>
...Here parameter svnr defaults to an empty string when not supplied. Set a default with attribute select. The zeros below are quoted to make a string rather than an XPath expression:
<xsl:param name="svnr" select="'000000000'"/>In template formatiereSVNR, function substring( ) extracts parts of the social security number. We discuss substring( ) and other string functions later.
Incrementing variables
XSLT has no standard way to increment variables; once defined they are immutable, like a Java field marked final. Recursion with template parameters sometimes achieves the same effect, as shown with stammbaum.xml.
Example: stammbaum.xml
<?xml version="1.0" encoding="ISO-8859-1"?>
<?xml-stylesheet type="text/xsl" href="stammbaum.xslt"?>
<person name="Otto">
<person name="Sandra">
<person name="Jeremy">
<person name="Eliana"/>
</person>
<person name="Eric">
<person name="Aidan"/>
</person>
<person name="Philip">
<person name="Alex"/>
<person name="Andy"/>
</person>
</person>
</person>These data are recursive. Each element <person> may contain any number of child elements <person>, themselves containing further children <person>. This simplified family tree illustrates a common XML pattern. Display generations with indentation: Otto at the root, Sandra one space in, and her children another space further. This visualizes relationships:
Otto
Sandra
Jeremy
Eliana
Eric
Aidan
Philip
Alex
AndyThe stylesheet producing this output is stammbaum.xslt.
Example: stammbaum.xslt
<?xml version="1.0" encoding="ISO-8859-1"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="html"/>
<!-- hier beginnt die Verarbeitung -->
<xsl:template match="/">
<html>
<body>
<!-- wählt den ältesten Vorfahr -->
<xsl:apply-templates select="person">
<xsl:with-param name="ebene" select="'0'"/>
</xsl:apply-templates>
</body>
</html>
</xsl:template>
<!-- Informationen über eine Person ausgeben und Kinder rekursiv selektieren. -->
<xsl:template match="person">
<xsl:param name="ebene"/>
<!-- je nach Ebene einrücken -->
<div style="text-indent:{$ebene}em">
<xsl:value-of select="@name"/>
</div>
<!-- Rekursiv die Kinder auswählen und die Variable inkrementieren -->
<xsl:apply-templates select="person">
<xsl:with-param name="ebene" select="$ebene + 1"/>
</xsl:apply-templates>
</xsl:template>
</xsl:stylesheet>As usual, it matches the root and emits a basic HTML document, then selects root element <person> and passes ebene=0 as a parameter to the template matching person:
<xsl:apply-templates select="person">
<xsl:with-param name="ebene" select="'0'"/>
</xsl:apply-templates>The template for person uses an HTML tag <div> to display each name on a new line, with indentation in em. CSS interprets an em as the width of a lowercase m in the current font. Finally, the template for person calls itself with parameter $ebene + 1. This does not change an existing variable: it passes a new local value increased by one. Such recursive tricks are necessary to emulate increments in XSLT.
Template modes
Modes resemble parameters but are simpler and often cleaner. Several templates can match one pattern in different modes: one displays full data, another abbreviates. No modes are predefined; you define them. Attribute mode looks like this:
<xsl:template match="name" mode="langfassung">
...den vollen Namen ausgeben
</xsl:template>
<xsl:template match="name" mode="kurzfassung">
...den zweiten Vornamen auslassen
</xsl:template>To instantiate the correct template, add to element <xsl:apply-templates> an attribute mode:
<xsl:apply-templates select="bundespraesident/name" mode="langfassung"/>Without attribute mode, the processor seeks a matching template with no mode. Both shown templates have modes, so <xsl:apply-templates> must specify one or neither is instantiated.
A complete stylesheet appears in Template modes. It displays a president’s name in a table or list. Instead of passing a parameter to template bundespraesident, define two modes. Mode tabelle displays a table row, while mode liste displays an HTML list item.
Example: Template modes
<?xml version="1.0" encoding="ISO-8859-1"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="html"/>
<!-- ** zeigt, wie Template-Modi eingesetzt werden können -->
<xsl:template match="/">
<html>
<body>
<h2>Die Bundespräsidenten in einer HTML-Tabelle</h2>
<table border="1">
<tr>
<th>Nachname</th>
<th>Vorname</th>
</tr>
<xsl:apply-templates select="//bundespraesident" mode="tabelle"/>
</table>
<h2>Die Bundespräsidenten in einer unsortierten Liste</h2>
<ul>
<xsl:apply-templates select="//bundespraesident" mode="liste"/>
</ul>
</body>
</html>
</xsl:template>
<!-- ** Den Namen eines Bundespräsidenten als Tabellenzeile anzeigen -->
<xsl:template match="bundespraesident" mode="tabelle">
<tr>
<td>
<xsl:value-of select="name/nachname"/>
</td>
<td>
<xsl:value-of select="name/vorname"/>
</td>
</tr>
</xsl:template>
<!-- ** Den Namen eines Bundespräsidenten als Listenelement anzeigen -->
<xsl:template match="bundespraesident" mode="liste">
<li>
<xsl:value-of select="name/nachname"/>
<xsl:text>, </xsl:text>
<xsl:value-of select="name/vorname"/>
</li>
</xsl:template>
</xsl:stylesheet>Summary of <xsl:template> syntax
Listing all variations of <xsl:template> seems hard, but we have only encountered three attributes:
matchSpecifies the XML node to which the template applies.
nameGives a template an arbitrary name independent of XML data.
modeLike Java method overloading, allows several templates matching one pattern.
The only attribute not discussed in detail is priority, which resolves conflicting templates. The specification defines a precise procedure for multiple matching rules (see section 5.5 of the XSLT specification). For maintainability avoid overlapping template rules. Combining stylesheets may nevertheless cause conflicts; higher numeric priorities can resolve them. This table summarizes common forms of <xsl:template>.
Table: Common template syntax
Template example | Notes |
|---|---|
| Matches Bundespräsident nodes in source XML. |
|
|
| Defines a named template used with |
|
|
| Matches |
Copyright © 2002 O'Reilly Verlag GmbH & Co. KG
You may print the online version for your private use.
Otherwise, this chapter from “Java und XSLT” is subject to the same conditions as the bound edition. The work, including all its parts, is protected by copyright. All rights reserved, including reproduction, translation, microfilming, and storage and processing in electronic systems.
O’Reilly Verlag GmbH & Co. KG, Balthasarstraße 81, 50670 Köln, kommentar(at)oreilly.de