Grouping with group-adjacent : Grouping « XSLT stylesheet « XML






Grouping with group-adjacent



File: Data.xml

<?xml version="1.0"?>
<html>
  <body>
    <h2>A</h2>
    <p class="item">A <code>key</code>.</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">G</p>
    <p class="item">H</p>
    <p class="note">T</p>
    <p class="item">I</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="html" include-content-type="no"/>
  <xsl:template match="/">
    <html>
      <head>
        <title>Grouping with group-adjacent</title>
      </head>
      <body>
        <xsl:for-each-group select="html/body/*"
          group-adjacent="boolean(self::p)">
          <xsl:choose>
            <xsl:when test="current-grouping-key()">
              <ul>
                <xsl:for-each select="current-group()">
                  <li>
                    <xsl:copy-of select="@*"/>
                    <xsl:apply-templates select="*|text()"/>
                  </li>
                </xsl:for-each>
              </ul>
            </xsl:when>
            <xsl:otherwise>
              <xsl:for-each select="current-group()">
                <xsl:apply-templates select="."/>
              </xsl:for-each>
            </xsl:otherwise>
          </xsl:choose>
        </xsl:for-each-group>
      </body>
    </html>
  </xsl:template>

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

</xsl:stylesheet>

Output:

<html>
   <head>
      <title>Grouping with group-adjacent</title>
   </head>
   <body>
      <h2>A</h2>
      <ul>
         <li class="item">A <code>key</code>.
         </li>
         <li class="item">B</li>
         <li class="note">C</li>
         <li class="note">D</li>
         <li class="note">E</li>
         <li class="item">F.</li>
      </ul>
      <h2>B</h2>
      <ul>
         <li class="item">G</li>
         <li class="item">H</li>
         <li class="note">T</li>
         <li class="item">I</li>
      </ul>
   </body>
</html>

 








Related examples in the same category

1.Grouping in XSLT
2.Addresses grouped by zip code