How to implement if-else statement in XSLT?
I am trying to implement an if -else statement in XSLT but my code just doesn't parse. Does anyone have any ideas?
<xsl:variable name="CreatedDate" select="@createDate"/>
<xsl:variable name="IDAppendedDate" select="2012-01-01" />
<b>date: <xsl:value-of select="$CreatedDate"/></b>
<xsl:if test="$CreatedDate > $IDAppendedDate">
<h2> mooooooooooooo </h2>
</xsl:if>
<xsl:else>
<h2> dooooooooooooo </h2>
</xsl:else>
Solution 1:
You have to reimplement it using <xsl:choose>
tag:
<xsl:choose>
<xsl:when test="$CreatedDate > $IDAppendedDate">
<h2> mooooooooooooo </h2>
</xsl:when>
<xsl:otherwise>
<h2> dooooooooooooo </h2>
</xsl:otherwise>
</xsl:choose>
Solution 2:
If statement is used for checking just one condition quickly.
When you have multiple options, use <xsl:choose>
as illustrated below:
<xsl:choose>
<xsl:when test="$CreatedDate > $IDAppendedDate">
<h2>mooooooooooooo</h2>
</xsl:when>
<xsl:otherwise>
<h2>dooooooooooooo</h2>
</xsl:otherwise>
</xsl:choose>
Also, you can use multiple <xsl:when>
tags to express If .. Else If
or Switch
patterns as illustrated below:
<xsl:choose>
<xsl:when test="$CreatedDate > $IDAppendedDate">
<h2>mooooooooooooo</h2>
</xsl:when>
<xsl:when test="$CreatedDate = $IDAppendedDate">
<h2>booooooooooooo</h2>
</xsl:when>
<xsl:otherwise>
<h2>dooooooooooooo</h2>
</xsl:otherwise>
</xsl:choose>
The previous example would be equivalent to the pseudocode below:
if ($CreatedDate > $IDAppendedDate)
{
output: <h2>mooooooooooooo</h2>
}
else if ($CreatedDate = $IDAppendedDate)
{
output: <h2>booooooooooooo</h2>
}
else
{
output: <h2>dooooooooooooo</h2>
}