[XSL-LIST Mailing List Archive Home] [By Thread] [By Date]

[xsl] XSLT 1.0 Grouping


Subject: [xsl] XSLT 1.0 Grouping
From: aspsa <aspsa@xxxxxxxxxxxxx>
Date: Tue, 12 Apr 2005 01:06:41 -0400

Hi, folks...

I'm trying to wrap my brain around the Muenchian Method. Essentially, I have
the following simple XML document.

<?xml version="1.0" encoding="UTF-8"?>
<root>
 <people>
  <person>
   <name>
    <fname>Jack</fname>
    <mname>Fred</mname>
    <lname>Smith</lname>
   </name>
   <age>22</age>
  </person>
  <person>
   <name>
    <fname>Jane</fname>
    <mname>Mary</mname>
    <lname>Smith</lname>
   </name>
   <age>23</age>
  </person>
  <person>
   <name>
    <fname>Frank</fname>
    <mname>Joseph</mname>
    <lname>Franks</lname>
   </name>
   <age>23</age>
  </person>
 </people>
</root>

I'd like to sort and group it by age, such that each person of the same age
is placed in ascending order within each unique age value.

Here's what I have so far.

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

 <xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>

 <xsl:key name="byAge" match="person" use="age"/>

 <xsl:template match="/">
  <people>
   <xsl:apply-templates select="root/people/person">
    <xsl:sort select="age" data-type="number" order="ascending"/>
   </xsl:apply-templates>
   <xsl:apply-templates mode="personGrouped"
	select="root/people/person[generate-id()=generate-id(key('byAge',
age)[1])]"/>
  </people>
 </xsl:template>

 <xsl:template match="person" mode="personGrouped">
  <age>
   <xsl:attribute name="value"><xsl:value-of select="age"/></xsl:attribute>
   <name>
    <fname><xsl:value-of select="name/fname"/></fname>
    <mname><xsl:value-of select="name/mname"/></mname>
    <lname><xsl:value-of select="name/lname"/></lname>
   </name>
  </age>
 </xsl:template>

</xsl:stylesheet>

Here's the output after processing...

<?xml version="1.0" encoding="UTF-8"?>
<people>JackFredSmith22JaneMarySmith23FrankJosephFranks23
 <age value="22">
  <name>
   <fname>Jack</fname>
   <mname>Fred</mname>
   <lname>Smith</lname>
  </name>
 </age>
 <age value="23">
  <name>
   <fname>Jane</fname>
   <mname>Mary</mname>
   <lname>Smith</lname>
  </name>
 </age>
</people>

Here is the output I would like to see...

<?xml version="1.0" encoding="UTF-8"?>
<people>
 <age value="22">
  <name>
   <fname>Jack</fname>
   <mname>Fred</mname>
   <lname>Smith</lname>
  </name>
 </age>
 <age value="23">
  <name>
   <fname>Frank</fname>
   <mname>Joseph</mname>
   <lname>Franks</lname>
  </name>
  <name>
   <fname>Jane</fname>
   <mname>Mary</mname>
   <lname>Smith</lname>
  </name>
 </age>
</people>

Thanks for your feedback.


Regards,

ASP


Current Thread
Keywords
xml