Advanced XSL Transformation Instructions

xsl:sort Used to sort elements. It is used within xsl:for-each and xsl:apply-templates. It sorts the elements selected by the select attribute of xsl:for-each or xsl:apply-templates. Its select attribute specifies the key to be used for sorting. Example:

<UL> <xsl:for-each select="author"> <xsl:sort select="last"/> <LI> <xsl:value-of select="last"/>, <xsl:value-of select="first"/>. </LI> </xsl:for-each> </UL>

The example lists last name, a comma, first name, and a period, as an HTML bullet list, sorted by last name. Something similar may be accomplished as follows:

<xsl:template match="authorlist"> <UL> <xsl:apply-templates select="author"> <xsl:sort select="last"/> </xsl:apply-templates> </UL> </xsl:template> <xsl:template match="author"> <LI> <xsl:value-of select="last"/>, <xsl:value-of select="first"/>. </LI> </xsl:template>

Lab 4E (advanced/optional)

xsl:for-each Applies a template to each occurrence of an element. For example:

<xsl:for-each select="writers/author"> <LI><xsl:value-of select="."/></LI> </xsl:for-each>

loops through each author element within all writers elements and outputs its contents as HTML list items.

Lab 4F (advanced/optional)

{ } Generates text for use in an attribute in the result tree. For example, given this XML data as input:

<picture> <href>pretty.jpg</href> <size width="400"/> </picture>

We could use the following XSL code to produce an HTML IMG element:

<xsl:template match="picture"> <IMG SRC="{href}" WIDTH="{size/@width}"/> </xsl:template>

This would produce the following element in the result tree:

<IMG SRC="pretty.jpg" WIDTH="400">

Lab 4G (advanced/optional)

xsl:variable For temporarily storing local data. In this example, a large string is assembled by concatenating several small ones into a variable. XML input data:

<keywords> <keyword>literature</keyword> <keyword>Latin America</keyword> <keyword>modern classics</keyword> </keywords>

The following XSL code produces a meta tag for search engines:

<xsl:variable name="keywordlist"> <xsl:apply-templates select="keywords" /> </xsl:variable> <meta name="keywords" content="{$keywordlist}" /> <xsl:template match="keywords"> <xsl:apply-templates select="keyword" /> </xsl:template> <xsl:template match="keyword"> <xsl:apply-templates /> <xsl:text>, </xsl:text> </xsl:template>

Output:

<meta name="keywords" content="literature, Latin America, modern classics, " />