Home > front end >  Why is my XSLT counter variable not updated?
Why is my XSLT counter variable not updated?

Time:10-24

This is my XML:

<?xml version="1.0" encoding="UTF-8"?>
<catalog>
    <product id="V123049">
        <name>Bendable Sunglasses</name>
        <price>30</price>
        <quantity>1030</quantity>
    </product>
    <product id="C039890">
        <name>Sports Wrist Watch</name>
        <price>60</price>
        <quantity>1430</quantity>
    </product>
    <product id="M392829">
        <name>AutoPilot Road Navigator</name>
        <price>19</price>
        <quantity>129</quantity>
    </product>
    <product id="D190315">
        <name>StealthFinder GPS for Laptop</name>
        <price>100</price>
        <quantity>45</quantity>
    </product>
    <product id="E938393">
        <name>Frye Folding Leather Shopper</name>
        <price>89</price>
        <quantity>230</quantity>
    </product>
    <product id="V392839">
        <name>Pachislo Slot Machine</name>
        <price>595</price>
        <quantity>95</quantity>
    </product>
    <product id="K928379">
        <name>Sterling Cross Necklace</name>
        <price>100</price>
        <quantity>329</quantity>
    </product>
    <product id="I303920">
        <name>World Time Calculator</name>
        <price>30</price>
        <quantity>698</quantity>
    </product>
</catalog>

I want to show number of prices over 100.

Here the code that I've written:

          <xsl:for-each select="//product"> 
            <xsl:variable name="pr" select="//price" />
            <xsl:variable name="counter" >0</xsl:variable>
            <xsl:variable name="var" >100</xsl:variable>
             <xsl:if test="$pr>=$var">
                 <xsl:variable name="counter" select="$counter  1" />
            </xsl:if>
          </xsl:for-each>
         <span class="text"> Total Products(price>=100):<xsl:value-of select="$counter"/>  </span>
           </p>
                      

Not only does it not show the number, the XSLT also doesn't work and shows plain codes, not the output.

I've checked most of the code, and it seems the main problem is with this line:

<xsl:variable name="counter" select="$counter  1" />

I've searched but I didn't find anything to solve it.

CodePudding user response:

Abandon the procedural loop altogether and use a single declarative expression over the input:

<xsl:value-of select="count(/catalog/product[price > 100])"/>.

For further explanation of the rationale, see How to change or reassign a variable in XSLT?

  • Related