IMTheNachoMan
IMTheNachoMan

Reputation: 5811

How to use inline conditional (if then else) in XSLT?

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>

Upvotes: 4

Views: 4660

Answers (1)

michael.hor257k
michael.hor257k

Reputation: 116992

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>

Upvotes: 6

Related Questions