xml – How to implement if-else statement in XSLT?

xml – How to implement if-else statement in XSLT?

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>

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>
   }

xml – How to implement if-else statement in XSLT?

If I may offer some suggestions (two years later but hopefully helpful to future readers):

  • Factor out the common h2 element.
  • Factor out the common ooooooooooooo text.
  • Be aware of new XPath 2.0 if/then/else construct if using XSLT 2.0.

XSLT 1.0 Solution (also works with XSLT 2.0)

<h2>
  <xsl:choose>
    <xsl:when test=$CreatedDate > $IDAppendedDate>m</xsl:when>
    <xsl:otherwise>d</xsl:otherwise>
  </xsl:choose>
  ooooooooooooo
</h2>

XSLT 2.0 Solution

<h2>
   <xsl:value-of select=if ($CreatedDate > $IDAppendedDate) then m else d/>
   ooooooooooooo
</h2>

Leave a Reply

Your email address will not be published.