XML technologies / XSLT / Introduction to XSLT 2.0 / XSLT and XPath – getting started / A comparison: expression versus instruction / Comparing the two variants
(Excerpt from “XSLT 2.0 & XPath 2.0” by Frank Bongers, chapter 1.)
Comparing the two variants of the template rule makes the superiority of XSLT 2.0 and XPath 2.0 over the previous version seem obvious. Here is the backward-compatible variant:
<!-- alte Methode (auch mit XSLT 1.0 zu verarbeiten): -->
<xsl:template match="anschrift">
<xsl:value-of select="strasse"/>
<xsl:text> </xsl:text>
<xsl:value-of select="nr"/>
<xsl:text>, </xsl:text>
<xsl:value-of select="plz"/>
<xsl:text> </xsl:text>
<xsl:value-of select="ort"/>
</xsl:template>
Code example: kap01/1.16.11/adressen.xsl (excerpt).
A functionally equivalent template rule can be expressed much more concisely with XPath 2.0, but cannot be processed by an older processor:
<!-- neue Methode (nur in XSLT 2.0 einsetzbar): -->
<xsl:template match="anschrift">
<xsl:value-of select="(strasse, nr, ',', plz, ort)"/>
</xsl:template>
Code example: kap01/1.16.11/adressen-xpath2.xsl (excerpt).
Which approach seems more intuitive is a matter of taste. In the second case, XPath actually does the work. An XPath expression can be used as a functional equivalent to XSLT instructions, as we will see repeatedly. Even literals implemented the old way as text literals or in xsl:text are quietly passed as part of the XPath sequence. This reduces the required source code by a factor of four here. (Note: The average saving is unlikely to be this large. Around 30% less source code may be more realistic when replacing XSLT 1.0/XPath 1.0 constructions with their equivalents in XSLT 2.0 or XPath 2.0.)
Replacing XSLT instructions with XPath expressions comes at a price. We have already mentioned the difficulty of modifying a result obtained solely through XPath. For example, in the first template variant, additional elements can simply be inserted as Literal Result Elements. Since an XSLT stylesheet is essentially a normal XML document, XSLT itself can perform this insertion: this is the advantage of the more verbose, XSLT-oriented approach.
An XPath expression, by contrast, has the nature of a string. It too can be processed and modified, including with XSLT, but this takes substantially more effort. In return, stylesheets using more complex XPath expressions can be much more compact.
Copyright © Galileo Press, Bonn 2008
You may print the online version for your private use.
Otherwise, this chapter from “XSLT 2.0 & XPath 2.0 ― Das umfassende Handbuch” 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.
Galileo Press, Rheinwerkallee 4, 53227 Bonn