XML Tutorial/XSLT stylesheet/for each group

Материал из Web эксперт
Перейти к: навигация, поиск

for-each-group select="make|model" group-ending-with="*[position() mod"

File: Data.xml
<?xml version="1.0"?>
<!-- carlist.xml -->
<cars>
  <make>Alfa Romeo</make>
  <make>Bentley</make>
  <make>Chevrolet</make>
  <make>Dodge</make>
  <make>Eagle</make>
  <make>Ford</make>
  <make>GMC</make>
</cars>
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>Car Makes and Models</title>
      </head>
      <body>
        <h1>Car Makes and Models</h1>
        <paragraph>Here are the car makes and models in 
        our input document.</p>
        <table border="1" cellpadding="5">
          <xsl:apply-templates select="cars"/>
        </table>
      </body>
    </html>
  </xsl:template>
  <xsl:template match="cars">
    <xsl:for-each-group select="make|model" group-ending-with="*[position() mod 3 = 0]">
      <tr>
        <xsl:apply-templates select="current-group()"/>
        <xsl:if test="count(current-group()) lt 3">
          <td style="background: #CCCCCC;"
            colspan="{3 - count(current-group())}">
          </td>
        </xsl:if>
      </tr>
    </xsl:for-each-group>
  </xsl:template>
  <xsl:template match="make">
    <td>
      <xsl:apply-templates/>
    </td>
  </xsl:template>
  <xsl:template match="model">
    <td style="font-style: italic; font-weight: bold;">
      <xsl:apply-templates/>
    </td>
  </xsl:template>
  
</xsl:stylesheet>
Output:
<html>
   <head>
      <title>Car Makes and Models</title>
   </head>
   <body>
      <h1>Car Makes and Models</h1>
      <paragraph>Here are the car makes and models in 
         our input document.
      </p>
      <table border="1" cellpadding="5">
         <tr>
            <td>Alfa Romeo</td>
            <td>Bentley</td>
            <td>Chevrolet</td>
         </tr>
         <tr>
            <td>Dodge</td>
            <td>Eagle</td>
            <td>Ford</td>
         </tr>
         <tr>
            <td>GMC</td>
            <td style="background: #CCCCCC;" colspan="2"></td>
         </tr>
      </table>
   </body>
</html>