XML technologies / XML / Perl & XML / Introduction to XML / Transformations
(Excerpt from “Perl & XML” by Erik T. Ray & Jason McIntosh)
Our final topic here is transformation. In XML, a transformation restructures a document or converts it to an entirely different form. The W3C recommends a special language called XML Stylesheet Language for Transformations (XSLT). This technology is incredibly useful and pleasantly simple.
Like an XML schema, an XSLT script is itself XML. It consists of templates or template rules. Each template instructs the conversion of a particular element into something else. The word template often describes how something should look, with marked places for insertions. XSLT rules work in exactly this way: they exemplify the final result and leave the XSLT processor to fill the gaps.
The following rudimentary transformation converts a simple DocBook XML document into HTML.
Example: An XSLT transformation script
<?xml version="1.0" encoding="iso-8859-1"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
<xsl:output method="html"/>
<!-- Regel für das Element "book" -->
<xsl:template match="book">
<html>
<head>
<title><xsl:value-of select="title"/></title>
</head>
<body>
<h1><xsl:value-of select="title"/></h1>
<h3>Inhaltsverzeichnis</h3>
<xsl:call-template name="inhaltsverzeichnis"/>
<xsl:apply-templates select="chapter"/>
</body>
</html>
</xsl:template>
<!-- Regel für "chapter" -->
<xsl:template match="chapter">
<xsl:apply-templates/>
</xsl:template>
<!-- Regel für den Titel eines Kapitels -->
<xsl:template match="chapter/title">
<h2>
<xsl:text>Kapitel </xsl:text>
<xsl:number count="chapter" level="any" format="1"/>
</h2>
<xsl:apply-templates/>
</xsl:template>
<!-- Regel für "para" (Absatz) -->
<xsl:template match="para">
<p><xsl:apply-templates/></p>
</xsl:template>
<!-- Regel mit Namen: "inhaltsverzeichnis" -->
<xsl:template name="toc">
<xsl:if test="count(chapter)>0">
<xsl:for-each select="chapter">
<xsl:text>Kapitel </xsl:text>
<xsl:value-of select="position( )"/>
<xsl:text>: </xsl:text>
<i><xsl:value-of select="title"/></i>
<br/>
</xsl:for-each>
</xsl:if>
</xsl:template>
</xsl:stylesheet>
First the processor reads the stylesheet and builds an internal rule table. It then examines the source document node by node. A node or tree node is an element, text fragment, processing instruction (PI), attribute or namespace declaration. For each, it finds the best-matching rule and applies it, outputting its template with substitutions in place of the node.
The next document lets you test the transformation.
Example: A transformable document
<?xml version="1.0" encoding="iso-8859-1"?>
<book>
<title>Ein diabolischer Verstand</title>
<chapter>
<title>Im Basar</title>
<para>Was für ein wunderbarer Tag das war! In den Ständen türmten sich die
verschiedensten importierten Güter: Datteln, Bananen, Trockenfrüchte,
feinste Seide und mehr als ich beschreiben kann. Als ich umherlief
und die Düfte von frischem Kaffe, gewürztem Wein und Kardamom genoß,
hätte ich beinahe einen unauffälligen, fahrbaren Stand übersehen, an
dem ein kleiner Mann Gehirne verkaufte.</para>
<para>Gehirne! Ja, menschliche Gehirne, grau und etwas aufgequollen, aber
gut erhalten und in großen Glasgläsern schwimmend, die mit einer
grünlichen Flüssigkeit gefüllt waren.</para>
<para>"Möchten Sie gerne ein Gehirn versuchen, mein Herr?" fragte er. "Sie
sind heute sehr preisgünstig. Hier ist das von Heisenberg, nur zwei
Euro! Oder bevorzugen Sie Kant? Falls Sie es etwas pompöser mögen,
wäre Ihnen vielleicht der große Kurfürst recht?"</para>
<para>Ich fuhr entgeistert zurück...</para>
</chapter>
</book>Let us walk through it step by step.
The first element is
<book>. The first rule matches best, as it explicitly targets “book.” Its template outputs tags such as<html>,<head>or<title>. These tags count as data because they lack the prefixxsl:.At the XSLT instruction
<xsl:value-ofselect="title"/>, the processor looks for a<title>element that is a child of the current<book>element. Once found, it determines its value, simply its entire textual content. The template outputs that text inside a<title>element.Processing continues until the instruction
<xsl:call-templatename="toc"/>. At the stylesheet’s end is a rule beginning with<xsl:template name="inhaltsverzeichnis">. This is a named template, acting as a function call. It builds a table of contents and returns the generated text to the calling rule for output.Inside it is an element named
<xsl:if test="count(chapter)>0">, a conditional instruction testing whether the current element, still<book>, contains at least one<chapter>element. The test succeeds, so processing enters the conditional body.The instruction
<xsl:for-each select="chapter">makes the processor find all<chapter>children of the current element. Each in turn temporarily becomes current, and the content of the<xsl:for-each>element is processed. This is analogous to aforeach( )-loop in Perl. The instruction<xsl:value-of select="position( )"/>returns the numeric position of the current<chapter>element, yielding “Kapitel 1,” “Kapitel 2” and so forth.The template named “inhaltsverzeichnis” returns its text to the calling rule and processing continues to the element
<xsl:apply-templates select="chapter"/>. Used without attributes, this<xsl:apply-templates>means visiting the current element’s children, making each current in turn. Here the attributeselect="chapter"is present, so only children of type<chapter>are visited. After these and their ancestors produce text, it is output and the remainder of the rule runs to completion.The processor takes the first
<chapter>element and searches for a rule, finding only<xsl:apply-templates/>. The remaining treatment of<title>and<para>is now obvious.
XSLT is rich, yet often leaves something to be desired. Large documents can be slow because processors usually build an internal representation before working. Its syntax cleverly uses XML, but is less expressive and easy to use than Perl. Many later examples could use XSL instead of Perl. Decide for yourself between XSLT’s simplicity and Perl’s power.
That ends our quick XML tour. Next we establish Perl XML processing basics through parsers written in Perl and simple document generation. You should now understand XML’s uses and benefits and recognize document components. If still unsure, consider reading an XML tutorial first.
Copyright © 2003 O'Reilly Verlag GmbH & Co. KG
You may print the online version for your private use.
Otherwise, this chapter from “Perl & XML” 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
back to top