Saturday, 18 April 2015

XSLT: add up number and print subtotal multiple times



im a beginner with XSLT and figured out that i cannot just add up numbers using variables by calling the multiple times trying to add up to a variable.


I have a XML with a list of numbers i need to add up until the element matches a specific attribute value, then print that number reset it to 0 and continue adding up the rest until i see that specific attribute again.


For example i have this XML:



<list>
<entry>
<field type="num" value="189.5" />
</entry>
<entry>
<field type="num" value="1.5" />
</entry>
<entry>
<field type="summary" />
</entry>
<entry>
<field type="num" value="9.5" />
</entry>
<entry>
<field type="num" value="11" />
</entry>
<entry>
<field type="num" value="10" />
</entry>
<entry>
<field type="summary" />
</entry>
</list>


Now i want my XSLT to print this:



189.5
1.5
#191#
9.5
11
10
#30.5#


I have read that i can do that by using sum() with conditions. I know how to use for-each and point to the elements relatively and iam also able to use sum() by simply summarizing all having type=num, but how to sum only first num until type=summary comes up, then next sum only from last type=summary until the next one?


I would expect something like this:



<xsl:for-each select="list/entry">
<xsl:if test="field[@type='summary']">
<!-- we are now at a type=summary element, now sum up -->
#<xsl:value-of select="sum(WHAT_TO_PUT_HERE?)" />#
</xsl:if>
<xsl:if test="field[@type='num']">
<xsl:value-of select="field/@value" />
</xsl:if>
</xsl:for-each>


Appreciate any help.


No comments:

Post a Comment