Thursday, June 23, 2005

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.

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).