Modifing XML values in XSLT documents

Posted by William on Nov 5, 2010

Ever wondered how to perform manipulations of XML values in an XSLT document?

For example, if you were consuming an RSS feed which had description values greater than 500 characters in length, but you only wanted to display the first 50 characters before leading the user through to the full post.

The solution is XPath functions. Much like any general level scripting language such as VBScript or PHP, XPath makes available a range of functions to help you achieve basic type manipulation and querying.

Lets elaborate on the RSS example. Imagine you were consuming a feed which looked similar to the following (trimmed for simplication).

<?xml version="1.0" encoding="UTF-8"?>
<rss>
<channel>
...
<item>
<title>Modifing XML values in XSLT documents</title>
<link>http://feedproxy.google.com/~r/wduffy/~3/WkFIKaXB1lI/</link>
<description><![CDATA[Ever wondered how to perform manipulations of XML values in an XSLT document?
For example, if you were consuming an RSS feed which had description values greater than 500 characters in length, but you only wanted to display the first 50 characters before leading the user through to the full post.
The solution is XPath functions. Much [...]]]></description>
</item>
...
</channel>
</rss>

You wish to render a short preview of the latest blog post in a format similar to the following example, perhaps on a website’s “latest blog posts” widget.

<strong>Modifing XML values in XSLT documents</strong><br />
Ever wondered how to perform manipulations of XML...<br />
<a href="http://feedproxy.google.com/~r/wduffy/~3/WkFIKaXB1lI/">Read the full post!</a>

The XSLT document would be formatted as below. Notice the call to substring() when requesting the value of the xml document’s description field. This function extracts a new value from the XML documents description value starting at position 0, and finishing at position 50.

<?xml version="1.0" encoding="ISO-8859-1"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
 <xsl:template match="/">
  <xsl:for-each select="/rss/channel/item">
   <xsl:if test="position() &lt;= 1">
 
       <strong><xsl:value-of select="title" /></strong><br />
       <xsl:value-of select="substring(description, 0, 50)" disable-output-escaping="yes" />...<br />
 
       <a>
        <xsl:attribute name="href"><xsl:value-of select="link"/></xsl:attribute>
        Read the full story
       </a>
 
   </xsl:if>
  </xsl:for-each>
 </xsl:template>
</xsl:stylesheet>

Having this level of control over the transformation process allows for a huge range of possibilities and doesn’t only apply to basic string manipulation. Functions exist for date types, numeric types, boolean types and nodes. For more details on exactly what is available check out this excellent overview of XPath, XQuery, and XSLT Functions on W3 Schools.