I would like to construct a sequence in XSLT 2 where each item of the sequence is individually conditionally included.
Something like this (where the test
expressions in reality are not this trivial):
<xsl:variable name="seq">
<xsl:if test="true()">
<xsl:value-of select="'foo'"/>
</xsl:if>
<xsl:if test="false()">
<xsl:value-of select="'bar'"/>
</xsl:if>
<xsl:if test="true()">
<xsl:value-of select="'baz'"/>
</xsl:if>
</xsl:variable>
In this case, I would want the value seq
variable to be the sequence ('foo', 'baz')
.
However, I seem to be missing something, because it's not working quite as expected. What I get returned for the above is a sequence with a single item 'foobar'
(i.e. the string concatenation of what was supposed to be all the individual items). If all the conditions are false, I get a sequence with a single item, but that item appears to be the empty string.
Note: Confusingly, I don't believe the <xsl:sequence>
item is necessarily related to the construction of a new sequence, and so is not relevant for this use case. It seems to be more about referencing existing items as opposed to copying them.
For context of the specific use case I am trying to solve now: I am trying to generate a sequence of strings representing HTML classes, each of which is included conditional on a different boolean expression. This will result in a list of variable length, between 0 and multiple strings. I am then planning to serialize this list to be a space separated string, as the HTML class
attribute expects, like so: string-join($classes, ' ')
.