Pregunta

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!

¿Fue útil?

Solución

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
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top