1

I am quite new to XSLT and I would like to generate a count of participants for a list of events. This is my XML:

<events>
    <event name="christmas"/>
    <event name="halloween"/>
    <event name="easter"/>
    <event name="easter"/>
</events>

What I need is something like this:

Christmas: 1 participant
Halloween: 1 participant
Easter: 2 participants

Can this be done with XSLT in any way?

Thanks for any help!

Tintin81
  • 9,821
  • 20
  • 85
  • 178

1 Answers1

3

Try this stylesheet, which uses the Muenchian Method to group the event elements by their @name:

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output omit-xml-declaration="yes" indent="yes"/>
<xsl:strip-space elements="*"/>
    <!-- based on 
    http://stackoverflow.com/a/16509871/2115381 
    from Dimitre Novatchev
    --> 
    <xsl:key name="kEventVal" match="event" use="@name"/>

<xsl:template match="*">

            <xsl:apply-templates select=
         "event[generate-id() = generate-id(key('kEventVal',@name)[1])]"/>
</xsl:template>

<xsl:template match="event">
    <xsl:value-of select="@name"/>
    <xsl:text>: </xsl:text>
    <xsl:value-of select="count(key('kEventVal',@name))"/>
    <xsl:text> participant</xsl:text>
    <xsl:if test="count(key('kEventVal',@name)) > 1 ">
        <xsl:text>s</xsl:text>
    </xsl:if>
    <xsl:text>&#10;</xsl:text>
</xsl:template>
</xsl:stylesheet>

Which will generate following output:

christmas: 1 participant
halloween: 1 participant
easter: 2 participants
Mads Hansen
  • 63,927
  • 12
  • 112
  • 147
hr_117
  • 9,589
  • 1
  • 18
  • 23
  • Thanks! Will try that. Just one question: What exactly does the `` do? Is that some kind of external plugin? – Tintin81 May 13 '13 at 10:59
  • That are two questions. ;-) 1. This generate something like a map wiht attribute name as key, and a list of all matching event elements as value. (E.g. have a look to http://www.w3schools.com/xsl/el_key.asp. 2. No plugin ore extension required. This xslt-1.0 . – hr_117 May 13 '13 at 11:08
  • Thank you very much for your help. It took me some time to read up on this, and I managed to get this working with a slightly modified code. I got stuck on one last detail though, so I posted a [new question](http://stackoverflow.com/questions/16572145/how-to-extend-a-muenchian-xml-grouping). – Tintin81 May 15 '13 at 18:15