RE: [xsl] Grouping & use of keys

Subject: RE: [xsl] Grouping & use of keys
From: "Michael Kay" <mike@xxxxxxxxxxxx>
Date: Thu, 26 Feb 2009 18:33:44 -0000
> I am a newbie at XSLT, have only written 1 identity transform 
> that took me 2 weeks to get working. I have a grouping task 
> for some xml data 

Grouping is MUCH easier in XSLT 2.0. Do you have anything that constrains
you to XSLT 1.0?

> 
> I think of <xsl:key......> as a declaration, similar to "new" 
> in some OO languages. 

Think of xsl:key as "create index", so

<xsl:key name="es" match="employee" use="surname"/>

creates an index of employees by surname, and

key('es', 'Smith')

finds the employees with surname 'Smith'

In XSLT 2.0, to group employees by surname, you simply do

<xsl:for-each-group select="employee" group-by="surname">
  then
  <xsl:for-each select="current-group()">

In XSLT 1.0 you use Muenchian grouping, which logically does this:

for each employee
  get the surname
  call key() to find all the employees with that surname
  apply [1] to get the first of these employees
  test whether this one is the current employee
  if so, treat this employee as the "owner" of the group
     find all employees with this surname by calling key() again
     and process them as required

OK?

Michael Kay
http://www.saxonica.com/

Current Thread