Skip to content

Invoking Java from XSLT using saxonb9 1 0 8j

Tim L edited this page Oct 14, 2013 · 16 revisions

How to instantiate and call a Java object from within XSLT using Saxon?

(Note: saxonb9-1-0-8j is the last version before Michael Kay removed Java extension support.)

Step 1: Add an XML namespace with the Java path to the class you want to instantiate:

<xsl:transform version="2.0" 
               xmlns:hash="java:java.util.HashMap"

Step 2: Add an XSL variable, calling the Java class constructor via the XML namespace:

<xsl:variable name="label-cache" select="hash:new()"/>

Step 3: Pass the Java method the Java instance before the "normal" arguments (c.f. label_cache.containsKey('my_key')):

<xsl:variable name="is-cached" select="hash:containsKey($label-cache,'my_key')"/>

Step 4: Make sure Saxon actually invokes the put method; it's optimizer might ignore it if it would have no affect:

<xsl:value-of select="if(hash:put($label-cache,$labeled,$label)) then '' else hash:get($label-cache,$labeled)"/>

What is next