Re: [xsl] Is it possible to select only nodes with distinct element?

Subject: Re: [xsl] Is it possible to select only nodes with distinct element?
From: Jeni Tennison <mail@xxxxxxxxxxxxxxxx>
Date: Mon, 26 Mar 2001 12:13:26 +0100
Hi Denis,

> I need to select only distinct nodes, something like SELECT DISTINCT
> in SQL. By distinct I mean that one element of node is distinct.

The basic way of doing this is by testing whether there are any
preceding nodes in the document that have the same value as this one -
if there are, then ignore the node; if there aren't, then process it.

Using your example, you could do this with:

  a[not(preceding-sibling::a/b = b)]

To only process these nodes, you can use:

  <xsl:apply-templates select="a[not(preceding-sibling::a/b = b)]" />

within a template matching the parent of the a elements.

You may find this inefficient if you have lots of a elements, in which
case, you should use the Muenchian method, and use a key to index the
a elements according to their b element child:

<xsl:key name="a-by-b" match="a" use="b" />

You can then select the distinct a elements by seeing whether the
particular a element is the same as the first a element with that
particular b value (as retrieved form the key).  i.e.:

  a[generate-id() = generate-id(key('a-by-b', b)[1])]

or:

  a[count(.|key('a-by-b', b)[1]) = 1]

I hope that helps,

Jeni

---
Jeni Tennison
http://www.jenitennison.com/



 XSL-List info and archive:  http://www.mulberrytech.com/xsl/xsl-list


Current Thread