I need to change the order in which my for-each is executed only if some conditions are met.
Here is what my XML looks like :
<OptionList>
<Option name="My First Option" />
<Option name="My Second Option" />
</OptionList>
However, in some case, my XML can be like this :
<OptionList>
<Option />
<Option name="My Second Option" />
</OptionList>
In my XSL, I’m doing a for-each like this :
<xsl:for-each select="//OptionList/Option">
{...}
</xsl:for-each>
I know I can change orders of Option nodes using this line in my for-each :
<xsl:sort select="position()" data-type="number" order="descending" />
The problem is that I want my order to be descending only when my first Option node is empty and doesn’t have the name attribute. Otherwise, I want to keep the default ascending order.
Any input on how I can acheive that? So far, everything I tried ended up with “Variable out of scope” or invalid use of xpath functions.
You can use a hack to change the sort order based on a condition:
The hack is that
number((true())returns 1 andnumber(false())returns 0. As a consequence, the expressionevaluates to
1if the firstoptionelement has anameattribute and to-1otherwise. This is used as a factor to reverse the sort order.