Is it possible to do inline conditionals (if then else) in XSLT? Something like:
<div id="{if blah then blah else that}"></div>
Or a real use-case/example:
<div id="{if (@ID != '') then '@ID' else 'default'}"></div>
As mentioned in the comments, the if () then else
construct is only supported in XSLT/XPpath 2.0.
My own preference would be to use the verbose, but readable:
<xsl:template match="some-node">
<div>
<xsl:attribute name="ID">
<xsl:choose>
<xsl:when test="string(@ID)">
<xsl:value-of select="@ID"/>
</xsl:when>
<xsl:otherwise>default</xsl:otherwise>
</xsl:choose>
</xsl:attribute>
</div>
</xsl:template>
or perhaps a shorter:
<xsl:template match="some-node">
<div ID="{@ID}">
<xsl:if test="not(string(@ID))">
<xsl:attribute name="ID">default</xsl:attribute>
</xsl:if>
</div>
</xsl:template>
However, if you're into cryptic code, you may like:
<xsl:template match="some-node">
<div ID="{substring(concat('default', @ID), 1 + 7 * boolean(string(@ID)))}">
</div>
</xsl:template>
or:
<xsl:template match="some-node">
<div ID="{concat(@ID, substring('default', 1, 7 * not(string(@ID))))}">
</div>
</xsl:template>