Tecnologías XML / XSLT / Recetario XSLT / Transformar XML en HTML / XSLT como lenguaje de estilo

(Extracto de «XSLT Kochbuch» de Sal Mangano)

Problema

Desea que el navegador aplique dinámicamente estilo a un documento XML para convertirlo en HTML.

Solución

Basta con una solución XSLT 1.0. Este ejemplo publica en HTML parte de un documento DocBook mediante una hoja XSLT. La fuente es parte de este capítulo:

<?xml version="1.0" encoding="utf-8"?>
<?xml-stylesheet type="application/xml" href="chapter.xsl"?>
<chapter label="8">
  <chapterinfo>
    <author>
      <surname>Mangano</surname>
      <firstname>Sal</firstname>
    </author>
    <copyright>
      <year>2002</year>
      <holder>O'Reilly</holder>
    </copyright>
  </chapterinfo>
  <title>XML in HTML transformieren</title>
  <epigraph>
    <para>Mich hat es überrascht, dass die Leute klaglos bereit waren, umständlich HTML einzugeben.</para>
    <attribution>Tim Berners-Lee</attribution>
  </epigraph>
  <sect1>
    <title>XSLT als Styling-Sprache verwenden</title>
    <sect2>
      <title>Problem</title>
      <para>Sie möchten, dass der Browser dynamisch einen Stil auf ein XML-Dokument anwendet, um daraus HTML zu machen.</para>
    </sect2>
    <sect2>
      <title>Lösung</title>
      <para>Es wird lediglich eine XSLT 1.0-Lösung benötigt. Es folgt ein Beispiel für die Veröffentlichung eines Teilaussschnitts eines DocBook-Dokuments in HTML, bei der ein XSLT-Stylesheet verwendet wird. Als Quelldokument dient ein Teil dieses Kapitels.</para>
    </sect2>
    <sect2>
      <title>Diskussion</title>
      <para>DocBook ist eine dokumentorientierte DTD, mit der Sie Dokumentinhalte erstellen und in einer präsentationsunabhängigen Form speichern können, in der die logische Struktur des Inhalts festgehalten wird. Das Schöne beim Erstellen von Dokumenten (besonders bei technischen Dokumenten) in dieser Form ist, dass Sie mit XSLT einen einzigen Inhalt in mehrere verschiedene Ausgabeformate wie HTML, PDF, Microsoft-Hilfsdateien und Unix-Manpages transformieren können. Auch wenn es bei diesem Buchbeispiel konkret um DocBook geht, lassen sich die gleichen Techniken ebenso gut bei anderen Dokumentschemata verwenden, seien es welche, die als Public-Domain verfügbar sind, oder solche, die Sie sich selbst ausgedacht haben.</para>
    </sect2>
  </sect1>
</chapter>

La segunda línea contiene una instrucción de procesamiento, concretamente xml-stylesheet. Indica al navegador que aplique esta hoja al XML y muestre el resultado en lugar del XML. Esto solo funciona en versiones actuales de los navegadores:

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <xsl:output method="html"/>
  <xsl:template match="/">
    <html>
      <head>
        <xsl:apply-templates mode="head"/>
      </head>
      <!-- Vielleicht möchten Sie lieber Styles in einem CSS-Style-Element verwenden, als sie fest zu kodieren, wie ich es hier mache -->
      <body style="margin-left: 100; margin-right: 100; margin-top: 50; margin-bottom: 50">
        <xsl:apply-templates/>
        <xsl:apply-templates select="chapter/chapterinfo/*" mode="copyright"/>
      </body>
    </html>
  </xsl:template>
  <!-- Head -->
  <xsl:template match="chapter" mode="head">
    <xsl:apply-templates select="chapterinfo" mode="head" />
    <xsl:apply-templates select="title" mode="head" />
  </xsl:template>
  <xsl:template match="chapter/title" mode="head">
    <title>
      <xsl:value-of select="."/>
    </title>
  </xsl:template>
  <xsl:template match="author" mode="head">
    <meta name="author" content="{concat(firstname,' ', surname)}"/>
  </xsl:template>
  <xsl:template match="copyright" mode="head">
    <meta name="copyright" content="{concat(holder,' ',year)}"/>
  </xsl:template>
  <xsl:template match="text( )" mode="head"/>
  <!-- Body -->
  <xsl:template match="chapter">
    <div align="right" style="font-size: 48pt; font-family: Times serif; font-weight: bold; padding-bottom: 10; color: red">
      <xsl:value-of select="@label"/>
    </div>
    <xsl:apply-templates/>
  </xsl:template>

  <xsl:template match="chapter/title">
    <div align="right" style="font-size: 24pt; font-family: Times serif; padding-bottom: 150; color:red">
      <xsl:value-of select="."/>
    </div>
  </xsl:template>

  <xsl:template match="epigraph/para">
    <div align="right" style="font-size: 10pt; font-family: Times serif; font-style: italic; padding-top: 4; padding-bottom: 4">
      <xsl:value-of select="."/>
    </div>
  </xsl:template>
  <xsl:template match="epigraph/attribution">
    <div align="right" style="font-size: 10pt; font-family: Times serif; padding-top: 4; padding-bottom: 4">
      <xsl:value-of select="."/>
    </div>
  </xsl:template>
  <xsl:template match="sect1">
    <h1 style="font-size: 18pt; font-family: Times serif; font-weight: bold">
      <xsl:value-of select="title"/>
    </h1>
    <xsl:apply-templates/>
  </xsl:template>
  <xsl:template match="sect2">
    <h2 style="font-size: 14pt; font-family: Times serif; font-weight: bold">
      <xsl:value-of select="title"/>
    </h2>
    <xsl:apply-templates/>
  </xsl:template>
  <xsl:template match="para">
    <p style="font-size: 12pt; font-family: Times serif">
      <xsl:value-of select="."/>
    </p>
  </xsl:template>
  <xsl:template match="text( )"/>
  <xsl:template match="copyright" mode="copyright">
    <div style="font-size: 10pt; font-family: Times serif; padding-top: 100">
      <xsl:text>Copyright </xsl:text>
      <xsl:value-of select="holder"/>
      <xsl:text> </xsl:text>
      <xsl:value-of select="year"/>
      <xsl:text>. All rights reserved.</xsl:text>
    </div>
  </xsl:template>
  <xsl:template match="*" mode="copyright"/>
</xsl:stylesheet>

El navegador recibe finalmente este HTML:

<html>
  <head>
    <meta name="author" content="Sal Mangano">
    <meta name="copyright" content="O'Reilly 2002">
    <title>XML in HTML transformieren</title>
  </head>
  <body style="margin-left:100;margin-right:100;margin-top:50;margin-bottom:50">
    <div align="right" style="font-size : 48pt; font-family: Times serif; font-weight : bold; padding-bottom:10; color:red">8</div>
    <div align="right" style="font-size : 24pt; font-family: Times serif; padding-bottom:150; color:red">XML to HTML</div>
    <div align="right" style="font-size : 10pt; font-family: Times serif; font-style : italic; padding-top:4; padding-bottom:4">Mich hat es überrascht, dass die Leute klaglos bereit waren, umständlich HTML einzugeben.</div>
    <div align="right" style="font-size : 10pt; font-family: Times serif; padding-top:4; padding-bottom:4">Tim Berners-Lee</div>
    <h1 style="font-size : 18pt; font-family: Times serif; font-weight : bold">XSLT als Styling-Sprache verwenden</h1>
    <h2 style="font-size : 14pt; font-family: Times serif; font-weight : bold">Problem</h2>
    <p style="font-size : 12pt; font-family: Times serif">Sie möchten, dass der Browser dynamisch einen Stil auf ein XML-Dokument anwendet, um daraus HTML zu machen.</p>
    <h2 style="font-size : 14pt; font-family: Times serif; font-weight : bold">Lösung</h2>
    <p style="font-size : 12pt; font-family: Times serif">Es wird lediglich eine XSLT 1.0-Lösung benötigt. Es folgt ein Beispiel für die Veröffentlichung eines Teilausschnitts eines DocBook-Dokuments in HTML, bei der ein XSLT-Stylesheet verwendet wird. Die Quelle dieses Dokuments ist Teil dieses Kapitels:</p>
    <h2 style="font-size : 14pt; font-family: Times serif; font-weight : bold">Discussion</h2>
    <p style="font-size : 12pt; font-family: Times serif">DocBook ist eine dokumentorientierte DTD, mit der Sie Dokumentinhalte erstellen und in einer präsentationsunabhängigen Form speichern können, in der die logische Struktur des Inhalts festgehalten wird. Das Schöne beim Erstellen von Dokumenten (besonders bei technischen Dokumenten) in dieser Form ist, dass Sie mit XSLT einen einzigen Inhalt in mehrere verschiedene Ausgabeformate wie HTML, PDF, Microsoft-Hilfsdateien und Unix-Manpages transformieren können. Auch wenn es bei diesem Buchbeispiel konkret um DocBook geht, lassen sich die gleichen Techniken ebenso gut bei anderen Dokumentschemata verwenden, seien es welche, die als Public-Domain verfügbar sind, oder solche, die Sie sich selbst ausgedacht haben.</p>
    <div style="font-size : 10pt; font-family: Times serif; padding-top : 100">Copyright O'Reilly 2002. All rights reserved.</div>
  </body>
</html>

Discusión

DocBook es una DTD documental que permite crear y guardar contenido independientemente de su presentación, conservando la estructura lógica. Resulta especialmente útil para documentación técnica: XSLT transforma una fuente en HTML, PDF, ayuda Microsoft o páginas de manual Unix. Estas técnicas también sirven para otros esquemas públicos o personalizados.

Utilizar un subconjunto de DocBook hacía cómoda una hoja monolítica. Una solución de producción modularizaría el tratamiento de elementos en hojas y plantillas separadas que usaran modos.

Un inconveniente es el estilo fijo en el código. Como los navegadores actuales suelen admitir Cascading Stylesheets (CSS), es mejor confiar la transformación a XSLT y el estilo a CSS.

La estructura básica permanece, pero sustituya los atributos codificados de forma fija style por atributos class que referencien una hoja llamada style.css, añadida al elemento HTML head:

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <xsl:output method="html"/>
  <xsl:template match="/">
    <html>
      <head>
        <xsl:apply-templates mode="head"/>
        <link href="style.css" rel="stylesheet" type="text/css"/>
      </head>
      <body>
        <xsl:apply-templates/>
        <xsl:apply-templates select="chapter/chapterinfo/*" mode="copyright"/>
      </body>
    </html>
  </xsl:template>
  <!-- Head -->
  <xsl:template match="chapter" mode="head">
    <xsl:apply-templates select="chapterinfo" mode="head" />
    <xsl:apply-templates select="title" mode="head" />
  </xsl:template>
  <xsl:template match="chapter/title" mode="head">
    <title>
      <xsl:value-of select="."/>
    </title>
  </xsl:template>
  <xsl:template match="author" mode="head">
    <meta name="author" content="{concat(firstname,' ', surname)}"/>
  </xsl:template>
  <xsl:template match="copyright" mode="head">
    <meta name="copyright" content="{concat(holder,' ',year)}"/>
  </xsl:template>
  <xsl:template match="text( )" mode="head"/>
  <!-- Body -->
  <xsl:template match="chapter">
    <div class="chapter">
      <xsl:value-of select="@label"/>
    </div>
    <xsl:apply-templates/>
  </xsl:template>
  <xsl:template match="chapter/title">
    <div class="title">
      <xsl:value-of select="."/>
    </div>
  </xsl:template>
  <xsl:template match="epigraph/para">
    <div class="epigraph">
      <xsl:value-of select="."/>
    </div>
  </xsl:template>
  <xsl:template match="epigraph/attribution">
    <div class="epigraph-attribution">
      <xsl:value-of select="."/>
    </div>
  </xsl:template>
  <xsl:template match="sect1">
    <h1>
      <xsl:value-of select="title"/>
    </h1>
    <xsl:apply-templates/>
  </xsl:template>
  <xsl:template match="sect2">
    <h2>
      <xsl:value-of select="title"/>
    </h2>
    <xsl:apply-templates/>
  </xsl:template>
  <xsl:template match="para">
    <p class="para">
      <xsl:value-of select="."/>
    </p>
  </xsl:template>
  <xsl:template match="text( )"/>
  <xsl:template match="copyright" mode="copyright">
    <div class="copyright">
      <xsl:text>Copyright </xsl:text>
      <xsl:value-of select="holder"/>
      <xsl:text> </xsl:text>
      <xsl:value-of select="year"/>
      <xsl:text>. All rights reserved.</xsl:text>
    </div>
  </xsl:template>
  <xsl:template match="*" mode="copyright"/>
</xsl:stylesheet>

Un CSS es simplemente un archivo ASCII (style.css) que sigue unas convenciones sencillas:

body
{
   margin-left:100;
   margin-right:100;
   margin-top:50;
   margin-bottom:50;
   font-family: Times serif;
   font-size : 12pt;
   color:black;
}

div.chapter
{
   text-align:right;
   font-size : 48pt;
   font-weight: bold;
   padding-bottom:10;
   color:red;
}

div.title
{
   font-size : 24pt;
   font-family: Times serif;
   padding-bottom:150;
   color:red"
}

div.epigraph
{
   font-style:: italic;
}

div.epigraph, div.epigraph-attribution
{
   text-align: right;
   font-size : 10pt;
   padding-top: 4;
   padding-bottom: 4;
}

h1
{
   font-size : 18pt;
   font-weight : bold;
}

h2
{
   font-size : 14pt;
   font-weight : bold";
}

Si no conoce CSS, encontrará una buena introducción en W3Schools. También recomiendo Cascading Style Sheets – Das umfassende Handbuch de Eric Meyer (O’Reilly, 2004). Existen muchas herramientas para CSS. Me gusta Macromedia Dreamweaver MX, aunque quizá sea excesivo si solo necesita un editor CSS.

Véase también

La mejor fuente sobre DocBook es Docbook.org. Norman Walsh desarrolló hojas de código abierto que convierten DocBook a muchos formatos de publicación. Están en DocBookXSLStylesheets.

  

<< atrás

siguiente >>

 

 

 

volver arriba