user3669116
user3669116

Reputation: 23

XSL to count xml node under inside loop

## I have my xml as below and I want get the count of title node I have tried below but I always get count as 1 since it is under for-each loop

    <xsl:if test="$countryVal !='' and $countryVal = 'USA'">
<tr>
      <td><xsl:value-of select="title"/></td>
      <h3>Count of titles <xsl:value-of select="count(catalog/cd/title)"/></h3>
    </tr>
    </xsl:if>
    </xsl:for-each>

<catalog>
  <cd>
    <title>USD</title>
    <artist>Bob Dylan</artist>
    <country>USA</country>
    <company>Columbia</company>
    <price>10.90</price>
    <year>1985</year>
  </cd>
  <cd>
    <title>USD</title>
    <artist>Bonnie Tyler</artist>
    <country>USA</country>
    <company>CBS Records</company>
    <price>9.90</price>
    <year>1988</year>
  </cd>
  <cd>
    <title>CAD</title>
    <artist>Dolly Parton</artist>
    <country>CAN</country>
    <company>RCA</company>
    <price>9.90</price>
    <year>1982</year>
  </cd>
  <cd>
    <title>USD</title>
    <artist>Gary Moore</artist>
    <country>USA</country>
    <company>Virgin records</company>
    <price>10.20</price>
    <year>1990</year>
  </cd>
</catalog>
#

xml shared is part of big xml sharing the snippet of it. Any pointers?

Upvotes: 0

Views: 159

Answers (1)

michael.hor257k
michael.hor257k

Reputation: 116993

I would suggest you use a variable to hold the filtered node-set - so that you only need to apply the filtering once:

<xsl:variable name="eligible-cds" select="/catalog/cd[country='USA']" />

Then you can do:

<xsl:for-each select="$eligible-cds">
    <tr>
        <td><xsl:value-of select="title"/></td>
    </tr>
</xsl:for-each>
<h3>Count of titles <xsl:value-of select="count($eligible-cds)"/></h3>

Upvotes: 1

Related Questions