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: Carrying variable value outside for-each loop


Hi Sri,

>   I have the following xsl structure.
>   <xsl:for-each>
>      <xsl:if <condition>>
>         <!--set a variable value to "true"-->
>      </xsl:if>
>   </xsl:for-each>
>   <!--would like to use the variable value here-->
>
> But unfortunately, the variable value becomes empty outside the
> for-each scope. So what should I do to have the variable retain its
> acquired value. Can I use global variable, if so how?

It's more straightforward to find an XSLT solution to this if you
think about the problem in a different way. You want to have the
variable hold the value true if one of the nodes that you're selecting
with the xsl:for-each fulfils the condition that you use in the
xsl:if.

Most of the time you can do this with a single XPath instead. Take the
nodes that you're selecting with the xsl:for-each, and filter them
using a predicate that contains the test that you're using with the
xsl:if. If the resulting node set contains any nodes, then you want
the value true, which you can get by converting the node set to a
boolean with the boolean() function.

For example, if you're trying:

  <xsl:for-each select="foo">
    <xsl:if test="bar = 'baz'">
      <xsl:variable name="anyFoo" select="true()" />
    </xsl:if>
  </xsl:for-each>

then you should do:

  <xsl:variable name="anyFoo" select="boolean(foo[bar = 'baz'])" />

This won't work if you're using the current() function in the xsl:if
test, and might not be practical if the test is based on complex
calculations that you use variables to help with. In that case, you
just need to move the setting of the variable outside the
xsl:for-each, as so:

  <xsl:variable name="anyFoo">
    <xsl:for-each select="foo">
      <xsl:if test="bar = 'baz'">true</xsl:if>
    </xsl:for-each>
  </xsl:variable>

I hope that helps,

Jeni

---
Jeni Tennison
http://www.jenitennison.com/


 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]