5

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

2 Answers 2

7

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Important to note that <xsl:param> must be declared at the top level of the stylesheet. If you declare it within a template, it will be considered a parameter to the template not to the whole stylesheet.
6

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" />

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.