I have a set of xml nodes with identical node names but one attribute that differentiate them, and an amount attribute:
<exampleNode typeOfnode="1" amount="100"/>
<exampleNode typeOfnode="1" amount="540"/>
<exampleNode typeOfnode="2" amount="200"/>
<exampleNode typeOfnode="2" amount="200"/>
<exampleNode typeOfnode="3" amount="10"/>
<exampleNode typeOfnode="3" amount="1"/>
<exampleNode typeOfnode="3" amount="110"/>
<exampleNode typeOfnode="3" amount="110"/>
<exampleNode typeOfnode="4" amount="110"/>
I’m using a recursive template to calculate the sum of the amounts, but only want to do that for a specific typeOfNode. Here is the code I’m using to call the template:
<xsl:call-template name="addition">
<xsl:with-param name="currentValue">0</xsl:with-param>
<xsl:with-param name="counter"><xsl:value-of select="count(//exampleNode[@typeOfnode= '1'])"/></xsl:with-param>
<xsl:with-param name="typeOfnode">1</xsl:with-param>
</xsl:call-template>
<xsl:template name="addition">
<xsl:param name="currentValue"/>
<xsl:param name="counter"/>
<xsl:param name="typeOfNode"/>
<xsl:variable name="amount" select="//exampleNode[@typeOfNode = '$typeOfnode' and $counter]/@amount"/>
<xsl:variable name="recursiveValue" select="number($recursiveValue + $amount)"/>
<xsl:choose>
<xsl:when test="number($counter - 1) > 0">
<xsl:call-template name="addition">
<xsl:with-param name="currentValue">
<xsl:value-of select="$recursiveValue"/>
</xsl:with-param>
<xsl:with-param name="counter">
<xsl:value-of select="number($counter - 1)"/>
</xsl:with-param>
<xsl:with-param name="agreementType">
<xsl:value-of select="$agreementType"/>
</xsl:with-param>
</xsl:call-template>
</xsl:when>
<xsl:otherwise>
<xsl:value-of select="$recursiveValue"/>
</xsl:otherwise>
</xsl:choose>
</xsl:template>
Having debugged through wiTH XMLspy, the amount variable is not being set, and I assume it’s because I’m screwing up the query. Anybody have any idea what I’m doing wrong?
for a quick answer, see the last code block. For some comments on the code, read from here.
How about fixing the recursive loop by using currentValue iso recursiveValue to seed the recursiveValue:
There are some XSLT errors here, e.g. this does not look like it will work:
if you mean to say “amount is the @amount of the $counter-th /exampleNode with @typeOfNode=$typeofnode, this is not the way.
Your snippet
is probably missing some confuscation, did you mean typeOfnode iso agreementType? 😀
All of that aside, there are simpler solutions. for instance a quite direct: