1

Im new to xlst and am confused as to whether there is any way to store a value and change it later, for example incrementing a variable in a loop. variables in XSLT are immutable. Kindly help

For example I want to do something like this:

 <xsl:for-each-group select="Values/value" group-by="xxx">
        <xsl:variable name="cur" select="0" />
         <xsl:for-each select="current-group()">
           <xsl:if test="$cur=0 and flag !='0'">
            <xsl:variable name="cur" select="$cur + 1" />
            <!-- DO SOMETHING -->
        </xsl:if>
        </xsl:for-each>
     </xsl:for-each-group>

flag node has 4 non zero record but need to display only one node. kindly help me to execute first occurrence of non zero record

XML:

<aa>....

<cc>
<Values>
<value>
<part>
<flag>0<flag>
<text></text>
...
...
</part>
<part>
<flag>0<flag>
<text></text>
...
...
</part>
<part>
<flag>1<flag>
<text></text>
...
...
</part>
</Value>

<value>
<part>
<flag>1<flag>
<text></text>
...
...
</part>
<part>
<flag>0<flag>
<text></text>
...
...
</part>
<part>
<flag>1<flag>
<text></text>
...
...
</part>
</Value>
</values>
</cc>
</aa>
Dev
  • 17
  • 4
  • 2
    Please post a [mcve] showing input and expected output. – michael.hor257k Jan 05 '22 at 18:20
  • Still no expected output. – michael.hor257k Jan 06 '22 at 12:18
  • 1
    Consider to indent your samples. Also, if you group by `xxx`, show the `xxx` element. Then explain which output you want to create or at least which condition you want to check. Currently a group contains `value` elements, your check for `flag` doesn't select anything at all, it seems, as `value` elements don't have `flag` children, only `part/flag` grandchildren. – Martin Honnen Jan 06 '22 at 14:12

1 Answers1

2

You are correct that variables are not mutable. Think declaratively, rather than imperatively.

Assuming that this is inside of an xsl:for-each-group and you want to get a count of the items in the current-group() whose flag is not equal to 0. Rather than iterating through them all and incrementing a counter, just count() the items that satisfy that condition:

<xsl:variable name="cur" select="count(current-group()[flag != '0'])" />
kjhughes
  • 106,133
  • 27
  • 181
  • 240
Mads Hansen
  • 63,927
  • 12
  • 112
  • 147