[xsl] Using xsl:for-each-group to create nested sections

Subject: [xsl] Using xsl:for-each-group to create nested sections
From: "Swanjord, Renee" <RSwanjord@xxxxxxxxxxxxxxxxxxx>
Date: Fri, 9 Jul 2004 10:57:15 -0500
I am creating nested section elements from a fairly flat input file, but
I am having difficulty getting the nested sections to output correctly.

This is my input XML:

<doc>
  <h1>chapter title</h1>
  <para>introduction</para>
  <h2>section title</h2>
  <para>stuff</para>
  <para>more stuff</para>
  <h2>another section</h2>
  <para>blah, blah, blah</para>
  <note>You will be on vacation soon!</note>
  <para>summary</para>
</doc>

This is my desired output:

<doc>
  <section>
    <title>chapter title</title>
    <para>introduction</para>
    <section>
      <title>section title</title>
      <para>stuff</para>
      <para>more stuff</para>
    </section>
    <section>
      <title>another section</title>
      <para>blah, blah, blah</para>
      <note>You will be on vacation soon!</note>
      <para>summary</para>
    </section>
  </section>
</doc>

However, my current XSLT:

<xsl:template match="doc">
  <doc>
    <xsl:for-each-group select="*" group-starting-with="h1">
      <section>
        <xsl:apply-templates select="current-group()[self::h1]" />
        <xsl:for-each-group select="current-group() except ."
                            group-starting-with="h2">
          <section>
            <xsl:apply-templates select="current-group()[self::*]" />
          </section>
        </xsl:for-each-group>
      </section>
    </xsl:for-each-group>
  </doc>
</xsl:template>
....

Is producing the following output:

<doc>
   <section>
      <title>chapter title</title>
      <section>
         <para>introduction</para>
      </section>
      <section>
         <title>section title</title>
         <para>stuff</para>
         <para>more stuff</para>
      </section>
      <section>
         <title>another section</title>
         <para>blah, blah, blah</para>
         <note>You will be on vacation soon!</note>
         <para>summary</para>
      </section>
   </section>
</doc>

How can I get the stylesheet to wrap the nested section tags only around
the content beginning with the first <h2> and not around the elements
that come before the first <h2>?

Thanks,
Renee

Current Thread