RE: [xsl] "Group by" question

Subject: RE: [xsl] "Group by" question
From: "Andreas L. Delmelle" <a_l.delmelle@xxxxxxxxxx>
Date: Mon, 22 Mar 2004 19:18:41 +0100
> -----Original Message-----
> From: Hilder Sousa [mailto:Helder.Sousa@xxxxxx]
>
> Hi :)
>
> I would like to kwonw how can I do a "group by".. I explain:
> Imagine i have the next xml:
>
<snip />
> I need a xsl to "group by" the address. Like this:
>

Hi,

The easiest (and in case you have *a lot* of these nodes, also the most
efficient) way to achieve this, is using keys:

Put a declaration like this on the top-level of your stylesheet:
<xsl:key name="doc-by-addr" match="doc"
         use="@address" />

Then further on, you can use for example

<xsl:apply-templates select="key('doc-by-addr', 'av. A1')" />

Which will apply-templates to all document nodes with an address attribute
equal to 'av. A1'.

If you add a global variable, like

<xsl:variable name="vaddr"
              select="doc[not(@address = preceding::doc/@address)]" />

and apply-templates to it

<xsl:template match="docs">
  <xsl:copy>
    <xsl:apply-templates select="$vaddr" mode="group"/>
  </xsl:copy>
</xsl:template>

<xsl:template match="doc" mode="group">
  <address val="{@address}">
    <xsl:apply-templates select="key('doc-by-addr',@address)" />
  </address>
</xsl:template>

<xsl:template match="doc">
  <xsl:copy>
    <xsl:copy-of select="@id" />
    <xsl:apply-templates />
  </xsl:copy>
</xsl:template>

Together with a generic copy-template for the pages/page nodes, this
produces the wanted result.


Hope this helps!

Cheers,

Andreas

Current Thread