XSLT is not a programming language

Tags:

Well, at least not your typical procedual language, in the sense that it doesn’t have an equivalent of the variable, one that you can use to keep a running sum of element values.

Say you have:

 <Products>

<Product>
<Name>Gadget</Name>
<Price>$10.00</Price>
</Product>
<Product>
<Name>Gizmo</Name>
<Price>$7.50</Price>
</Product>

</Products>

And you want to know the sum of all item prices. You can do it, but you can’t throw things in a loop and do

<xsl:variable name="sum" select="$sum + Price" />  

You will get an error message that you can’t define the variable "sum" twice in an XSL template. In fact, variables in XSL are like "constants" or maybe "external read-only variables", whose value is set as you iterate through the XML elements, but you can’t change it after it’s assigned a value.

It turns our you can do it — you can’t change it’s value, but you can pass the value to a different template and change its value as you traverse. The solution is recursion. See Use recursion effectively in XSL. It’s like Lisp is alive again (maybe it never died in me).

For example, the  price-sum problem can be solved with a clever tail recursion algorithm:

<xsl:template name="priceSumTail">
<xsl:param name="productList"/>
<xsl:param name="result" select="0"/>
<xsl:choose>
<xsl:when test="$productList">
<xsl:call-template name="priceSumTail">
<xsl:with-param name="productList"
select="$productList[position() > 1]"/>
<xsl:with-param name="result"
select="$result +
number(substring-after($productList[1]/Price,’$'))"/>
</xsl:call-template>
</xsl:when>
<xsl:otherwise><xsl:value-of select="$result"/></xsl:otherwise>
</xsl:choose>
</xsl:template>

The reason I got into this is that I use XML eye movement experiments for stimulus control and data storage. I used to use Tcl/Tk or Python for XSLT, where I can easily mix XML with local variables. I would like to move to a more formalized workflow, where I keep a collection of XSL for standard tasks. Alas, it’s hard. But I got my code to work the way I liked.

XSLT is afterall not a programming language. Despite all the buzz around it, it’s not a general solution to data transformation. Programmers scream for an easy way to solve everyday tasks like this, while computer philosophors insist on the purity of the XSLT. I think I will go back to the mixed solution — binding XML with a programming language. In a long haul this is problematic, but XSLT doesn’t seem to be a solution either.

Leave a Reply

If the above Image does not contain text, use this secure code: DjWu9Q