XSLT: Calculating Across Columns of Table

N

Newbie

Suppose that I have an HTML table of numbers, and I need to replace the value of each cell with
itself divided by the total for that column. The best I can think of is as follows:

<xsl:for-each select="tr">
<xsl:copy>
<xsl:for-each select="td">
<xsl:variable name="col" select="position()" />
<xsl:variable name="total" select="sum(../../tr/td[position()=$col])" />
<xsl:copy>
<xsl:value-of select=". div $total" />
</xsl:copy>
</xsl:for-each>
</xsl:copy>
</xsl:for-each>

This is rather verbose (the temporary col variable), and has to be recalculated for each row. Is
there a more concise/efficient way of doing this?
 
S

Soren Kuula

Newbie said:
Suppose that I have an HTML table of numbers, and I need to replace the
value of each cell with itself divided by the total for that column. The
best I can think of is as follows:

Better make that XHTML ;)

The best I can think of is using keys: All 1'st td's will be mapped
under 1 in the k key, all second under 2, etc.... The key is then looked
up (using position()) where needed. Column node selection is thus done,
but the sum is still recomputed.


<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
version='1.0'>

<xsl:key name="k" match="td" use="1 + count(preceding-sibling::td)"/>

<xsl:template match="tr">
<tr>
<xsl:apply-templates select="td"/>
</tr>
</xsl:template>

<xsl:template match="td">
<td>
<xsl:value-of select=". div sum(key('k', position()))"/>
</td>
</xsl:template>

</xsl:stylesheet>



Sample input:
<html>
<body>
<table>
<tr>
<td>1</td>
<td>2</td>
</tr>
<tr>
<td>3</td>
<td>4</td>
</tr>
</table>
</body>
</html>


Sample output:

<tr><td>0.25</td><td>0.33333333333333</td></tr>
<tr><td>0.75</td><td>0.66666666666667</td></tr>

(oops that's not even XML --- well a / mathcing template could wrap over
it what it is missing ;) ;) )


Søren
 

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,999
Messages
2,570,243
Members
46,836
Latest member
login dogas

Latest Threads

Top