Tecnologías XML / XSLT / Recetario XSLT / De XML a texto / Crear un informe en columnas
(Extracto de «XSLT Kochbuch» de Sal Mangano)
Problema
Quiere dar formato a datos para presentarlos en columnas.
Solución
Hay dos formas generales de distribuir XML en columnas: asignar distintos elementos o atributos a columnas separadas, o distribuir los elementos según su posición relativa.
Cree primero una plantilla para alinear el texto en una columna de anchura fija. Construya la rutina mostrada a continuación a partir de la plantilla str:dup creada en la receta Duplicar una cadena n veces.
Ejemplo: plantilla genérica para alinear texto: text.justify.xslt.
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:str="http://www.ora.com/XSLTCookbook/namespaces/strings" xmlns:text="http://www.ora.com/XSLTCookbook/namespaces/text" extension-element-prefixes="text">
<xsl:include href="../strings/str.dup.xslt"/>
<xsl:template name="text:justify">
<xsl:param name="value" />
<xsl:param name="width" select="10"/>
<xsl:param name="align" select=" 'left' "/>
<!-- Abschneiden, falls zu lang -->
<xsl:variable name="output" select="substring($value,1,$width)"/>
<xsl:choose>
<xsl:when test="$align = 'left'">
<xsl:value-of select="$output"/>
<xsl:call-template name="str:dup">
<xsl:with-param name="input" select=" ' ' "/>
<xsl:with-param name="count" select="$width - string-length($output)"/>
</xsl:call-template>
</xsl:when>
<xsl:when test="$align = 'right'">
<xsl:call-template name="str:dup">
<xsl:with-param name="input" select=" ' ' "/>
<xsl:with-param name="count" select="$width - string-length($output)"/>
</xsl:call-template>
<xsl:value-of select="$output"/>
</xsl:when>
<xsl:when test="$align = 'center'">
<xsl:call-template name="str:dup">
<xsl:with-param name="input" select=" ' ' "/>
<xsl:with-param name="count" select="floor(($width - string-length($output)) div 2)"/>
</xsl:call-template>
<xsl:value-of select="$output"/>
<xsl:call-template name="str:dup">
<xsl:with-param name="input" select=" ' ' "/>
<xsl:with-param name="count" select="ceiling(($width - string-length($output)) div 2)"/>
</xsl:call-template>
</xsl:when>
<xsl:otherwise>INVALID ALIGN</xsl:otherwise>
</xsl:choose>
</xsl:template>
</xsl:stylesheet>Con esta plantilla, producir columnas solo requiere definir el orden y la disposición de los datos. Los dos ejemplos siguientes lo hacen para los atributos person de people.xml. Una solución similar podría tratar la codificación mediante elementos de people-elem.xml.
Ejemplo: people-to-columns.xslt.
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:str="http://www.ora.com/XSLTCookbook/namespaces/strings" xmlns:text="http://www.ora.com/XSLTCookbook/namespaces/text">
<xsl:include href="text.justify.xslt"/>
<xsl:output method="text" />
<xsl:strip-space elements="*"/>
<xsl:template match="people">
Name | Alter | Geschlecht | Raucher |
----------------------------------------------------------
<xsl:apply-templates/>
</xsl:template>
<xsl:template match="person">
<xsl:call-template name="text:justify">
<xsl:with-param name="value" select="@name"/>
<xsl:with-param name="width" select="20"/>
</xsl:call-template>
<xsl:text>|</xsl:text>
<xsl:call-template name="text:justify">
<xsl:with-param name="value" select="@age"/>
<xsl:with-param name="width" select="8"/>
<xsl:with-param name="align" select=" 'right' "/>
</xsl:call-template>
<xsl:text>|</xsl:text>
<xsl:call-template name="text:justify">
<xsl:with-param name="value" select="@sex"/>
<xsl:with-param name="width" select="11"/>
<xsl:with-param name="align" select=" 'center' "/>
</xsl:call-template>
<xsl:text>|</xsl:text>
<xsl:call-template name="text:justify">
<xsl:with-param name="value" select="@smoker"/>
<xsl:with-param name="width" select="10"/>
<xsl:with-param name="align" select=" 'center' "/>
</xsl:call-template>
<xsl:text> </xsl:text>
</xsl:template>
</xsl:stylesheet>Ejemplo: salida.
|
|
|
|
|
|
|
|
----------------------------------------------------------------------- | |||||||
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
Transformar según la posición exige otro enfoque. Primero decida las columnas: utilice un parámetro y deje que el número de elementos determine las filas, o fije las filas y deje variar las columnas. Después decida cómo distribuir las posiciones. Las asignaciones más habituales son por filas (row-major) y por columnas (column-major). Por filas, el primer elemento va a la primera columna, el segundo a la segunda y así hasta llenar las columnas y comenzar otra fila. Por columnas, los primeros (N div Anzahl-der-Spalten) elementos van a la primera columna, los siguientes (N div Anzahl-der-Spalten) a la segunda, y así sucesivamente. Puede entenderse como una transposición de filas y columnas.
Cree dos plantillas para producir ambas disposiciones, como se muestra a continuación.
Ejemplo: text.matrix.xslt
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:text="http://www.ora.com/XSLTCookbook/namespaces/text" extension-element-prefixes="text">
<xsl:output method="text"/>
<xsl:include href="text.justify.xslt"/>
<xsl:template name="text:row-major">
<xsl:param name="nodes" select="/.."/>
<xsl:param name="num-cols" select="2"/>
<xsl:param name="width" select="10"/>
<xsl:param name="align" select=" 'left' "/>
<xsl:param name="gutter" select=" ' ' "/>
<xsl:if test="$nodes">
<xsl:call-template name="text:row">
<xsl:with-param name="nodes" select="$nodes[position() <= $num-cols]"/>
<xsl:with-param name="width" select="$width"/>
<xsl:with-param name="align" select="$align"/>
<xsl:with-param name="gutter" select="$gutter"/>
</xsl:call-template>
<!-- Verarbeiten der verbleibenden Zeilen -->
<xsl:call-template name="text:row-major">
<xsl:with-param name="nodes" select="$nodes[position() > $num-cols]"/>
<xsl:with-param name="num-cols" select="$num-cols"/>
<xsl:with-param name="width" select="$width"/>
<xsl:with-param name="align" select="$align"/>
<xsl:with-param name="gutter" select="$gutter"/>
</xsl:call-template>
</xsl:if>
</xsl:template>
<xsl:template name="text:col-major">
<xsl:param name="nodes" select="/.."/>
<xsl:param name="num-cols" select="2"/>
<xsl:param name="width" select="10"/>
<xsl:param name="align" select=" 'left' "/>
<xsl:param name="gutter" select=" ' ' "/>
<xsl:if test="$nodes">
<xsl:call-template name="text:row">
<xsl:with-param name="nodes" select="$nodes[(position() - 1) mod ceiling(last() div $num-cols) = 0]"/>
<xsl:with-param name="width" select="$width"/>
<xsl:with-param name="align" select="$align"/>
<xsl:with-param name="gutter" select="$gutter"/>
</xsl:call-template>
<!-- Verarbeiten der verbleibenden Zeilen -->
<xsl:call-template name="text:col-major">
<xsl:with-param name="nodes" select="$nodes[(position() - 1) mod ceiling(last() div $num-cols) != 0]"/>
<xsl:with-param name="num-cols" select="$num-cols"/>
<xsl:with-param name="width" select="$width"/>
<xsl:with-param name="align" select="$align"/>
<xsl:with-param name="gutter" select="$gutter"/>
</xsl:call-template>
</xsl:if>
</xsl:template>
<xsl:template name="text:row">
<xsl:param name="nodes" select="/.."/>
<xsl:param name="width" select="10"/>
<xsl:param name="align" select=" 'left' "/>
<xsl:param name="gutter" select=" ' ' "/>
<xsl:for-each select="$nodes">
<xsl:call-template name="text:justify">
<xsl:with-param name="value" select="."/>
<xsl:with-param name="width" select="$width"/>
<xsl:with-param name="align" select="$align"/>
</xsl:call-template>
<xsl:value-of select="$gutter"/>
</xsl:for-each>
<xsl:text>
</xsl:text>
</xsl:template>
</xsl:stylesheet>Los tres ejemplos siguientes utilizan estas plantillas.
Ejemplo: entrada.
<numbers>
<number>10</number>
<number>3.5</number>
<number>4.44</number>
<number>77.7777</number>
<number>-8</number>
<number>1</number>
<number>444</number>
<number>1.1234</number>
<number>7.77</number>
<number>3.1415927</number>
<number>10</number>
<number>9</number>
<number>8</number>
<number>7</number>
<number>666</number>
<number>5555</number>
<number>-4444444</number>
<number>22.33</number>
<number>18</number>
<number>36.54</number>
<number>43</number>
<number>99999</number>
<number>999999</number>
<number>9999999</number>
<number>32</number>
<number>64</number>
<number>-64.0001</number>
</numbers>Ejemplo: hoja de estilo.
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:text="http://www.ora.com/XSLTCookbook/namespaces/text">
<xsl:output method="text" />
<xsl:include href="text.matrix.xslt"/>
<xsl:template match="numbers">
Fünf Spalten mit Zahlen in zeilenweiser Anordnung:
<xsl:text/>
<xsl:call-template name="text:row-major">
<xsl:with-param name="nodes" select="number"/>
<xsl:with-param name="align" select=" 'right' "/>
<xsl:with-param name="num-cols" select="5"/>
<xsl:with-param name="gutter" select=" ' | ' "/>
</xsl:call-template>
Fünf Spalten mit Zahlen in spaltenweiser Anordnung:
<xsl:text/>
<xsl:call-template name="text:col-major">
<xsl:with-param name="nodes" select="number"/>
<xsl:with-param name="align" select=" 'right' "/>
<xsl:with-param name="num-cols" select="5"/>
<xsl:with-param name="gutter" select=" ' | ' "/>
</xsl:call-template>
</xsl:template>
</xsl:stylesheet>Ejemplo: salida.
Fünf Spalten mit Zahlen in zeilenweiser Anordnung:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
Fünf Spalten mit Zahlen in spaltenweiser Anordnung:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| |
|
|
|
| |
|
|
|
|
XSLT 2.0
La principal mejora en XSLT 2.0 consiste en convertir la plantilla text:justify en una función, utilizando XPath 2.0 para hacerla más concisa. Utilice la función string-join con una expresión for para construir una función de relleno que inserte la cantidad adecuada de espacio en blanco. Sobrecargue también text:justify para simular un parámetro de alineación predeterminado:
<xsl:function name="text:dup" as="xs:string">
<xsl:param name="input" as="xs:string"/>
<xsl:param name="count" as="xs:integer"/>
<xsl:sequence select="string-join(for $i in 1 to $count return $input, '')"/>
</xsl:function>
<xsl:function name="text:justify" as="xs:string">
<xsl:param name="value" as="xs:string"/>
<xsl:param name="width" as="xs:integer" />
<xsl:sequence select="text:justify($value, $width, 'left')"/>
</xsl:function>
<xsl:function name="text:justify" as="xs:string">
<xsl:param name="value" as="xs:string"/>
<xsl:param name="width" as="xs:integer" />
<xsl:param name="align" as="xs:string" />
<!-- Abschneiden, falls zu lang -->
<xsl:variable name="output" select="substring($value,1,$width)" as="xs:string"/>
<xsl:variable name="offset" select="$width - string-length($output)" as="xs:integer"/>
<xsl:choose>
<xsl:when test="$align = 'left'">
<xsl:value-of select="concat($output, text:dup(' ', $offset))"/>
</xsl:when>
<xsl:when test="$align = 'right'">
<xsl:value-of select="concat(text:dup(' ', $offset), $output)"/>
</xsl:when>
<xsl:when test="$align = 'center'">
<xsl:variable name="before" select="$offset idiv 2"/>
<xsl:variable name="after" select="$before + $offset mod 2"/>
<xsl:value-of select="concat(text:dup(' ', $before), $output,text:dup(' ', $after))"/>
</xsl:when>
<xsl:otherwise>INVALID ALIGN</xsl:otherwise>
</xsl:choose>
</xsl:function>Discusión
Convertir en columnas datos codificados mediante elementos o atributos se parece al problema de datos delimitados de la receta Exportar XML a datos delimitados. La diferencia principal es el destinatario: máquinas para datos delimitados, personas aquí. Las personas pueden ser más exigentes con la alineación y las ayudas visuales. Puede utilizarse el mismo enfoque genérico dirigido por datos, pero requiere más información sobre cada columna. Los tres ejemplos siguientes muestran la solución basada en atributos.
Ejemplo: generic-attr-to-columns.xslt
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:str="http://www.ora.com/XSLTCookbook/namespaces/strings" xmlns:text="http://www.ora.com/XSLTCookbook/namespaces/text">
<xsl:include href="text.justify.xslt"/>
<xsl:param name="gutter" select=" ' ' "/>
<xsl:output method="text"/>
<xsl:strip-space elements="*"/>
<xsl:variable name="columns" select="/.."/>
<xsl:template match="/">
<xsl:for-each select="$columns">
<xsl:call-template name="text:justify" >
<xsl:with-param name="value" select="@name"/>
<xsl:with-param name="width" select="@width"/>
<xsl:with-param name="align" select=" 'left' "/>
</xsl:call-template>
<xsl:value-of select="$gutter"/>
</xsl:for-each>
<xsl:text>
</xsl:text>
<xsl:for-each select="$columns">
<xsl:call-template name="str:dup">
<xsl:with-param name="input" select=" '-' "/>
<xsl:with-param name="count" select="@width"/>
</xsl:call-template>
<xsl:call-template name="str:dup">
<xsl:with-param name="input" select=" '-' "/>
<xsl:with-param name="count" select="string-length($gutter)"/>
</xsl:call-template>
</xsl:for-each>
<xsl:text>
</xsl:text>
<xsl:apply-templates/>
</xsl:template>
<xsl:template match="/*/*">
<xsl:variable name="row" select="."/>
<xsl:for-each select="$columns">
<xsl:variable name="value">
<xsl:apply-templates select="$row/@*[local-name(.)=current()/@attr]" mode="text:map-col-value"/>
</xsl:variable>
<xsl:call-template name="text:justify" >
<xsl:with-param name="width" select="@width"/>
<xsl:with-param name="align" select="@align"/>
</xsl:call-template>
<xsl:value-of select="$gutter"/>
</xsl:for-each>
<xsl:text>
</xsl:text>
</xsl:template>
<xsl:template match="@*" mode="text:map-col-value">
<xsl:value-of select="."/>
</xsl:template>
</xsl:stylesheet>Ejemplo: people-to-cols-using-generic.xslt
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:str="http://www.ora.com/XSLTCookbook/namespaces/strings" xmlns:text="http://www.ora.com/XSLTCookbook/namespaces/text">
<xsl:import href="generic-attr-to-columns.xslt"/>
<!--Definiert die Zuordnung von Attributen zu Spalten -->
<xsl:variable name="columns" select="document('')/*/text:column"/>
<text:column name="Name" width="20" align="left" attr="name"/>
<text:column name="Alter" width="8" align="right" attr="age"/>
<text:column name="Geschlecht" width="12" align="left" attr="sex"/>
<text:column name="Raucher" width="9" align="left" attr="smoker"/>
<!-- Verarbeitet eigene Attributzuordnungen -->
<xsl:template match="@sex" mode="text:map-col-value">
<xsl:choose>
<xsl:when test=".='m'">männlich</xsl:when>
<xsl:when test=".='w'">weiblich</xsl:when>
<xsl:otherwise>error</xsl:otherwise>
</xsl:choose>
</xsl:template>
</xsl:stylesheet>Ejemplo: salida (con el parámetro separador « | »).
|
|
|
|
|
|
|
|
----------------------------------------------------------------------- | |||||||
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
Copyright © 2006 O'Reilly Verlag GmbH & Co. KG
Puede imprimir la versión en línea para uso privado.
Para cualquier otro uso, este capítulo de «XSLT Kochbuch» está sujeto a las mismas condiciones que la edición encuadernada. La obra y todas sus partes están protegidas por derechos de autor. Todos los derechos reservados, incluidos reproducción, traducción, microfilmación, almacenamiento y tratamiento en sistemas electrónicos.
O'Reilly Verlag GmbH & Co. KG, Balthasarstraße 81, 50670 Köln, kommentar(at)oreilly.de