Tuesday, July 14, 2009

Conditionally set an xsl:variable

How to select content out of the current XML-payload
into an <xsl:variable />, based on some condition(s).

The input-XML looks like this:

<data>
  <item value="Foo" type="10" />
  <item value="Bar" type="10" />
  <item value="ALFKI" type="20" />
  <item value="Baz" type="10" />
</data>

Depending on the parameter 'condition' of the following template,
a different query is executed and it's results are stored in variable 'selection'.

<xsl:template name="makeASelection">
  <xsl:param name="condition" />

  <xsl:variable name="selection">
  <xsl:choose>
    <xsl:when test="$condition = 0">
    <xsl:copy-of select="/data/item[@type = 10][position() = 1]" />
    </xsl:when>
    <xsl:otherwise>
    <xsl:copy-of select="/data/item[@type = 20]" />
    </xsl:otherwise>
  </xsl:choose>
  </xsl:variable>

  <xsl:variable name="selectionSet" select="msxsl:node-set($selection)" />

  <xsl:foreach select="$selectionSet/*">
    ...
  </xsl:foreach>

</xsl:template>


The take-away is to
1. put content in the variable ('selection') using <xsl:copy-of ... />
2. use msxsl:node-set to address the content in this variable
3. use /* when iterating over the nodeset-variable

No comments: