Mega Code Archive

 
Categories / XML / XSLT StyleSheet
 

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>