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" ?>
<feeds>
<feed>
<title>Moreover Engineering News</title>
<url>http://p.moreover.com/cgi-local/page?index_engineering%20rss</url>
</feed>
<feed>
<title>SOSIG: Conferences in Anthropology</title>
<url>http://www.sosig.ac.uk/grapevine/Query?view=rss_confBySubject&sub_id=a</url>
</feed>
</feeds>

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"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:xalan="http://xml.apache.org/xalan"
exclude-result-prefixes="xalan">
<xsl:output method="html" />

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

<xsl:template match="feeds">
<html>
<head>
<title>Blah..</title>
</head>
<body>
<xsl:apply-templates select="feed" />
</body>
</html>
</xsl:template>

<xsl:template match="feed">
<xsl:variable xmlns:encoder="xalan://java.net.URLEncoder"
name="feedlink"
select="encoder:encode( string( url ) ) "
/>
<xsl:element name="a">
<xsl:attribute name="href">http://somewhere.edu/index.jsp?rss=
<xsl:value-of select="$feedlink" /></xsl:attribute>
<xsl:value-of select="title" />
</xsl:element>
<br />
</xsl:template>

</xsl:stylesheet>

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

0 comments: