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:

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

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:when test="$condition = 0">
    <xsl:copy-of select="/data/item[@type = 10][position() = 1]" />
    <xsl:copy-of select="/data/item[@type = 20]" />

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

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


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: