XSLT: Set multiple variables depending on condition
But what if I want to assign two variables depending on the same condition $someCondition?
I don't want to write the same xsl:choose statement again, because it is somewhat lengthy and computation intensive in the real example.
Assuming the values of the variables are not nodes, this code doesn't use any extension function to define them:
<xsl:variable name=vAllVars>
<xsl:choose>
<xsl:when test="$someCondition">
<xsl:value-of select="1|Fred"/>
<xsl:when>
<xsl:when test="$someCondition2">
<xsl:value-of select="12|ASDD"/>
<xsl:when>
<xsl:otherwise>
<xsl:value-of select="4711|PQR" />
</xsl:otherwise>
</xsl:choose>
</xsl:variable>
<xsl:variable name="foo" select="substring-before($vAllVars, '|')"/>
<xsl:variable name="bar" select="substring-after($vAllVars, '|')"/>
What you could is have your main variable return a list of elements; one for each variable you want to set
<xsl:variable name="all">
<xsl:choose>
<xsl:when test="a = 1">
<a>
<xsl:value-of select="1"/>
</a>
<b>
<xsl:value-of select="2"/>
</b>
</xsl:when>
<xsl:otherwise>
<a>
<xsl:value-of select="3"/>
</a>
<b>
<xsl:value-of select="4"/>
</b>
</xsl:otherwise>
</xsl:choose>
</xsl:variable>
Then, using the exslt function, you can convert this to a 'node set' which can then be used to set your individual variables
<xsl:variable name="a" select="exsl:node-set($all)/a"/>
<xsl:variable name="b" select="exsl:node-set($all)/b"/>
Don't forget you'll need to declare the namepsace for the exslt functions in the XSLT for this to work.