I am a beginner , and I was wondering how I can converts the following XML format with XSLT 1.0 transform.
<project>
<item>
<id>123</id>
<name>abc</name>
<category>list</category>
</item>
<item>
<id>456</id>
<name>def</name>
<category>object</category>
</item>
<item>
<id>789</id>
<name>dfd</name>
<category>list</category>
</item>
<item>
<id>111</id>
<name>SC, CM</name>
<category>object</category>
</item>
</project>
To the following xml form, in which xml elements are grouped based on their unique category.
<?xml version="1.0" ?>
<project xmlns="">
<findings>
<finding>
<category>list</category>
<id>123</id>
<name>abc</name>
<id>789</id>
<name>dfd</name>
</finding>
<finding >
<category>object</category>
<id>456</id>
<name>def</name>
<id>111</id>
<name>SC, CM</name>
</finding>
<findings>
</project>
I know it would be the worst way of implementing it but, here is what I have tried so far :
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="/">
<project xmlns="xyz.com">
<xsl:key name="keyCategory" match="item" use="category" />
<findings>
<xsl:for-each select="//item[generate-id(.) = generate-id(key('keyCategory)', category)[1])]">
<finding>
<category><xsl:value-of select="category"/></category>
<id><xsl:value-of select="id"/></id>
<name><xsl:value-of select="name"/></name>
</finding></xsl:for-each>
<findings>
</project>
</xsl:template>
</xsl:stylesheet>
Try this:
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output indent="yes"/>
<xsl:key name="keyCategory" match="item" use="category"/>
<xsl:template match="/">
<project xmlns="xyz.com">
<findings>
<xsl:for-each
select="//item[generate-id(.) = generate-id(key('keyCategory', category)[1])]">
<finding>
<category>
<xsl:value-of select="category"/>
</category>
<xsl:for-each select="key('keyCategory', category)">
<id>
<xsl:value-of select="id"/>
</id>
<name>
<xsl:value-of select="name"/>
</name>
</xsl:for-each>
</finding>
</xsl:for-each>
</findings>
</project>
</xsl:template>
</xsl:stylesheet>
See Transform at https://xsltfiddle.liberty-development.net/94AcskZ