Search code examples
xmlxsltxslt-2.0xslt-grouping

group an element using xslt


I want to use the function "group by" in a xsl file but I am just getting errors.

This is my code:

<table xsl:version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<tr>
<th>A</th>
<th>B</th>
</tr>
<xsl:for-each-group select="Result/Record" group-by="AC_CPR">
<tr>
  <td><xsl:value-of select="AC_CPR"/></td>
  <td><xsl:value-of select='sum(//AC_LNA/Row/Column[2])'/></td>
</tr>

The error is this one:

msxml3.dll error '80004005'

"Keyword table may not contain xsl:for-each-group".

The xml is this:

 <Result>
<Record code="033007">
<Name>demo</Name>
 <AC_CPR>02080</AC_CPR>
<date>10/06/2009</date>
<AC_LNA ncols="2">
<Row>
<Column>000115</Column>
<Column>9</Column>
</Row>
</AC_LNA>
<AC_FSE>10/06/2009</AC_FSE>
<AC_AV/>
</Record>
</Result>

Solution

  • Write a complete stylesheet with e.g.

    <xsl:stylesheet
      xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
      version="1.0">
    
    <xsl:key name="group" match="Result/Record" use="AC_CPR"/>
    
    <xsl:template match="Result">
    <table>
    <tr>
    <th>A</th>
    <th>B</th>
    </tr>
    <xsl:for-each select="Record[generate-id() = generate-id(key('group', AC_CPR)[1])]">
    <tr>
      <td><xsl:value-of select="AC_CPR"/></td>
      <td><xsl:value-of select="sum(key('group', AC_CPR)/AC_LNA/Row/Column[2])"/></td>
    </tr>
    </xsl:for-each>
    </table>
    
    </xsl:template>
    
    </xsl:stylesheet>
    

    For the sum I have guessed that you want to sum for each group and not for the complete set of all nodes.