Input xml
<catalog>
<product id="1">
<name>abc</name>
<category>aaa</category>
<category>bbb</category>
<category>ccc</category>
</product>
<product id="2">
<name>cde</name>
<category>aaa</category>
<category>bbb</category>
</product>
</catalog>
Expected Output xml
<products>
<product>
<id>1</id>
<name>abc</name>
<category>aaa,bbb,ccc</category>
</product>
<product>
<id>2</id>
<name>cde</name>
<category>aaa,bbb</category>
</product>
</products>
XSLT for transformation
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" indent="yes"/>
<xsl:template match="/catalog">
<products>
<xsl:for-each select="product">
<product>
<id><xsl:value-of select="@id"/></id>
<name><xsl:value-of select="name"/></name>
<category><xsl:value-of select="category" /></category>
</product>
</xsl:for-each>
</products>
</xsl:template>
</xsl:stylesheet>
Actual Output xml :(
<products>
<product>
<id>1</id>
<name>abc</name>
<category>aaa</category>
</product>
<product>
<id>2</id>
<name>cde</name>
<category>aaa</category>
</product>
</products>
Code needed in looping through all sibling node by the name 'category' under every 'product' and merging/concatenating into single node separated by a comma. Number of 'category' varies for every product and hence the count is unknown.
In XSLT 2.0 you only need to make one small change to your code:
Note that if you require an XSLT 1.0 solution it's a good idea to say so. Some people in some environments are stuck on 1.0, but a lot of people aren't.
Using this handy join call-template defined here, this becomes as simple as:
Output:
Here's one other XSLT 1.0 solution.
When this XSLT:
...is applied to the OP's original XML:
...the desired result is produced:
Explanation:
Identity Template
-- matches all nodes and attributes and copies them to the result document as-is.<category>
element and processing the text children of each<category>
element in the current location of the document.