I’m working on an application which uses apache cocoon to convert an XML to PDF, and I’m redesigning the XSL that handles the input XML.
Currently in the XSL, we have code like this
<xsl:variable name="variable1">
<xsl:choose>
<xsl:when test="$testVariable ='1'">
<xsl:value-of select="'A'"/>
</xsl:when>
<xsl:when test="$testVariable ='1'">
<xsl:value-of select="'B'"/>
</xsl:when>
</xsl:choose>
</xsl:variable>
<xsl:variable name="variable2">
<xsl:choose>
<xsl:when test="$testVariable ='1'">
<xsl:value-of select="'X'"/>
</xsl:when>
<xsl:when test="$testVariable ='1'">
<xsl:value-of select="'Y'"/>
</xsl:when>
</xsl:choose>
</xsl:variable>
Will it work if I change it to this?
<xsl:variable name="variable1"/>
<xsl:variable name="variable2"/>
<xsl:choose>
<xsl:when test="$testVariable ='1'">
<xsl:variable name="variable1" select="'A'">
<xsl:variable name="variable2" select="'X'">
</xsl:when>
<xsl:when test="$testVariable ='2'">
<xsl:variable name="variable1" select="'B'">
<xsl:variable name="variable2" select="'Y'">
</xsl:when>
</xsl:choose>
No, unlike in a lot of other languages, XSLT variables cannot change their values after they are created. You can however, avoid extraneous code with a technique like this:
In fact, once you’ve got the
valuesvariable, you may not even need separatevariable1andvariable2variables. You could just use$values/@v1and$values/@v2instead.