Calling Objects from XSLT

John Ellis

I have found something cool about xslt that could possibly benefit those developing osp portfolio templates or other osp pieces that require xslt. it is the ability to call any arbitrary static java method from within the xslt transformation. it works like this:

create a class with a static method that uses "org.w3c.dom.Node" or "java.lang.String" objects (I'm sure others will work, but i've tried those so far). in this class, you can return a Node, a NodeList, a String or probably any other object that can equate to a string. this class then needs to be accessible from the webapp where the transform is happening. i'm envisioning a library of "helper" methods for particular purposes.

in the xslt, declare the class as a namespace in your "stylesheet" element with the full package name of the class with static methods:

<xsl:stylesheet version="2.0"
xmlns="http://www.w3.org/1999/xhtml"
xmlns:sakaifn="org.sakaiproject.metaobj.utils.xml.XsltFunctions"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:xhtml="http://www.w3.org/1999/xhtml"
xmlns:osp="http://www.osportfolio.org/OspML"
xmlns:xs="http://www.w3.org/2001/XMLSchema">

from there, you can use any method in the "XsltFunctions" class where you would normally use x-path methods:

<xsl:value-of select="sakaifn:getRichTextScript($name, .)" disable- output-escaping="yes"/>

where the signature of "getRichTextScript" is:

public static String getRichTextScript(String textBoxId, Node  schemaElement)

so far, it seems pretty good at mutating parameter types to the signature of the method. if the method calls for a string, and you pass a node, it will typically pass the text content of the node. if it calls for a NodeList and you pass a single node, it will create a NodeList with one item in it, etc.

i'm not sure, yet, if it supports the arbitrary number of parameters feature that java 5 has. i am going to be trying that soon so that i can implement a "MessageFormat" type method for i18n purposes.

i think it is probably important not to get too crazy here. one of the cool things about using xslt is that it can be previewed in tools like xml spy. the more of these types of methods we use, the further away we get from being able to effectively do that. if we use it for things we don't want rendered in xml spy anyway, we should be ok.

Enter labels to add to this page:
Please wait 
Looking for a label? Just start typing.