Using Java in XSL
I have found the following tip useful and it was also tricky to find so I thought I would reproduce it here for other portal developers benefit. 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.
Using Java to perform URL encoding inside XSLT
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 the 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, uPortal uses Xalan by default but if you'd like to see the results of this transformation externally to uPortal then see: Using Xalan from the Command Line
<?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>
Other userful sources of XSLT reference information:
Dave Pawson's XSLT Questions and Answers
Zvon.org
Xalan Extensions Library
EXSLT (Xalan incorporates most, if not all, of these extentions)
Jeni Tennison's XSLT Pages
Author: Mark McLaren, Portal Development Team, University of Bristol, UK