PDA

View Full Version : XSLT: Using the sum function


Joseph McGarvey
03-03-2003, 07:15 PM
I have been reading about sum() to evaluate some nodes. I am very confused and cannot get anything working.

Here is my (simplified) XML:

<entity>
<value>55</value>
</entity>
<entity>
<value>7</value>
</entity>
<entity>
<value>18</value>
</entity>

How do I write my XSL to add the <value> nodes to return the total? Do I use "sum()" with a "call-template" and what should that called template look like?

Thanks!!

P.S. Sorry if this has been covered in the forum, but you cannot search for strings less than 4 characters... like "sum", so I was unable to get any search results.

mpjbrennan
03-07-2003, 09:04 PM
Here's an xml file and an xsl stylesheet which performs the sum operation you are looking for:-

patrick

sum_me.xml (sourcefile)
------------------
<?xml version="1.0"?>
<?xml-stylesheet type="text/xsl" href="sum_it.xml"?>
<main>
<entity>
<value>55</value>
</entity>
<entity>
<value>7</value>
</entity>
<entity>
<value>18</value>
</entity>
</main>

sum_it.xml (stylesheet)
------------------
<?xml version="1.0"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
<xsl:output method="html"/>
<xsl:template match="/">
<html>
<body>
<xsl:apply-templates />
</body>
</html>

</xsl:template>
<xsl:template match="main">
<p>
<xsl:value-of select="sum(*)"/>
</p>
</xsl:template>
</xsl:stylesheet>