Grouping in XSLT : Grouping « XSLT stylesheet « XML

XML
1. CSS Style
2. SVG
3. XML Schema
4. XQuery
5. XSLT stylesheet
Java
XML Tutorial
Java Tutorial
Java Source Code / Java Documentation
Java Open Source
Jar File Download
Java Articles
Java Products
Java by API
C# / C Sharp
C# / CSharp Tutorial
ASP.Net
ASP.NET Tutorial
JavaScript DHTML
JavaScript Tutorial
JavaScript Reference
HTML / CSS
HTML CSS Reference
C / ANSI-C
C Tutorial
C++
C++ Tutorial
Ruby
PHP
Python
SQL Server / T-SQL
SQL Server / T-SQL Tutorial
Oracle PL / SQL
Oracle PL/SQL Tutorial
PostgreSQL
SQL / MySQL
MySQL Tutorial
VB.Net
VB.Net Tutorial
Flash / Flex / ActionScript
VBA / Excel / Access / Word
Microsoft Office PowerPoint 2007 Tutorial
Microsoft Office Excel 2007 Tutorial
Microsoft Office Word 2007 Tutorial
XML » XSLT stylesheet » Grouping 
Grouping in XSLT


File: Data.xml
<?xml version="1.0"?>
<html>
  <body>
    <h2>A</h2>
    <p class="item">A</p>
    <p class="item">B</p>
    <p class="note">C</p>
    <p class="note">D</p>
    <p class="note">E</p>
    <p class="item">F</p>
    <h2>B</h2>
    <p class="item">b1</p>
    <p class="item">b2</p>
    <p class="note">b3</p>
    <p class="item">b4</p>
  </body>
</html>


File: Transform.xslt

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

  <xsl:output method="xml" indent="yes"/>

  <xsl:template match="/">
    <chapter>
      <title>Grouping in XSLT</title>
      <xsl:apply-templates select="html/body"/>
    </chapter>
  </xsl:template>

  <xsl:template match="body">
    <xsl:for-each-group select="*" group-starting-with="h1">
      <sect1>
        <xsl:apply-templates select="current-group()"/>
      </sect1>
    </xsl:for-each-group>
  </xsl:template>

  <xsl:template match="h1">
    <title>
      <xsl:apply-templates/>
    </title>
  </xsl:template>

  <xsl:template match="p">
    <para>
      <xsl:apply-templates/>
    </para>
  </xsl:template>

  <xsl:template match="*">
    <xsl:copy>
      <xsl:copy-of select="@*"/>
      <xsl:apply-templates/>
    </xsl:copy>
  </xsl:template>

</xsl:stylesheet>

Output:

<?xml version="1.0" encoding="UTF-8"?>
<chapter>
   <title>Grouping in XSLT</title>
   <sect1>
      <h2>A</h2>
      <para>A</para>
      <para>B</para>
      <para>C</para>
      <para>D</para>
      <para>E</para>
      <para>F</para>
      <h2>B</h2>
      <para>b1</para>
      <para>b2</para>
      <para>b3</para>
      <para>b4</para>
   </sect1>
</chapter>

 
Related examples in the same category
1. Grouping with group-adjacent
2. Addresses grouped by zip code
www.java2java.com | Contact Us
Copyright 2010 - 2030 Java Source and Support. All rights reserved.
All other trademarks are property of their respective owners.