Thursday, June 23, 2005

Using Java to perform URL encoding inside XSLT

I originally posted this on the JASIG wiki, I have found the following tip useful and it was also tricky to find so I thought I would reproduce it here also. It concerns how to make use of Java functionality inside XSL. I originally found this information on this site: Using Java in XSL.

Although not generally encouraged there are times when it is easier to let Java do some of the work rather than trying to write an elegant XSLT solution. The main disadvantage of using Java inside XSL is that the XSL created immediately becomes Java XSLT engine specific.

The following example is derived from a real problem when I wanted to pass an URL as a parameter to a newsfeed aggregator application through an external link from a portal. Without first being URL encoded the following two examples will not pass easily as parameters. Admittedly, I could URL encode these before I store them inside the XML but I think this makes the XML less human readable and rather pollutes the data for other uses.

<?xml version="1.0" ?>
<title>Moreover Engineering News</title>
<title>SOSIG: Conferences in Anthropology</title>

The following XSLT makes use of Java to perform the URL encoding process without the need to perform any pre/post processing outside of the XSL transformation itself. To perform this transformation you must use the Java Xalan transformation engine. My portal software, uPortal, uses Xalan by default but if you'd like to see the results of this transformation externally to a portal then see: Using Xalan from the Command Line alternatively if you are using Ant you could use the Xslt/Style Task (which itself uses Xalan).

<?xml version="1.0"?>
<xsl:stylesheet version="1.0"
<xsl:output method="html" />

<xsl:template match="/">
<xsl:apply-templates select="feeds" />

<xsl:template match="feeds">
<xsl:apply-templates select="feed" />

<xsl:template match="feed">
<xsl:variable xmlns:encoder="xalan://"
select="encoder:encode( string( url ) ) "
<xsl:element name="a">
<xsl:attribute name="href">
<xsl:value-of select="$feedlink" /></xsl:attribute>
<xsl:value-of select="title" />
<br />


Note: The line spacing in the above stylesheet was modified slightly for presentation purposes.