Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Execute XSLT Transform from Java with parameter

Tags:

java

xslt

I am executing an XSLT transform from within my java web application with no problems, as follows:

Transformer transformer = TransformerFactory.newInstance().newTransformer(xslSource);
transformer.transform(xmlInput, xmlOutput);

In my XSLT transform I am now adding a call to the document() function to load the response from a RESTful web service:

<!-- do stuff -->
<xsl:variable name="url">
   http://server/service?id=<xsl:value-of select="@id"/>
</xsl:variable>
<xsl:call-template name="doMoreStuff">
   <xsl:with-param name="param1" select="document($url)/foo"/>
</xsl:call-template>

Ok cool, no problem. But now, I want to read the base URL from a utils class in java and pass it in to the stylesheet.

//java
String baseUrl = myUtils.getBaseUrl();

<!-- xslt -->
<xsl:variable name="url">
   <xsl:value-of select="$baseUrl"/>
   <xsl:text>/service?id=</xsl:text>
   <xsl:value-of select="@id"/>
</xsl:variable>

Any suggestion on how to do this? My Java utils class loads the value from a myApp.properties file on the classpath, but I'm not sure I can utilize that from XSLT...

like image 614
schmimd04 Avatar asked Oct 06 '11 22:10

schmimd04


2 Answers

Declare an xsl:param in your stylesheet, so that the baseUrl value can be passed at invocation time:

<xsl:param name="baseUrl" />

Set the parameter on the Transformer object:

Transformer transformer = TransformerFactory.newInstance().newTransformer(xslSource);
transformer.setParameter('baseUrl', myUtils.getBaseUrl());
transformer.transform(xmlInput, xmlOutput);

If you are using XSLT 2.0, then you may consider using the resolve-uri() function when you are constructing the url variable value:

<xsl:variable name="url" 
              select="resolve-uri(concat('/service?id=', @id), $baseUrl)" />

resolve-uri() can help compensate for trailing slashes, hashtags, and other things in the baseUrl that might otherwise result an invalid URL to be constructed by simply concatenating the $baseUrl with the fragment and @id.

like image 123
Mads Hansen Avatar answered Oct 04 '22 19:10

Mads Hansen


Call setParameter on your Transformer instance, with the name and value of your parameter. Then inside your XSLT document declare the parameter using <xsl:param name="yourParamName" /> and you can then use it in your XSLT for example this way: <xsl:value-of select="$yourParamName" />

like image 40
Clafou Avatar answered Oct 04 '22 20:10

Clafou