Michael
Michael

Reputation: 443

XSL For-each Total Count

I am trying to return a total count using for-each in xsl. For example in one instance, there are 8 iterations or car_types and I'd like to return a total count for $car_types[0] + $car_types[1] + $car_types[2] + $car_types[3] ...and so on. Does anyone know how to achieve this? Thanks!

<xsl:for-each select="$car_types">
    <xsl:variable name="counter" select="position()"/>
    <xsl:value-of select="count(/webpage/results/cars/*[type = $car_types[$counter]])" />
</xsl:for-each>

Upvotes: 1

Views: 2326

Answers (3)

Dimitre Novatchev
Dimitre Novatchev

Reputation: 243599

Just use:

count(/webpage/results/cars/*[type = $car_types])

The above means:

Give me the count of all children-elements of all /webpage/results/cars, whose type is one of the types contained in $car_types

Read more about the semantics of the XPath general equality operator here and here.

Upvotes: 1

hr_117
hr_117

Reputation: 9627

Try:

 <xsl:value-of select="count(/webpage/results/cars/*[type = $car_types])" />

Upvotes: 1

Martin Honnen
Martin Honnen

Reputation: 167716

Store the main document with

<xsl:variable name="main-doc" select="/"/>

outside of the for-each, then you can use

<xsl:for-each select="$cart_types">
  <xsl:value-of select="count($main-doc/webpage/results/car/*[type = current()])"/>
</xsl:for-each>

That assumes that $cart_types contains nodes from a document different to the primary, main input document. And it assumes your paths are correct as shown, you will have to show an input sample to allow us to tell.

Upvotes: 1

Related Questions