This is the mail archive of the xsl-list@mulberrytech.com mailing list .


Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]

Re: Conditional variable assignment


| CONCEPTUALLY I want to say:
| 
| <xsl:variable name="style"
|     <xsl:if test="@style_override">
|             style = @style_override
|    </xsl:if>
|     <xsl:if test="not(@style_override)">
|             style =$default_style
|    </xsl:if>


Using <xsl:choose> to conditionally assign a variable, your first 
instinct would likely compel you to do the following:

<!--Variable n does not exist here since it's not been set yet -->
<xsl:choose>
  <xsl:when test="b > 45">
    <xsl:variable name="n" select="15"/>
    <!--Variable n has value "15"inside this <xsl:when>-->
  </xsl:when>
  <xsl:otherwise>
    <xsl:variable name="n" select="20"/>
    <!--Variable n has value "20"inside this <xsl:otherwise>-->
  </xsl:otherwise>
</xsl:choose>
<!--Variable n does not exist here since it's out of scope -->

While this is completely legal XSLT, it is probably not what you
intended. It creates a variable n with value 15 that is scoped to the
part of the stylesheet tree nested inside the <xsl:when> element where
the variable is set. So the variable n comes into existence, but no
other element nested within the <xsl:when> element makes use of its
value. It dies a silent death, unnoticed. Then within the
<xsl:otherwise> a new variable -- coincidentally, also named n -- is
bound to the value 20; however, it meets a similar fate. If the
developer tries to reference the value of n outside of this
<xsl:choose>, it will be undefined because of the scoping rules for
XSLT variables.  Rather than thinking of conditionally assigning a
variable, in XSLT you need to think instead of assigning a variable a
conditional value. An example will make things clear. Here is the
right way to assign the variable n to the conditional value 15 or 20:

<xsl:variable name="n">
  <!--Conditionally instantiate a value to be assigned to the variable -->
  <xsl:choose>
    <xsl:when test="b > 45">
      <xsl:value-of select="15"/><!-- We either instantiate a "15" -->
    </xsl:when>
    <xsl:otherwise>
      <xsl:value-of select="20"/><!-- ...or a "20" -->
    </xsl:otherwise>
  </xsl:choose>
</xsl:variable>
<!--Value of n is visible here and will be either 15 or 20 -->

______________________________________________________________
Steve Muench, Lead XML Evangelist & Consulting Product Manager
BC4J & XSQL Servlet Development Teams, Oracle Rep to XSL WG
Author "Building Oracle XML Applications", O'Reilly
http://www.oreilly.com/catalog/orxmlapp/



 XSL-List info and archive:  http://www.mulberrytech.com/xsl/xsl-list

Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]