I m working with XSLT1.0 . My requirement is to merge set of elements based on a common attribute. I ve an xml which looks like this:
As shown in the other topic halfbit linked to, you need to use a key in order to (1) select distinct products (aka the Muenchian method) and (2) collect the values from the related group.
Here's a little more readable (IMHO) version:
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes" />
<xsl:key name="sameProduct" match="product" use="productId" />
<xsl:template match="/">
<!-- SELECT ONLY THE FIRST PRODUCT IN EACH GROUP -->
<xsl:for-each select="Catalog/product[generate-id() = generate-id(key('sameProduct', productId)[1])]">
<product>
<productId><xsl:value-of select="productId"/></productId>
<name><xsl:value-of select="name"/></name>
<category>
<!-- GET THE VALUES FROM ALL MEMBERS OF THE GROUP -->
<xsl:for-each select="key('sameProduct', productId)">
<xsl:value-of select="category"/>
<xsl:if test="position() != last()">
<xsl:text>,</xsl:text>
</xsl:if>
</xsl:for-each>
</category>
</product>
</xsl:for-each>
</xsl:template>
</xsl:stylesheet>
If your processor is EXSLT capable, you can use the set:distinct() function instead of the Muenchian grouping.