<root>
<element>
<id>1</id>
<group>first</group>
</element>
<element>
<id>2</id>
<group>second</group>
</element>
<element>
<id>3</id>
<group>first</group>
</element>
...
<root>
How I can group my elements by the group name in xslt 1.0. the output:
<root>
<group name="first">
<element>
<id>1</id>
<group>first</group>
</element>
<element>
<id>3</id>
<group>first</group>
</element>
</group>
<group name="second">
<element>
<id>2</id>
<group>second</group>
</element>
</group>
</root>
Any ideas?
This is a job for Muenchian Grouping. You will numerous examples of it within the XSLT tag here on StackOverflow.
First, you need to define a key to help you group the groups
This will look up group elements for a given group name.
Next, you need to match all the occurrences of the first instance of each distince group name. This is done with this scary looking statement
i.e Match group elements which happen to be the first occurence of that element in our key.
When you have matched the distinct group nodes, you can then loop through all other group nodes with the same name (where $currentGroup is a variable holding the current group name)
Putting this altogether gives
Applying this on your sample XML gives the following result
I. Here is a complete and very short XSLT 1.0 solution:
when this transformation is applied on the provided XML document:
the wanted, correct result is produced:
Do note:
The use of the Muenchian method for grouping. This is the most efficient grouping method in XSLT 1.0.
The use of AVT (Attribute Value Template) to specify a literal result element and its variable - value attribute as one whole. Using AVTs simplifies coding and yields shorter and more understandable code.
II. An even shorter XSLT 2.0 solution:
when this transformation is applied on the same XML document (above), the same correct result is again produced.
Do note:
.1. The use of the
<xsl:for-each-group>
XSLT 2.0 instruction..2. The use of the standard XSLT 2.0 functions
current-group()
andcurrent-grouping-key()