Re: [xsl] How to find distinct nodes by value?

Subject: Re: [xsl] How to find distinct nodes by value?
From: "James A. Robinson" <jim.robinson@xxxxxxxxxxxx>
Date: Wed, 11 Oct 2006 10:55:58 -0700
> I would like to retrieve only the distinct nodes (by value) from a
> "//myElement"-like  expression; <myElement> is either empty or contains
> only text.

I don't know if you know in advance which elements you want to filter
on -- if you did, or if you could set this up so that you populated an
importable .xsl file with keys, then one way you could do this in XSL
1.0 is by using keys built on the values:
  
  <?xml version="1.0" encoding="UTF-8"?>
  <xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"; version="1.0">
    
    <xsl:output indent="yes"/>
    
    <xsl:key name="myElementByValue" match="myElement" use="string(.)"/>
    
    <xsl:template match="/">
      <unique>
        <xsl:copy-of select="//myElement[generate-id(.) = generate-id(key('myElementByValue', string(.))[1])]"/>
      </unique>
    </xsl:template>
   
  </xsl:stylesheet>

In XSL 2.0 you could handle this in a more flexible way by using grouping,
using the element values as the grouping item:
  
  <?xml version="1.0" encoding="UTF-8"?>
  <xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"; version="2.0">
    
    <xsl:output indent="yes"/>
    
    <xsl:key name="myElementByValue" match="myElement" use="string(.)"/>
    
    <xsl:template match="/">
      <unique>
        <xsl:for-each-group select="//myElement" group-by="string(.)">
          <xsl:sequence select="."/>
        </xsl:for-each-group>
      </unique>
    </xsl:template>
   
  </xsl:stylesheet>

Jim

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
James A. Robinson                       jim.robinson@xxxxxxxxxxxx
Stanford University HighWire Press      http://highwire.stanford.edu/
+1 650 7237294 (Work)                   +1 650 7259335 (Fax)

Current Thread