RE: [xsl] for-each-loop case

Subject: RE: [xsl] for-each-loop case
From: "Michael Kay" <mike@xxxxxxxxxxxx>
Date: Fri, 8 Apr 2005 08:24:47 +0100
> I am pretty new to XSLT2.0. My question is how to get desired output
> xml from following input by just using for-each-group. I can do it now
> with temporary tree but that means two phases transform:

A two phase transform is often a good thing - it keeps your code modular and
reusable!
> 
> input:

It's really helpful to readers to add some indentation:
> 
> <scores>
>  <devision id="1">
>   <student name="Tiger">
>    <subject name="English">
>     <score>98</score>
>    </subject>
>    <subject name="Math">
>     <score>102</score>
>    </subject>
>    <subject name="History">
>     <score>100</score>
>    </subject>
>   </student>
>   <student name="Jack">
...
>   </student>
>  </devision>
>  <devision id="2">
...
>  </devision>
> </scores>
> 
> Desired output :
> 
> <?xml version="1.0" encoding="UTF-8"?>
> <scores>
>    <subject name="English">
>       <devision id="1">
>          <student name="Tiger">
>             <score>98</score>
>          </student>
>          <student name="Jack">
>             <score>88</score>
>          </student>
>       </devision>
...
>    </subject>
> </scores>
> 

An unusual one!

I think this is:

<xsl:for-each-group select="//subject" group-by="@name">
<subject name="{current-grouping-key()}">
  <xsl:variable name="students-of-subject"
select="current-group()/parent::student"/>
  <xsl:for-each-group select="current-group()/ancestor::devision"
group-by="@id">
    <devision id="{current-grouping-key()}">
      <xsl:copy-of select="$students-of-subject intersect
current-group()/student"/>
    </
  </
</
</

Not tested.

Michael Kay
http://www.saxonica.com/

Current Thread