Christophe Debove
Christophe Debove

Reputation: 6296

Groupby distinct how can I do that?

<?xml version="1.0"?>
<Products>
     <product>
         <productId >1</productId>
          <textdate>11/11/2011</textdate>
          <price>200</price>
      </product>
  <product>
         <productId >6</productId>
          <textdate>11/11/2011</textdate>
          <price>100</price>
      </product>
  <product>
         <productId >1</productId>
          <textdate>16/11/2011</textdate>
          <price>290</price>
      </product>
</Products>

I've this xml and I want an xslt transformation that regroup product something like this :

{ product 1 :
11/11/2011 - 200
16/11/2011 - 290 }
{ product 6
11/11/2011 - 100 }

I work with xslt 1.0 Asp .net C# XslCompiledTransformation

Upvotes: 0

Views: 99

Answers (2)

Flack
Flack

Reputation: 5892

This XSLT:

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="text"/>
<xsl:strip-space elements="*"/>

<xsl:key name="groupById" match="product" use="productId"/>

<xsl:template match="/*">
    <xsl:apply-templates select="product[
                        generate-id() =
                        generate-id( key( 'groupById', productId ) )
                        ]"/>
</xsl:template>

<xsl:template match="product">
    <xsl:text>{ product </xsl:text>
    <xsl:value-of select="concat(productId, ' : &#xa;')"/>
    <xsl:apply-templates select="key( 'groupById', productId )" mode="inner-content"/>
    <xsl:text> }&#xa;</xsl:text>
</xsl:template>

<xsl:template match="product" mode="inner-content">
    <xsl:value-of select="concat( textdate, ' - ', price )"/>
    <xsl:if test="position() != last()">
        <xsl:text>&#xa;</xsl:text>
    </xsl:if>
</xsl:template>

</xsl:stylesheet>

Applied to your code sample, it will produce this result:

{ product 1 : 
11/11/2011 - 200
16/11/2011 - 290 }
{ product 6 : 
11/11/2011 - 100 }

Upvotes: 1

Martin Honnen
Martin Honnen

Reputation: 167696

Use Muenchian grouping as explained here: http://www.jenitennison.com/xslt/grouping/index.xml. If you need help with writing the code then please state whether you want plain text output or HTML output in the format you posted.

Upvotes: 1

Related Questions