Kundan
Kundan

Reputation: 153

Grouping and counting in XSLT 1.0

I have input XML:

<?xml version="1.0" encoding="UTF-8"?>
<root>
   <FT>Paket</FT>
   <FT>Parti</FT>
   <FT>Paket</FT>
   <FT>Styche</FT>
   <FT>Styche</FT>
</root>

And I want my output to display such as -

Paket   2
Parti   1
Styche  2

Its is grouping the value of elements and the no. is showing the total count of the value being repeated. Like Paket is indicating the value and it is being repeated 2 times in the XML.

How the logic will work?

Upvotes: 2

Views: 1473

Answers (1)

Kirill Polishchuk
Kirill Polishchuk

Reputation: 56222

In XSLT 1.0, using Muenchian grouping:

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <xsl:output method="text" indent="yes"/>
  <xsl:key name="k" match="FT" use="."/>

  <xsl:template match="/*">
    <xsl:apply-templates select="FT[generate-id() = generate-id(key('k', .))]"/>
  </xsl:template>

  <xsl:template match="FT">
    <xsl:value-of select="concat(., ' ', count(key('k', .)))"/>
    <xsl:text>&#xa;</xsl:text>
  </xsl:template>

</xsl:stylesheet>

Output:

Paket 2
Parti 1
Styche 2

Upvotes: 2

Related Questions