For each group I have to group by artists having the same number. In the output I have to show the position of the for-each-group (output: 1, 2, 3) but the position resets when entering the second loop of the group and the output currently is (wrong-output:1,2,1).
<xsl:for-each select="group"> <xsl:for-each-group select="artist" group-by="number"> <position> <xsl:value of select="position()"/> </position> <counter> <xsl:value of select="count(number)"/></counter> </xsl:for-each-group> </xsl:for-each>
or
<xsl:for-each select="group"> <xsl:for-each-group select="artist" group-by="number"> <position> <xsl:value of select="position()"/> </position> <counter> <xsl:value of select="count(number)"/></counter> </xsl:for-each-group> </xsl:for-each>
<?xml version="1.0" encoding="UTF-8"?>
<group>
<artist>
<number>1</number>
</artist>
<artist>
<number>1</number>
</artist>
<artist>
<number>2</number>
</artist>
<artist>
<number>2</number>
</artist>
</group>
<group>
<artist>
<number>5</number>
</artist>
<artist>
<number>5</number>
</artist>
</group>
CodePudding user response:
It sounds, based on the wanted output, that you don't need and want the outer for-each
and instead directly want to group all artist
s with e.g.
<xsl:for-each-group select="group/artist" group-by="number">
For your sample data, that would give three groups and the inner <xsl:value of select="position()"/>
would that way output the sequence 1, 2, 3.
CodePudding user response:
Here is an example showing how you could number all subgroups consecutively while also keeping their parent groups numbering:
XML
<input>
<group>
<item>
<category>a</category>
</item>
<item>
<category>a</category>
</item>
<item>
<category>a</category>
</item>
<item>
<category>b</category>
</item>
<item>
<category>b</category>
</item>
</group>
<group>
<item>
<category>a</category>
</item>
<item>
<category>a</category>
</item>
</group>
</input>
XSLT 2.0
<xsl:stylesheet version="2.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>
<xsl:template match="/input">
<xsl:variable name="groups">
<xsl:for-each select="group">
<group group-num="{position()}" >
<xsl:copy-of select="*"/>
</group>
</xsl:for-each>
</xsl:variable>
<output>
<xsl:for-each-group select="$groups/group/item" group-by="concat(category, '|', generate-id(..))">
<category group-num="{../@group-num}" subgroup-num="{position()}" >
<xsl:value-of select="category"/>
</category>
</xsl:for-each-group>
</output>
</xsl:template>
</xsl:stylesheet>
Result
<?xml version="1.0" encoding="UTF-8"?>
<output>
<category group-num="1" subgroup-num="1">a</category>
<category group-num="1" subgroup-num="2">b</category>
<category group-num="2" subgroup-num="3">a</category>
</output>