Hi all,
I'm having some trouble with getting my groups correct with for-each-group. I'm able to group by <coll>, but I would like to avoid repeating the <county>. I've placed my style sheet below the desired output. Any suggestions would be greatly appreciated.
I've attempted a few different variations using group-adjacent but I'm missing something. Thank you for your time & trouble. I'm using XSLT 2.0.
I have the following input file:
Code:
<base>
<item>
<coll>AAA</coll>
<inst>horn</inst>
<name>Andy</name>
<county>AlphaC</county>
</item>
<item>
<coll>BBB</coll>
<inst>chimes</inst>
<name>Bob</name>
<county>BravoC</county>
</item>
<item>
<coll>AAA</coll>
<inst>bells</inst>
<name>Cynthia</name>
<county>CharlieC</county>
</item>
<item>
<coll>CCC</coll>
<inst>flute</inst>
<name>Daria</name>
<county>BravoC</county>
</item>
<item>
<coll/>
<inst>horn</inst>
<name>Edgar</name>
<county>DeltaC</county>
</item>
<item>
<coll>AAA</coll>
<inst>drum</inst>
<name>Fred</name>
<county>AlphaC</county>
</item>
</base>
I would like to output the following:
Code:
<newDoc>
<group>
<doc>Edgar-docTitle</doc>
<title/>
<subject>Edgar</subject>
<subject>DeltaC</subject>
</group>
<group>
<doc>AAA-docTitle</doc>
<title>AAA</title>
<subject>Andy</subject>
<subject>Cynthia</subject>
<subject>Fred</subject>
<subject>AlphaC</subject>
<subject>CharlieC</subject>
</group>
<group>
<doc>BBB-docTitle</doc>
<title>BBB</title>
<subject>Bob</subject>
<subject>BravoC</subject>
</group>
<group>
<doc>CCC-docTitle</doc>
<title>CCC</title>
<subject>Daria</subject>
<subject>BravoC</subject>
</group>
</newDoc>
This is my style sheet:
Code:
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:xs="http://www.w3.org/2001/XMLSchema" exclude-result-prefixes="xs" version="2.0">
<xsl:strip-space elements="*"/>
<xsl:output method="xml" indent="yes"/>
<xsl:template match="/">
<newDoc>
<xsl:for-each-group select="base/item" group-by="coll">
<xsl:sort select="current-grouping-key()"/>
<xsl:variable name="vResultName">
<xsl:choose>
<!-- doesn't work. keep working on this. -->
<xsl:when test="current-grouping-key() = ''">
<xsl:value-of select="concat(name[1], '-docTitle')"/>
</xsl:when>
<xsl:otherwise>
<xsl:value-of select="concat(current-grouping-key(), '-docTitle')"/>
</xsl:otherwise>
</xsl:choose>
</xsl:variable>
<group>
<doc>
<xsl:value-of select="$vResultName"/>
</doc>
<title>
<xsl:value-of select="current-grouping-key()"/>
</title>
<xsl:for-each select="current-group()">
<subject>
<xsl:value-of select="name"/>
</subject>
</xsl:for-each>
<!-- grab county element, unique only -->
<xsl:for-each-group select="current-group()" group-adjacent="county">
<xsl:sort select="current-grouping-key()"/>
<subject>
<xsl:value-of select="current-grouping-key()"/>
</subject>
</xsl:for-each-group>
</group>
</xsl:for-each-group>
</newDoc>
</xsl:template>
</xsl:stylesheet>