Tecnologías XML / XSLT / Recetario XSLT / Transformar XML en HTML / Generar tablas HTML

(Extracto de «XSLT Kochbuch» de Sal Mangano)

Problema

Desea convertir contenido XML en tablas HTML.

Solución

Las tablas suelen generarse en dos pasos: crear el marcado superior y aplicar plantillas para filas y celdas. Esta solución modifica la hoja de la receta Crear documentos enlazados. La parte modificada está resaltada:

<xsl:stylesheet version="1.1" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <xsl:output method="html"/>
  <xsl:param name="URL"/>
  <xsl:template match="/">
    <xsl:apply-templates select="*" mode="index"/>
    <xsl:apply-templates select="*" mode="content"/>
  </xsl:template>
  <!-- =  =  =  =  =  =  =  =  =  =  =  =  =  =  =  =  =  =  =  =  =  =  =  =  = -->
  <!--             Erzeuge index.html  (mode = "index")                          -->
  <!-- =  =  =  =  =  =  =  =  =  =  =  =  =  =  =  =  =  =  =  =  =  =  =  =  = -->
  <xsl:template match="salesBySalesperson" mode="index">
    <!-- Nicht standardkonformes Saxon-xsl:document! -->
    <xsl:document href="index.html">
      <html>
        <head>
          <title>Sales by Salesperson</title>
        </head>
        <body bgcolor="#FFFFFF" text="#000000">
          <h1>Sales By Salesperson</h1>
          <xsl:apply-templates mode="index"/>
        </body>
      </html>
    </xsl:document>
  </xsl:template>
  <xsl:template match="salesperson" mode="index">
    <h2>
      <a href="{concat($URL,@name,'.html')}">
        <xsl:value-of select="@name"/>
      </a>
    </h2>
  </xsl:template>
  <!-- =  =  =  =  =  =  =  =  =  =  =  =  =  =  =  =  =  =  =  =  =  =  =  =  = -->
  <!--          Erzeuge @name.html  (mode = "content")                           -->
  <!-- =  =  =  =  =  =  =  =  =  =  =  =  =  =  =  =  =  =  =  =  =  =  =  =  = -->
  <template:xsl match="salesperson" mode="content">
    <xsl:document href="{concat(@name,'.html')}">
      <html>
        <head>
          <title><xsl:value select="@name"/></title>
        </head>
        <body bgcolor="#FFFFFF" text="#000000">
          <h1><xsl:value-of select="@name"/> Sales</h1>
          <table border="1" cellpadding="3">
            <tbody>
              <tr>
                <th>SKU</th>
                <th>Sales (in US $)</th>
              </tr>
              <xsl:apply-templates mode="content"/>
            </tbody>
          </table>
          <h2><a href="{concat($URL,'index.html')}">Home</a></h2>
        </body>
      </html>
    </xsl:document>
  </xsl:template>
  <xsl:template match="product" mode="content">
    <tr>
      <td><xsl:value-of select="@sku"/></td>
      <td><xsl:value-of select="@totalSales"/></td>
    </tr>
  </xsl:template>
</xsl:stylesheet>

Discusión

XSLT 1.0

Generar tablas suele requerir agrupaciones. La dificultad depende de la agrupación inicial y de si los criterios son cerrados o abiertos. Suponga que debe agrupar ventas por región:

<?xml version="1.0" encoding="UTF-8"?>
<sales>
  <product sku="10000" sales="90000.00" region="NE"/>
  <product sku="10000" sales="10000.00" region="NW"/>
  <product sku="10000" sales="55000.00" region="SE"/>
  <product sku="10000" sales="32000.00" region="SW"/>
  <product sku="10000" sales="95000.00" region="NC"/>
  <product sku="10000" sales="88000.00" region="SC"/>
  <product sku="20000" sales="77000.00" region="NE"/>
  <product sku="20000" sales="11100.00" region="NW"/>
  <product sku="20000" sales="33210.00" region="SE"/>
  <product sku="20000" sales="78000.00" region="SW"/>
  <product sku="20000" sales="105000.00" region="NC"/>
  <product sku="20000" sales="12300.00" region="SC"/>
  <product sku="30000" sales="1000.00" region="NE"/>
  <product sku="30000" sales="5100.00" region="NW"/>
  <product sku="30000" sales="3210.00" region="SE"/>
  <product sku="30000" sales="8000.00" region="SW"/>
  <product sku="30000" sales="5000.00" region="NC"/>
  <product sku="30000" sales="11300.00" region="SC"/>
</sales>

Con seis regiones conocidas de antemano, puede realizarse una selección explícita:

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <xsl:output method="html"/>
  <xsl:template match="sales">
    <html>
      <head>
        <title>Sales by Region</title>
      </head>
      <body>
        <h1>Sales by Region</h1>
        <table border="1" cellpadding="3">
          <tbody>
            <tr>
              <th>SKU</th>
              <th>Sales</th>
            </tr>
            <xsl:call-template name="group-region">
              <xsl:with-param name="region" select=" 'NE' "/>
              <xsl:with-param name="title" select="'North East Sales'"/>
            </xsl:call-template>
            <xsl:call-template name="group-region">
              <xsl:with-param name="region" select=" 'NW' "/>
              <xsl:with-param name="title" select="'North West Sales'"/>
            </xsl:call-template>
            <xsl:call-template name="group-region">
              <xsl:with-param name="region" select=" 'NC' "/>
              <xsl:with-param name="title" select="'North Central Sales'"/>
            </xsl:call-template>
            <xsl:call-template name="group-region">
              <xsl:with-param name="region" select=" 'SE' "/>
              <xsl:with-param name="title" select="'South East Sales'"/>
            </xsl:call-template>
            <xsl:call-template name="group-region">
              <xsl:with-param name="region" select=" 'SC' "/>
              <xsl:with-param name="title" select="'South Central Sales'"/>
            </xsl:call-template>
            <xsl:call-template name="group-region">
              <xsl:with-param name="region" select=" 'SW' "/>
              <xsl:with-param name="title" select="'South West Sales'"/>
            </xsl:call-template>
          </tbody>
        </table>
      </body>
    </html>
  </xsl:template>
  <xsl:template name="group-region">
    <xsl:param name="region"/>
    <xsl:param name="title"/>
    <xsl:variable name="products" select="product[@region = $region]" />
    <tr>
      <th colspan="2"><xsl:value-of select="$title" /></th>
    </tr>
    <xsl:apply-templates select="$products"/>
    <tr style="font-weight:bold">
      <td>Total</td>
      <td align="right">
        <xsl:value-of select="format-number(sum($products/@sales), '#.00')"/>
      </td>
    </tr>
  </xsl:template>
  <xsl:template match="product">
    <tr>
      <td><xsl:value-of select="@sku"/></td>
      <td align="right"><xsl:value-of select="@sales"/></td>
    </tr>
  </xsl:template>
</xsl:stylesheet>

Para evitar nombres escritos directamente en el código, utilice una tabla:

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:sales="sales">
  <sales:region code="NE" name="North East"/>
  <sales:region code="NC" name="North Central"/>
  <sales:region code="NW" name="North West"/>
  <sales:region code="SE" name="South East"/>
  <sales:region code="SC" name="South Central"/>
  <sales:region code="SW" name="South West"/>
  <xsl:variable name="products" select="/sales/product"/>
  <xsl:output method="html"/>
  <xsl:template match="sales">
    <html>
      <head>
        <title>Sales by Region</title>
      </head>
      <body>
        <h1>Sales by Region</h1>
        <table border="1" cellpadding="3">
          <tbody>
            <tr>
              <th>SKU</th>
              <th>Sales</th>
            </tr>
            <xsl:for-each select="document('')/*/sales:region">
              <tr>
                <th colspan="2"><xsl:value-of select="@name"/> Sales</th>
              </tr>
              <xsl:call-template name="group-region">
                <xsl:with-param name="region" select="@code"/>
              </xsl:call-template>
            </xsl:for-each>
          </tbody>
        </table>
      </body>
    </html>
  </xsl:template>
  <xsl:template name="group-region">
    <xsl:param name="region"/>
    <xsl:apply-templates select="$products[@region=$region]"/>
    <tr style="font-weight:bold">
      <td>Total</td>
      <td align="right">
        <xsl:value-of select="format-number(sum($products[@region=$region]/@sales),'#.00')"/>
      </td>
    </tr>
  </xsl:template>
  <xsl:template match="product">
    <tr>
      <td><xsl:value-of select="@sku"/></td>
      <td align="right"><xsl:value-of select="@sales"/></td>
    </tr>
  </xsl:template>
</xsl:stylesheet>

Muchos problemas son más difíciles. Una hoja usada por varias empresas o departamentos debe manejar distintas convenciones de nombres. Una de las soluciones más eficaces es la agrupación de Muench, llamada así por su inventor Steve Muench en Oracle, que combina claves e identificadores:

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:sales="sales">
  <xsl:output method="html"/>
  <xsl:key name="region-key" match="product" use="@region"/>
  <xsl:template match="sales">
    <html>
      <head>
        <title>Sales by Region</title>
      </head>
      <body>
        <h1>Sales by Region</h1>
        <table border="1" cellpadding="3">
          <tbody>
            <tr>
              <th>SKU</th>
              <th>Sales</th>
            </tr>
            <xsl:variable name="unique-regions" select="/sales/product[generate-id(.) = generate-id(key('region-key',@region))]/@region"/>
            <xsl:for-each select="$unique-regions">
              <tr >
                <th colspan="2"><xsl:value-of select="."/> Sales</th>
              </tr>
              <xsl:call-template name="group-region">
                <xsl:with-param name="region" select="."/>
              </xsl:call-template>
            </xsl:for-each>
          </tbody>
        </table>
      </body>
    </html>
  </xsl:template>
  <xsl:template name="group-region">
    <xsl:param name="region"/>
    <xsl:apply-templates select="key('region-key', @region)"/>
    <tr style="font-weight:bold">
      <td>Total</td>
      <td align="right">
        <xsl:value-of select="format-number(sum(key('region-key', @region)/@sales),'#.00')"/>
      </td>
    </tr>
  </xsl:template>
  <xsl:template match="product">
    <tr>
      <td><xsl:value-of select="@sku"/></td>
      <td align="right"><xsl:value-of select="@sales"/></td>
    </tr>
  </xsl:template>
</xsl:stylesheet>

Esta solución se parece al método con tabla, pero determina de otro modo los grupos únicos. La tabla codifica explícitamente las regiones únicas en elementos sales:region. El método de Muench utiliza una clave. La expresión key('region-key',@region) devuelve todos los productos cuya región es @region. Para un conjunto de nodos, generate-id devuelve el identificador único del primer elemento. Por tanto, la expresión [generate-id(.) = generate-id(key('region-key', @region))] solo es verdadera para el primer nodo de cada grupo e identifica las regiones únicas. La clave también mejora los demás accesos a productos.

XSLT 2.0

Salvo que haya saltado directamente aquí, sabe que la mejor forma de agrupar en XSLT 2.0 utiliza xsl:for-each-group:

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <xsl:output method="html"/>
  <xsl:template match="sales">
    <html>
      <head>
        <title>Sales by Region</title>
      </head>
      <body>
        <h1>Sales by Region</h1>
        <table border="1" cellpadding="3">
          <tbody>
            <tr>
              <th>SKU</th>
              <th>Sales</th>
            </tr>
            <xsl:for-each-group select="product" group-by="@region">
              <tr >
                <th colspan="2"><xsl:value-of select="."/> Sales</th>
              </tr>
              <xsl:apply-templates select="current-group( )"/>
              <tr style="font-weight:bold">
                <td>Total</td>
                <td align="right">
                  <xsl:value-of select="format-number(sum(current-group( )/@sales),'#.00')"/>
                </td>
              </tr>
            </xsl:for-each-group>
          </tbody>
        </table>
      </body>
    </html>
  </xsl:template>
  <xsl:template match="product">
    <tr>
      <td><xsl:value-of select="@sku"/></td>
      <td align="right"><xsl:value-of select="@sales"/></td>
    </tr>
  </xsl:template>
</xsl:stylesheet>

  

<< atrás

siguiente >>

 

 

 

volver arriba