RE: [xsl] Question about grouping

Subject: RE: [xsl] Question about grouping
From: Scott Trenda <Scott.Trenda@xxxxxxxx>
Date: Thu, 23 Sep 2010 23:31:54 -0500
David,

While Hugh's answer might work, the method used in his first for-each select is kind of an odd way of doing Muenchian grouping in XSLT 1.0. Here's the approach with the standard method:

<xsl:key name="authorgroup" match="book" use="@author" />

<xsl:template match="/doc">
	<report>
		<xsl:for-each select="book[generate-id() = generate-id(key('authorgroup', @author))]">
			<author name="{@author}">
				<xsl:for-each select="key('authorgroup', @author)">
					<title><xsl:value-of select="@title" /></title>
				</xsl:for-each>
			</author>
		</xsl:for-each>
	</report>
</xsl:template>

Someone else might be able to elaborate more about the performance differences of using generate-id() vs. count(), but generate-id() is the more widely used approach.

~ Scott

-----Original Message-----
From: David Frey [mailto:dpfrey@xxxxxxx] 
Sent: Thursday, September 23, 2010 8:51 PM
To: xsl-list@xxxxxxxxxxxxxxxxxxxxxx
Subject: [xsl] Question about grouping

I have an XSLT problem that I haven't been able to figure out.  The example 
below is essentially the simplest version of the problem I have encountered.

Say you have a document like this:

<doc>
  <book title="aaa" author="jones"/>
  <book title="bbb" author="smith"/>
  <book title="ccc" author="douglas"/>
  <book title="ddd" author="jones"/>
  <book title="eee" author="jones"/>
  <book title="fff" author="douglas"/>
  <book title="ggg" author="smith"/>
</doc>


How can you produce a document like this?:

<report>
  <author name="jones">
	<title>aaa</title>
	<title>ddd</title>
	<title>eee</title>
  </author>
  <author name="smith">
	<title>bbb</title>
	<title>ggg</title>
  </author>
  <author name="douglas">
	<title>bbb</title>
	<title>fff</title>
  </author>
</report>

Restrictions:
- Only XSLT 1.0
- You can't hard-code the names of the books or the authors in the XSLT.


Thanks,
Dave

Current Thread