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:when test="referenceToElemen/@attribute">
    <xsl:variable name="x" select = "referenceToElemen/@attribute">
     <xsl:variable name="x">0</xsl:variable>
  <xsl:value-of select = "$x + 100"
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:when test ="oms:OrderHeader/oms:OrderSummary/@Total">
      <xsl:value-of select ="oms:OrderHeader/oms:OrderSummary/@Total"/> 
   <xsl:variable name ="StaffDiscount">
     <xsl:when test ="oms:OrderHeader/oms:OrderSummary/@StaffDiscount">
      <xsl:value-of select ="oms:OrderHeader/oms:OrderSummary/@StaffDiscount"/>
    <xsl:value-of select = "$PriceDiscount + $StaffDiscount"/>


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


# 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