Reputation: 5
I need some help to compute sum and add some comparison complexity to know which element should be part of the sum.
Let's take the following XML
<REF>
<amount>3</amount>
<rate>7</rate>
</REF>
<A>
<amount>10</amount>
<rate>4</rate>
</A>
<A>
<amount>-21</amount>
<rate>2</rate>
</A>
<B>
<amount>8</amount>
<rate>1</rate>
</B>
<C>
<amount>7</amount>
<rate>32</rate>
</C>
I would like to display the sum of each amount multiplied by each associated rate within a Total element. And I would like to split my total into two elements: NegativeTotal and PositiveTotal. PostiveTotal will contain the SUM of ((amount * rate) if the value is greater than (amount * rate) of REF object) NegativeTotal will contain the SUM of ((amount * rate) if the value is less than (amount * rate) of REF object)
It should give the below output
<Total>
<PositiveTotal>
264 <!-- 40 + 224 -->
</PositiveTotal>
<NegativeTotal>
-34 <!-- -42 + 8 -->
</NegativeTotal>
</Total>
Please let me know if it's possible For information technical limitation: XSLT 1.0
Thanks in advance
Regards,
Upvotes: 0
Views: 48
Reputation: 116959
I would suggest you do it this way:
XSLT 1.0
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:exsl="http://exslt.org/common"
extension-element-prefixes="exsl">
<xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>
<xsl:template match="/root">
<!-- first pass -->
<xsl:variable name="summands-rtf">
<xsl:for-each select="*">
<value>
<xsl:value-of select="amount * rate" />
</value>
</xsl:for-each>
</xsl:variable>
<xsl:variable name="summands" select="exsl:node-set($summands-rtf)/value" />
<!-- get the threshold -->
<xsl:variable name="threshold" select="REF/amount * REF/rate" />
<!-- output -->
<Total>
<PositiveTotal>
<xsl:value-of select="sum($summands[. > $threshold])" />
</PositiveTotal>
<NegativeTotal>
<xsl:value-of select="sum($summands[. < $threshold])" />
</NegativeTotal>
</Total>
</xsl:template>
</xsl:stylesheet>
When applied to a well-formed XML input (with a single root element):
XML
<root>
<REF>
<amount>3</amount>
<rate>7</rate>
</REF>
<A>
<amount>10</amount>
<rate>4</rate>
</A>
<A>
<amount>-21</amount>
<rate>2</rate>
</A>
<B>
<amount>8</amount>
<rate>1</rate>
</B>
<C>
<amount>7</amount>
<rate>32</rate>
</C>
</root>
the result will be:
<?xml version="1.0" encoding="UTF-8"?>
<Total>
<PositiveTotal>264</PositiveTotal>
<NegativeTotal>-34</NegativeTotal>
</Total>
Note that the product of REF
amount and rate is not included in any of the two totals, as it is neither above nor below the threshold. Similarly, if any other product happens to be equal to the threshold. it too will be excluded.
Upvotes: 1