Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use for each group in XSL

im still learning for-each-group what is the best way of grouping something like this using XSL?(by country) i'm trying to use XSL to convert this XML to another XML.

<?xml version="1.0" encoding="UTF-8"?>
<Person>
    <Student>
        <Info Country="England" Name="Dan" Age="20" Class="C" />
    </Student>
    <Student>
        <Info Country="England" Name="Dan" Age="20" Class="B" />

    </Student>
    <Student>
        <Info Country="England" Name="Sam" Age="20" Class="A" />
    </Student>

    <Student>
       <Info Country="Australia" Name="David" Age="22" Class="D" />
    </Student>
    <Student>
        <Info Country="Australia" Name="David" Age="22" Class="A" />
    </Student>

</Person>
like image 501
Hash Avatar asked Oct 01 '13 11:10

Hash


People also ask

What is for-each-group in XSLT?

Allocates the items in an input sequence into groups of items (that is, it establishes a collection of sequences) based either on common values of a grouping key, or on a pattern that the initial or final node in a group must match.

What is the use of for each in XSLT?

The <xsl:for-each> element selects a set of nodes and processes each of them in the same way. It is often used to iterate through a set of nodes or to change the current node.

What is for-each-group?

Groups the items in a list by a specified element. This statement requires a Grouping statement to specify which element to group-by. See Converting a List Into a Grouped List for an example of using the For-Each-Group statement.


1 Answers

If you group by country you would start with e.g.

<xsl:template match="Person">
  <xsl:for-each-group select="Student/Info" group-by="@Country">
    <country name="{current-grouping-key()}">

    </country>
  </xsl:for-each-group>
</xsl:template>

Then you have to decide whether you want to further group the Info elements in each country group, for instance by name:

<xsl:template match="Person">
  <xsl:for-each-group select="Student/Info" group-by="@Country">
    <country name="{current-grouping-key()}">
      <xsl:for-each-group select="current-group()" group-by="@Name">
        <student name="{current-grouping-key()}">
          <classes>
            <xsl:for-each select="current-group()">
              <class><xsl:value-of select="@Class"/></class>
            </xsl:for-each>
          </classes>
        </student>
      </xsl:for-each-group>
    </country>
  </xsl:for-each-group>
</xsl:template>
like image 172
Martin Honnen Avatar answered Sep 28 '22 16:09

Martin Honnen