Re: [xsl] Grouping problem

Subject: Re: [xsl] Grouping problem
From: Martin Honnen <Martin.Honnen@xxxxxx>
Date: Sat, 04 Apr 2009 16:27:42 +0200
Vincent De Groote wrote:

and I want to structure the document like this:

<document>
   <section>
        Some text-fragments ...
        <section>
             Some text-fragments ...
        </section>
   </section>
   <section>
        ... Some fragments for the second section ...
   </section>
</document>

Here is an XSLT 2.0 stylesheet that should work for two levels:


<xsl:stylesheet
  xmlns:xsl="http://www.w3.org/1999/XSL/Transform";
  version="2.0">

  <xsl:output method="xml" indent="yes"/>
  <xsl:strip-space elements="*"/>

<xsl:template match="document">
<xsl:copy>
<xsl:for-each-group select="text-fragment" group-starting-with="text-fragment[@function = 'section' and @level = '1']">
<section>
<xsl:for-each-group select="current-group()" group-starting-with="text-fragment[@function = 'section' and @level = '2']">
<xsl:choose>
<xsl:when test="not(@level = '2')">
<xsl:apply-templates select="current-group()"/>
</xsl:when>
<xsl:otherwise>
<section>
<xsl:apply-templates select="current-group()"/>
</section>
</xsl:otherwise>
</xsl:choose>
</xsl:for-each-group>
</section>
</xsl:for-each-group>
</xsl:copy>
</xsl:template>


  <xsl:template match="text-fragment">
    <xsl:copy>
      <xsl:apply-templates/>
    </xsl:copy>
  </xsl:template>

</xsl:stylesheet>

When applied to your XML input (made well-formed) it creates the following result:

<document>
   <section>
      <text-fragment> Some text </text-fragment>
      <text-fragment> Some text </text-fragment>
      <text-fragment> Some text </text-fragment>
      <text-fragment> Some text </text-fragment>
      <section>
         <text-fragment> Some text </text-fragment>
         <text-fragment> Some text </text-fragment>
         <text-fragment> Some text </text-fragment>
         <text-fragment> Some text </text-fragment>
      </section>
      <section>
         <text-fragment> Some text </text-fragment>
         <text-fragment> Some text </text-fragment>
         <text-fragment> Some text </text-fragment>
         <text-fragment> Some text </text-fragment>
      </section>
   </section>
   <section>
      <text-fragment> Some text </text-fragment>
      <text-fragment> Some text </text-fragment>
      <text-fragment> Some text </text-fragment>
      <text-fragment> Some text </text-fragment>
   </section>
</document>

--

	Martin Honnen
	http://JavaScript.FAQTs.com/

Current Thread