Not yet rated

Problem

You're using XSLT to display the contents of an RSS feed or XML document, but want to limit the number of characters displayed by an element.

Solution

Use the XSLT substring() function, which takes three arguments: the name of the XML element, the starting position counting from 1, and the number of characters to be displayed.

Detailed explanation

The following XSLT code displays the title and description elements of an RSS feed:

<xsl:for-each select="rss/channel/item">
    <h3><a href="{link}"><xsl:value-of select="title"/></a></h3>
    <p><xsl:value-of select="description" disable-output-escaping="yes"/></p>
</xsl:for-each>

To limit the length of the description element to the first 300 characters, amend the third line in the preceding code sample like this:

<p><xsl:value-of select="substring(description, 1, 300)" disable-output-escaping="yes"/>...</p>

Note that the quotation marks are removed from the element name ( description), and wrapped around the substring() function. Unlike JavaScript and PHP, the substring() function starts counting from 1, not 0. Otherwise, it works the same way.

Adding an ellipsis after the <xsl:value-of> tag indicates that the content has been abbreviated. If you're not using HTML elements in your XSLT fragment, you need to wrap the ellipsis in <xsl:text> tags like this:

<xsl:text>...</xsl:text>

+
This work is licensed under a Creative Commons Attribution-Noncommercial-Share Alike 3.0 Unported License. Permissions beyond the scope of this license, pertaining to the examples of code included within this work are available at Adobe.

Report abuse

Related recipes