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>
The most straight-forward approach is to do a second if-test but with the condition inverted. This technique is shorter, easier on the eyes, and easier to get right than a choose-when-otherwise nested block:
Here's a real-world example of the technique being used in the style-sheet for a government website: http://w1.weather.gov/xml/current_obs/latest_ob.xsl
If statement is used for checking just one condition quickly. When you have multiple options, use
<xsl:choose>
as illustrated below:Also, you can use multiple
<xsl:when>
tags to expressIf .. Else If
orSwitch
patterns as illustrated below:The previous example would be equivalent to the pseudocode below:
You have to reimplement it using
<xsl:choose>
tag:If I may offer some suggestions (two years later but hopefully helpful to future readers):
h2
element.ooooooooooooo
text.if/then/else
construct if using XSLT 2.0.XSLT 1.0 Solution (also works with XSLT 2.0)
XSLT 2.0 Solution