Groups | Blog | Home
all groups > dotnet xml > july 2007 >

dotnet xml : Help - use XSLT to group by multiple values?



7/23/2007 7:40:47 AM
I'm using XSLT and .NET Framework 1.1 to try to transform XML to group
by multiple values, and I'm not succeeding. I have source XML that
looks like the following:

<Data>
<Flavor>
<Name>Vanilla</Name>
<StartDate>20070704</StartDate>
<EndDate>20071231</EndDate>
</Flavor>
<Flavor>
<Name>Chocolate</Name>
<StartDate>20070704</StartDate>
<EndDate>20071131</EndDate>
</Flavor>
<Flavor>
<Name>Strawberry</Name>
<StartDate>20070804</StartDate>
<EndDate>20071131</EndDate>
</Flavor>
<Flavor>
<Name>Mint</Name>
<StartDate>20070704</StartDate>
<EndDate>20071131</EndDate>
</Flavor>
</Data>


I need to group the items together that have the same values for
StartDate and EndDate such that the output looks like the following:

<Groups>
<Group>
<Name>Group1</Name>
<Flavors>
<Name>Vanilla</Name>
</Flavors>
<StartDate>20070704</StartDate>
<EndDate>20071231</EndDate>
</Group>
<Group>
<Name>Group2</Name>
<Flavors>
<Name>Chocolate</Name>
<Name>Mint</Name>
</Flavors>
<StartDate>20070704</StartDate>
<EndDate>20071131</EndDate>
</Group>
<Group>
<Name>Group3</Name>
<Flavors>
<Name>Strawberry</Name>
</Flavors>
<StartDate>20070804</StartDate>
<EndDate>20071231</EndDate>
</Group2>
</Groups>

I've tried to use the Muenchian Method with keys, but I haven't been
successful. Can anyone please provide some assistance?

Thanks in advance
Martin Honnen
7/23/2007 5:35:03 PM
[quoted text, click to view]

Not sure where you had problems as you have not shown your XSLT but here
is a working XSLT 1.0 stylesheet:

<xsl:stylesheet
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
version="1.0">

<xsl:output method="xml" indent="yes"/>

<xsl:strip-space elements="*"/>

<xsl:key name="by-date" match="Flavor" use="concat(StartDate, '_',
EndDate)"/>

<xsl:template match="Data">
<Groups>
<xsl:apply-templates select="Flavor[generate-id() =
generate-id(key('by-date', concat(StartDate, '_', EndDate))[1])]"
mode="group"/>
</Groups>
</xsl:template>

<xsl:template match="Flavor" mode="group">
<Group>
<Name><xsl:value-of select="concat('Group', position())"/></Name>
<Flavors>
<xsl:apply-templates select="key('by-date', concat(StartDate,
'_', EndDate))/Name"/>
</Flavors>
<xsl:apply-templates select="StartDate | EndDate"/>
</Group>
</xsl:template>

<xsl:template match="Name | StartDate | EndDate">
<xsl:copy>
<xsl:apply-templates/>
</xsl:copy>
</xsl:template>

</xsl:stylesheet>
--

Martin Honnen --- MVP XML
AddThis Social Bookmark Button