I have to create an XSL variable with a choose in it. Like the following:
That's what <xsl:text>
is for:
<xsl:variable name="grid_position">
<xsl:choose>
<xsl:when test="count(/Element) >= 1">
<xsl:text>inside</xsl:text>
</xsl:when>
<xsl:otherwise>
<xsl:text>outside</xsl:text>
</xsl:otherwise>
</xsl:choose>
</xsl:variable>
It allows you to structure your code and control whitespace at the same time.
In fact, you should stay clear of text nodes in XSL that are not wrapped in <xsl:text>
to avoid these kinds of bugs in the future, too (i.e. when code gets re-formatted or re-factored later).
For simple cases, like in your sample, doing what Jim Garrison suggests is also an option.
As an aside, testing for the existence of an element with count()
is superfluous. Selecting it is enough, since the empty node-set evaluates to false
.
<xsl:when test="/Element">
Just use:
<xsl:variable name="grid_position" select=
"concat(substring('inside', 1 div boolean(/Element)),
substring('outside', 1 div not(/Element))
)
"/>
The strategies in the other answers are good, in fact preferable to this one when feasible. But there are times when you don't have control over (or it's harder to control) what's in the variable. In those cases, you can strip away the surrounding space when you're testing the variable:
Instead of
<xsl:if test="$grid_position = 'inside'">
use
<xsl:if test="normalize-space($grid_position) = 'inside'">
normalize-space()
strips the leading and trailing whitespace, and collapses other repeating white spaces to single ones.
The simplest way is not to put the whitespace there in the first place:
<xsl:variable name="grid_position">
<xsl:choose>
<xsl:when test="count(/Element) >= 1">inside</xsl:when>
<xsl:otherwise>outside</xsl:otherwise>
</xsl:choose>
</xsl:variable>