Some tips & tricks for working with XSLT 2.0 (difference between XSLT 1.0 and XSLT 2.0)

Shortening your XSLT stylesheets

Please note: not all of the examples make absolute sense conceptually. They are mainly intended to demonstrate the technical purposes.

Avoid unnecessary <xsl:text>, <xsl:element>, and <xsl:attribute>

In many cases it is not necessary to use the XSLT elements <xsl:text>, <xsl:element>, and <xsl:attribute>. These often can be omitted as the following in most cases equally well working expressions demonstrate:

<xsl:element name="a">
    <xsl:attribute name="href">
        <xsl:text>http://www.example.com</xsl:text>
    </xsl:attribute>
    <xsl:attribute name="title">
        <xsl:text>Title of the link</xsl:text>
    </xsl:attribute>
</xsl:element>

<a href="http://www.example.com" title="Title of the link"/>

Attribute-value templates

Instead of using relatively complex statements for specifying attribute values (in output XML and also many XSLT nodes) it is possible to use XSLT's attribute-value templates. The following two statements will have the same effect:

<xsl:for-each select="distinct-values(//a/@href)">
    <link>
        <xsl:attribute name="href" select="."/>
        <xsl:attribute name="n" select="position()"/>
    </link>
</xsl:for-each>

<xsl:for-each select="distinct-values(//a/@href)">
    <link href="{.}" n="{position()}"/>
</xsl:for-each>

Attribute-value templates can also be used for specifying element names on <xsl:element name="{local-name()}"/> (you can use the whole XPath inventory), and there can be multiple attribute value templates in one attribute value, even combined with other textual content: <a href="{$baseurl}/index.php?query={$page}"/>

The 'select' attribute

Often it can be observed that people unnecessarily use complex and deeply nested constructions where it would be possible to use the 'select' attribute of the involved XSLT elements (e.g. <xsl:variable>, <xsl:attribute>). Accordingly the first statement can be rewritten by the second one:

<xsl:element name="{local-name()}">
    <xsl:variable name="href">
        <xsl:value-of select="."/>
    </xsl:variable>
    <xsl:attribute name="href">
        <xsl:value-of select="$href"/>
    </xsl:attribute>
</xsl:element>

<xsl:element name="{local-name()}">
    <xsl:variable name="href" select="."/>
    <xsl:attribute name="href" select="$href"/>
</xsl:element>

Use <xsl:for-each> if possible

From time to time you will see constructs which could be much shorter if <xsl:for-each> was used. For example when returning a sequence of attributes for a particular element it can be possible to summarize multiple <xsl:attribute> elements:

(... to be completed ...)

XPath functions instead of XSLT elements

(... to be completed ...)

Optimization of XSLT stylesheets

Keys: <xsl:key>

(... to be completed ...)

Comments in XPath

(... to be completed ...)