xsl-list
[Top] [All Lists]

Re: [xsl] Grouping problem

2009-04-04 10:28:18
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[(_at_)function = 'section' and @level = '1']">
        <section>
<xsl:for-each-group select="current-group()" group-starting-with="text-fragment[(_at_)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/

--~------------------------------------------------------------------
XSL-List info and archive:  http://www.mulberrytech.com/xsl/xsl-list
To unsubscribe, go to: http://lists.mulberrytech.com/xsl-list/
or e-mail: <mailto:xsl-list-unsubscribe(_at_)lists(_dot_)mulberrytech(_dot_)com>
--~--

<Prev in Thread] Current Thread [Next in Thread>