XSLT - if then else

If you try and implement if then else logic in XSLT in the same way that you would in a procedural language then you'll probably end up tying yourself in knots.
 
I had some XSLT to write today where I simply needed to check the existance of an attribute in the source document. If it existed then I would execute and addition against the value else I would substitue for a zero.
 
I had initially approached this with something like:
 
<xsl:choose>
  <xsl:when test="referenceToElemen/@attribute">
    <xsl:variable name="x" select = "referenceToElemen/@attribute">
  </xsl:when>
  <xsl:otherwise>
     <xsl:variable name="x">0</xsl:variable>
  </xsl:otherwise>
<xsl:choose>
 
<resultElement>
  <xsl:value-of select = "$x + 100"
</eesultElement>
 
Unfortunately this will not work because the scope of the vairable x is confined to the choose block.
 
The solution is to kind of turn the XSL variable declaration inside out, as shown below:
 
   <xsl:variable name ="PriceDiscount">
    <xsl:choose>
     <xsl:when test ="oms:OrderHeader/oms:OrderSummary/@Total">
      <xsl:value-of select ="oms:OrderHeader/oms:OrderSummary/@Total"/> 
     </xsl:when>
     <xsl:otherwise>0</xsl:otherwise>
    </xsl:choose>
   </xsl:variable>
   <xsl:variable name ="StaffDiscount">
    <xsl:choose>
     <xsl:when test ="oms:OrderHeader/oms:OrderSummary/@StaffDiscount">
      <xsl:value-of select ="oms:OrderHeader/oms:OrderSummary/@StaffDiscount"/>
     </xsl:when>
     <xsl:otherwise>0</xsl:otherwise>
    </xsl:choose>
   </xsl:variable>
   <t3m:introduced_by>
    <xsl:value-of select = "$PriceDiscount + $StaffDiscount"/>
   </t3m:introduced_by>

www.biztalkers.co.uk

Print | posted on Tuesday, November 18, 2008 1:53 PM

Feedback

# re: XSLT - if then else

left by dvd at 7/22/2010 8:32 AM Gravatar
first <xsl:choose> is wrong.

</xsl:choose> right

# re: XSLT - if then else

left by oxido at 8/6/2013 2:12 PM Gravatar
Rob Bowman,
tnx man, this is what i need.
Post A Comment
Title:
Name:
Email:
Comment:
Verification: