Subject: RE: Question about grouping
From: "Hugh Barnes" <Hugh.Barnes@xxxxxxxxxxxx>
Date: Fri, 24 Sep 2010 12:40:22 +1000
|
Hi David
> -----Original Message-----
> From: David Frey [mailto:dpfrey@xxxxxxx]
> Sent: Friday, 24 September 2010 11:51 AM
> To: xsl-list@xxxxxxxxxxxxxxxxxxxxxx
> Subject: 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.
>
This seems to work. Very quickly ripped off Jeni Tennison's example using the
Muenchian grouping method:
http://www.jenitennison.com/xslt/grouping/muenchian.html. Add sorting like she
did if you need it.
Throw this within your transform:
<xsl:key name="authorgroup" match="book" use="@author" />
<xsl:template match="/doc">
<report>
<xsl:for-each select="book[count(.|key('authorgroup',@author)[1]) = 1]">
<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>
Cheers
Hugh Barnes
Technical Interface Specialist
nehta - National E-Health Transition Authority
Address: Level 2, 10 Browning St, West End, QLD, 4101
Phone: +61 7 3023 8537
Mobile: +61 417 469 552
Email: hugh.barnes@xxxxxxxxxxxx
Web: http://www.nehta.gov.au
|