[xsl] Grouping based on the sum of an attribute

Subject: [xsl] Grouping based on the sum of an attribute
From: "Spencer Tickner" <spencertickner@xxxxxxxxx>
Date: Fri, 26 Jan 2007 09:32:02 -0800
Hi List,

Thanks in advance for the help. I've been wrapping my mind around
for-each-group for the last couple of days and finding it to be a very
useful tool. However, I have now come across a situation which I
really can't wrap my mind around, even after going through the
examples at http://www.w3.org/TR/xslt20/#element-for-each-group. I'm
using XSL 2.0.

XML:

<?xml version="1.0"?>
<table cols="3" rows="2">
	<cell cols="3" rows="1">
		<head>Head</head>
	</cell>
	<cell cols="1" rows="1">
		<p>Column 1</p>
	</cell>
	<cell cols="1" rows="1">
		<p>Column 2</p>
	</cell>
	<cell cols="1" rows="1">
		<p>Column 3</p>
	</cell>
</table>

Desired Output:

<?xml version='1.0' ?>
<table>
	<tr>
		<th colspan="3" rowspan="1">Head</th>
       </tr>
       <tr>
		<td colspan="1" rowspan="1">Column 1</td>
		<td colspan="1" rowspan="1">Column 2</td>
		<td colspan="1" rowspan="1">Column 3</td>
	</tr>
</table>

XSL:

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

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

<xsl:template match="table">
<table>
<xsl:variable name="tcols" select="@cols"/>
<xsl:for-each-group select="*" group-by="sum(cell/@cols) = number(tcols)">
<tr>
	<xsl:apply-templates select="current-group()"/>
</tr>
</xsl:for-each-group>
</table>
</xsl:template>

<xsl:template match="cell[p]"><td colspan="{@cols}"
rowspan="{@rows}"><xsl:apply-templates/></td></xsl:template>

<xsl:template match="cell[head]"><th colspan="{@cols}"
rowspan="{@rows}"><xsl:apply-templates/></th></xsl:template>


</xsl:stylesheet>


The problem is my XPath expression on the group-by. I've tried a
number of variations on the XPath as well as trying group-ending-with
and group-adjacent but I keep getting exactly the same output:

<?xml version='1.0' ?>
<table>
	<tr>
		<th colspan="3" rowspan="1">Head</th>
		<td colspan="1" rowspan="1">Column 1</td>
		<td colspan="1" rowspan="1">Column 2</td>
		<td colspan="1" rowspan="1">Column 3</td>
	</tr>
</table>

Any thoughts or suggestions would be greatly appreciated.

Thanks,

Spencer

Current Thread