RE: [xsl] Calling java in xsl.

Subject: RE: [xsl] Calling java in xsl.
From: "Michael Kay" <mike@xxxxxxxxxxxx>
Date: Tue, 14 Feb 2006 08:38:24 -0000
>     <xsl:variable name="todayPlus" select="cal:add($today, 6, 
> $offset)"/>
> Now, what bothers me about this is the variable todayPlus 
> which serves 
> no purpose other than giving us an opportunity to call add. 
> How can we 
> avoid this useless call?

You're right to be bothered: if Saxon were executing this, it would decide
that the variable served no useful purpose, and wouldn't evaluate it. Even
if it were evaluated, the order of evaluation is not guaranteed.

Of course in XSLT 2.0 you can do this calculation within the language, so
the problem wouldn't arise. But if you do need to call extension functions
for their side-effects rather than their result, my usual advice is to use a
construct where the result appears to be used. In many cases the Java method
returns void, so (in Saxon at any rate) you can do

<xsl:sequence select="cal:add($today, 6, $offset)"/>

(Although Saxon knows at compile time that the method returns void, which
maps to an XPath empty sequence, it carefully refrains from taking advantage
of this knowledge.)

or in 1.0, substitute xsl:value-of. If the method doesn't return void, and
you need to call it and then discard the result, you can use something like

<xsl:value-of select="substring(cal:add($today, 6, $offset), 1, 0))"/>

- which relies, of course, on your optimizer not recognizing this and
treating it specially. If you want to be absolutely sure, replace the "0"
with $zero where $zero is a stylesheet parameter.

Michael Kay 

Current Thread