Tecnologías XML / XSLT / Recetario XSLT / Transformar XML en HTML / Generar hojas dirigidas por datos

(Extracto de «XSLT Kochbuch» de Sal Mangano)

Problema

Desea HTML cuyo estilo dependa de sus datos.

Solución

XSLT 1.0

Los conjuntos de atributos encapsulan la complejidad del estilo dirigido por datos. Considere esta cartera XML:

<portfolio>
  <investment>
    <symbol>IBM</symbol>
    <current>72.70</current>
    <paid>65.00</paid>
    <qty>1000</qty>
  </investment>
  <investment>
    <symbol>JMAR</symbol>
    <current>1.90</current>
    <paid>5.10</paid>
    <qty>5000</qty>
  </investment>
  <investment>
    <symbol>DELL</symbol>
    <current>24.50</current>
    <paid>18.00</paid>
    <qty>100000</qty>
  </investment>
  <investment>
    <symbol>P</symbol>
    <current>57.33</current>
    <paid>63</paid>
    <qty>100</qty>
  </investment>
</portfolio>

Muéstrela como tabla, con ganancias negras y pérdidas rojas:

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <xsl:output method="html"/>
  <xsl:attribute-set name="gain-loss-font">
    <xsl:attribute name="color">
      <xsl:choose>
        <xsl:when test="(current - paid) * qty &gt;= 0">black</xsl:when>
        <xsl:otherwise>red</xsl:otherwise>
      </xsl:choose>
    </xsl:attribute>
  </xsl:attribute-set>
  <xsl:template match="portfolio">
    <html>
      <head>
        <title>My Portfolio</title>
      </head>
      <body bgcolor="#FFFFFF" text="#000000">
        <h1>Portfolio</h1>
        <table border="1" cellpadding="2">
          <tbody>
            <tr>
              <th>Symbol</th>
              <th>Current</th>
              <th>Paid</th>
              <th>Qty</th>
              <th>Gain/Loss</th>
            </tr>
            <xsl:apply-templates/>
          </tbody>
        </table>
      </body>
    </html>
  </xsl:template>
  <xsl:template match="investment">
    <tr>
      <td><xsl:value-of select="symbol"/></td>
      <td><xsl:value-of select="current"/></td>
      <td><xsl:value-of select="paid"/></td>
      <td><xsl:value-of select="qty"/></td>
      <td>
        <font xsl:use-attribute-sets="gain-loss-font">
          <xsl:value-of select="format-number((current - paid) * qty, '#,##0.00')"/>
        </font>
      </td>
    </tr>
  </xsl:template>
</xsl:stylesheet>

Para una versión más clara sin requisitos de navegadores antiguos, sustituya el elemento font por el atributo style de HTML 4.0:

<xsl:attribute-set name="gain-loss-color">
  <xsl:attribute name="style">color:<xsl:text/>
    <xsl:choose>
      <xsl:when test="(current - paid) * qty &gt;= 0">black</xsl:when>
      <xsl:otherwise>red</xsl:otherwise>
    </xsl:choose>
  </xsl:attribute>
</xsl:attribute-set>
...
<xsl:template match="investment">
  <tr>
    <td><xsl:value-of select="symbol"/></td>
    <td><xsl:value-of select="current"/></td>
    <td><xsl:value-of select="paid"/></td>
    <td><xsl:value-of select="qty"/></td>
    <td xsl:use-attribute-sets="gain-loss-color">
      <xsl:value-of select="format-number((current - paid) * qty, '#,##0.00')"/>
    </td>
  </tr>
</xsl:template>

XSLT 2.0

La versión 2.0 aporta sobre todo la concisión de expresiones XPath frente a xsl:choose. Este es un fragmento reescrito:

<xsl:attribute-set name="gain-loss-font">
  <xsl:attribute name="color" select="if ((current - paid) * qty ge 0) then 'black' else 'red'"/>
</xsl:attribute-set>

Discusión

Como suele ocurrir en XSLT, hay varios enfoques. Puede poner la lógica de estilo dentro de la generación de tablas:

<xsl:template match="investment">
  <tr>
    <td><xsl:value-of select="symbol"/></td>
    <td><xsl:value-of select="current"/></td>
    <td><xsl:value-of select="paid"/></td>
    <td><xsl:value-of select="qty"/></td>
    <td>
      <font>
        <xsl:attribute name="color">
          <xsl:choose>
            <xsl:when test="(current - paid) * qty &gt;= 0">black</xsl:when>
            <xsl:otherwise>red</xsl:otherwise>
          </xsl:choose>
        </xsl:attribute>
        <xsl:value-of select="format-number((current - paid) * qty, '#,##0.00')"/>
      </font>
    </td>
  </tr>
</xsl:template>

La selección de color en línea puede aclarar el comportamiento inmediato, pero complica la tabla. Un ejemplo complejo puede calcular atributos style para muchos elementos. Mezclar estructura y estilo dificulta entenderlos y modificarlos.

Las referencias de elementos fijas limitan la reutilización. Traslade la lógica fuera del conjunto con plantillas y modos. Considere inversiones con distintos cálculos de beneficio:

<portfolio>
  <stock>
    <symbol>IBM</symbol>
    <current>72.70</current>
    <paid>65.00</paid>
    <qty>1000</qty>
  </stock>
  <stock>
    <symbol>JMAR</symbol>
    <current>1.90</current>
    <paid>5.10</paid>
    <qty>5000</qty>
  </stock>
  <stock>
    <symbol>DELL</symbol>
    <current>24.50</current>
    <paid>18.00</paid>
    <qty>100000</qty>
  </stock>
  <stock>
    <symbol>P</symbol>
    <current>57.33</current>
    <paid>63.00</paid>
    <qty>100</qty>
  </stock>
  <property>
    <address>123 Main St. Anytown NY</address>
    <paid>100000</paid>
    <appraisal>250000</appraisal>
  </property>
  <property>
    <address>13 Skunks Misery Dr. Stinksville NJ</address>
    <paid>200000</paid>
    <appraisal>50000</appraisal>
  </property>
</portfolio>

Para evitar dos conjuntos equivalentes, traslade su lógica a plantillas:

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <xsl:output method="html"/>
  <xsl:attribute-set name="gain-loss-font">
    <xsl:attribute name="color">
      <xsl:apply-templates select="." mode="gain-loss-font-color"/>
    </xsl:attribute>
  </xsl:attribute-set>
  <xsl:template match="stock" mode="gain-loss-font-color">
    <xsl:choose>
      <xsl:when test="(current - paid) * qty &gt;= 0">black</xsl:when>
      <xsl:otherwise>red</xsl:otherwise>
    </xsl:choose>
  </xsl:template>
  <xsl:template match="property" mode="gain-loss-font-color">
    <xsl:choose>
      <xsl:when test="appraisal - paid  &gt;= 0">black</xsl:when>
      <xsl:otherwise>red</xsl:otherwise>
    </xsl:choose>
  </xsl:template>
  ...
</xsl:stylesheet>

Quizá prefiera mantener colores y fuentes fuera de XSLT. Puede que un especialista en identidad visual decida cómo mostrar ganancias y pérdidas. Clasifique los elementos y delegue el estilo a una hoja separada:

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <xsl:output method="html"/>
  <xsl:attribute-set name="gain-loss">
    <xsl:attribute name="class">
      <xsl:apply-templates select="." mode="gain-loss"/>
    </xsl:attribute>
  </xsl:attribute-set>
  <xsl:template match="stock" mode="gain-loss">
    <xsl:choose>
      <xsl:when test="(current - paid) * qty &gt;= 0">gain</xsl:when>
      <xsl:otherwise>loss</xsl:otherwise>
    </xsl:choose>
  </xsl:template>
  <xsl:template match="property" mode="gain-loss">
    <xsl:choose>
      <xsl:when test="appraisal - paid  &gt;= 0">gain</xsl:when>
      <xsl:otherwise>loss</xsl:otherwise>
    </xsl:choose>
  </xsl:template>
  <xsl:template match="portfolio">
    <html>
      <head>
        <title>My Portfolio</title>
        <link rel="stylesheet" type="text/css" href="portfolio.css"/>
      </head>
      ...
  </xsl:template>
  <xsl:template match="stock">
    <tr>
      <td><xsl:value-of select="symbol"/></td>
      <td align="right"><xsl:value-of select="current"/></td>
      <td align="right"><xsl:value-of select="paid"/></td>
      <td align="right"><xsl:value-of select="qty"/></td>
      <td align="right" xsl:use-attribute-sets="gain-loss">
        <xsl:value-of select="format-number((current - paid) * qty, '#,##0.00')"/>
      </td>
    </tr>
  </xsl:template>
  <xsl:template match="property">
    <tr>
      <td><xsl:value-of select="address"/></td>
      <td align="right"><xsl:value-of select="paid"/></td>
      <td align="right"><xsl:value-of select="appraisal"/></td>
      <td align="right" xsl:use-attribute-sets="gain-loss">
        <xsl:value-of select="format-number(appraisal - paid, '#,##0.00')"/>
      </td>
    </tr>
  </xsl:template>
</xsl:stylesheet>

El especialista decide entonces el aspecto de <td class="gain"> y <td class="loss"> mediante portfolio.css, como se muestra.

Ejemplo: portfolio.css

td.gain
{
     color:black;
}

td.loss
{
     color:red;
     font-weight:700;
}

  

<< atrás

siguiente >>

 

 

 

volver arriba