Execute XSLT Transform from Java with parameter
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...
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
.
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" />
精彩评论