XML - problem with sum function

C

cieron

Hi
I've got something like this one:

<positions>
<position>
<value>1000</value>
<count>3</count>
</position>
<position>
<value>800</value>
<count>2</count>
</position>
</positions>

I need on my page this result

1000 * 3 + 800 * 2 = 4600

but sum(position/value * position/count) is not working. How can I get what
I want?
 
D

David Carlisle

cieron said:
Hi
I've got something like this one:

<positions>
<position>
<value>1000</value>
<count>3</count>
</position>
<position>
<value>800</value>
<count>2</count>
</position>
</positions>

I need on my page this result

1000 * 3 + 800 * 2 = 4600

but sum(position/value * position/count) is not working. How can I get what
I want?


sum has to take a node set, so you can not in pure XSLT1 use sum() over
a computed expression.

IN Xpath2 (which is still in draft form, but implemented in saxon 8) you
will be able to do
sum(position/(value * count))

However for XSLT1, possibly the simplest is to use yor processor's
xx:node-set() extension function (if it has one, most do) and first
generate a list of products


<xsl:variable name="x">
<xsl:for-each select="position"/>
<x><xsl:value-of select="value * count"/></x>
</xsl:for-each>
</xsl:variable>

then sum these new x elements.:

<xsl:value-of select="xx:node-set($x/x)


Or you need to write a recursive template that accumuates the sum

<xsl:template match="positions">
<xsl:apply-templates select="position[1]"/>
</xsl:template>

<xsl:template match="position">
<xsl:param name="s" select="0"/>/>
<xsl:variable name="s2" select="$s + value * count"/>
<xsl:choose>
<xsl:when test="following-sibling::position">
<xsl:apply-templates select="following-sibling::position[1]">
<xsl:with-param name="s" select="$s2"/>
</xsl:apply-templates>
<xsl:eek:therwise>
<xsl:value-of select="$s2"/>
</xsl:eek:therwise>
</xsl:choose>
</xsl:template>

David
 
D

Dimitre Novatchev

cieron said:
Hi
I've got something like this one:

<positions>
<position>
<value>1000</value>
<count>3</count>
</position>
<position>
<value>800</value>
<count>2</count>
</position>
</positions>

I need on my page this result

1000 * 3 + 800 * 2 = 4600

but sum(position/value * position/count) is not working. How can I get
what
I want?


FXSL is your friend -- look for the foldl or runningTotals template.

or directly sumProducts.xsl in:
http://www.mulberrytech.com/Extreme/Proceedings/xslfo-pdf/2003/Novatchev01/EML2003Novatchev01.pdf


Cheers,
Dimitre Novatchev
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,764
Messages
2,569,564
Members
45,041
Latest member
RomeoFarnh

Latest Threads

Top