p2p.wrox.com Forums

p2p.wrox.com Forums (http://p2p.wrox.com/index.php)
-   XSLT (http://p2p.wrox.com/forumdisplay.php?f=86)
-   -   count distinct nodes (http://p2p.wrox.com/showthread.php?t=24628)

alexshiell January 27th, 2005 10:19 AM

count distinct nodes
 
In the XML below:

<stuff>
   <something type="12345"/>
   <something type="12345"/>
   <something type="23451"/>
   <something type="23451"/>
   <something type="33333"/>
</stuff>

I want to count the number of distinct types of 'something', in this case its 3.

I've tried using a key, but that only allows me to count the number of instances of each specified type.

I can create a long-winded template which will go through each node and increment a counter every time it discovers a new type, but i was wondering if there was a neat way to do it that I am missing.

Cheers

mhkay January 27th, 2005 11:16 AM

For all problems concerning eliminating, counting, or grouping duplicates, see http://www.jenitennison.com/xslt/grouping

It's easy in XPath 2.0, of course:

   count(distinct-values(something/@type))

You can't do it the way you suggest, by incrementing counters: functional languages don't work that way.

Michael Kay
http://www.saxonica.com/
Author, XSLT Programmer's Reference and XPath 2.0 Programmer's Reference

pgtips January 27th, 2005 11:19 AM

Let's say you have a key like this:
Code:

<xsl:key name="k1" match="something" use="@type"/>
then you can just do this:
Code:

<xsl:template match="stuff">
    unique : <xsl:value-of select="count(something[generate-id() = generate-id(key('k1', @type)[1])])"/>
</xsl:template>



All times are GMT -4. The time now is 12:49 PM.

Powered by vBulletin®
Copyright ©2000 - 2020, Jelsoft Enterprises Ltd.
© 2013 John Wiley & Sons, Inc.