Re: [xsl] grouping items in a list of records

Subject: Re: [xsl] grouping items in a list of records
From: Martin Honnen <Martin.Honnen@xxxxxx>
Date: Wed, 20 May 2009 13:09:34 +0200
Skopik Pavel wrote:

Within each "item" I need to group the node "planItemOrganization"
according to "role" and for each role output value represented by
node "organization/name1/name". The thing is that values of the role
node are not constant and they may change.

For now the stylesheets finds all roles according to key, groups
organizations right but outputs all in the first item which is not
desired. I am wondering how to restrict the processing to just
current item, so that within each item groups are created in the
right way. In XSLT 2.0 it would be fairly easy, but I am stuck with
1.0...

This is the stylesheet which I succesfully used for grouping in one
record now adapted to process list of records (for better readablity
and simplification I extracted it to ouptut text):

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

<xsl:key name="role" match="planItemOrganization"
use="role/name/name"/>

If you want to restrict the grouping to the parent 'item' element then one way to do that is to integrate the generated id of the 'item' element into the key, as in the following stylesheet:


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

<xsl:key name="role" match="planItemOrganization" use="concat(generate-id(parent::item), '|', role/name/name)"/>

    <xsl:output method="text" encoding="UTF-8"/>
    <xsl:strip-space elements="*"/>

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

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

<xsl:template match="item">
<xsl:text>Item </xsl:text>
<xsl:number/>
<xsl:for-each select="planItemOrganization[count(. | key('role', concat(generate-id(parent::item), '|', role/name/name))[1]) = 1]">
<xsl:sort select="order"/>
<xsl:text>&#10;</xsl:text>
<xsl:value-of select="role/name/name"/>
<xsl:text>&#10;</xsl:text>
<xsl:for-each select="key('role', concat(generate-id(parent::item), '|', role/name/name))">
<xsl:text> </xsl:text>
<xsl:value-of select="organization/name1/name"/>
<xsl:text>&#10;</xsl:text>
</xsl:for-each>
</xsl:for-each>
</xsl:template>


</xsl:stylesheet>

However that way I don't get quite the result you described, instead I get

Item 1
Orders
  Organization 1
  Organization 2
  Organization 4

Approves
  Organization 3
  Organization 5
Item 2
Organizes
  Organization 5
  Organization 6

Executes
  Organization 7
  Organization 8

Co-operation
  Organization 9

when I run the above stylesheet against your XML sample data. The result however should be what you want, I guess the sample result you provided did not match the sample input data you provided.

--

	Martin Honnen
	http://msmvps.com/blogs/martin_honnen/

Current Thread