Tecnologías XML / XSLT / Recetario XSLT / Convertir XML en SVG / Crear diagramas de árbol

(Extracto de «XSLT Kochbuch» de Sal Mangano)

Problema

Quiere representar la jerarquía de los datos como un árbol.

Solución

Esta sección presenta dos algoritmos de disposición de árboles. Ninguno es el más sofisticado, pero ambos producen resultados útiles.

Si todos los árboles fueran equilibrados, bastaría dividir el espacio horizontal por los nodos de cada nivel y el vertical por el número de niveles. En realidad debe dividirse por el número de nodos más 1 para evitar un error de desfase de una unidad, llamado fencepost error. Como los árboles reales son menos simétricos, el algoritmo debe considerar el ancho de cada rama.

El primer método recorre el árbol una vez y añade atributos de seguimiento al SVG resultante. Estos atributos se colocan en un espacio de nombres para evitar conflictos con los atributos SVG:

<?xml version="1.0" encoding="UTF-8"?>
<!-- version 1.1 ist erloschen, aktiviert aber in Saxon die Eigenschaft xsl:script. -->
<xsl:stylesheet version="1.1" xmlns:emath="http://www.exslt.org/math" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:tree="http://www.ora.com/XSLTCookbook/ns/tree" xmlns:Math="java:java.lang.Math" extension-element-prefixes="Math" exclude-result-prefixes="Math emath">
  <xsl:script implements-prefix="Math" xmlns:Math="java:java.lang.Math" language="java" src="java:java.lang.Math"/>
  <xsl:include href="../math/math.max.xslt"/>
  <xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes" doctype-public="-//W3C//DTD SVG 1.0/EN" doctype-system="http://www.w3.org/TR/2001/REC-SVG-20010904/DTD/svg10.dtd"/>
  <!-- Diese Parameter steuern die Ausdehnung des Baums und seiner Knoten -->
  <xsl:variable name="width" select="500"/>
  <xsl:variable name="height" select="500"/>
  <xsl:variable name="nodeWidth" select="2"/>
  <xsl:variable name="nodeHeight" select="1"/>
  <xsl:variable name="horzSpace" select="0.5"/>
  <xsl:variable name="vertSpace" select="1"/>
  <xsl:template match="/">
    <svg width="{$width}" height="{$height}">
      <!-- Halte den Unterbaum dieses Knotens in einer Variablen fest -->
      <xsl:variable name="subTree">
        <xsl:apply-templates/>
      </xsl:variable>
      <!-- maxPos ist das Maximum der entferntesten X- oder Y-Koordinate, die beim Rendern eines Knotens benutzt wird. -->
      <xsl:variable name="maxPos" select="Math:max(number($subTree/g/@tree:MAXX), number($subTree/g/@tree:MAXY))"/>
      <xsl:variable name="maxDim" select="Math:max($width,$height)"/>
      <!-- Wir skalieren den Baum, damit alle Knoten ins Koordinatensystem passen. -->
      <g transform="scale({$maxDim div ($maxPos + 1)})">
      <!-- Verwenden Sie exsl:node-set($subTree), falls Ihr XSLT-Prozessor die Version 1.0 hat. -->
        <xsl:copy-of select="$subTree/g/*"/>
      </g>
    </svg>
  </xsl:template>
  <!-- Das passt auf alle Knoten, die keine Blätter sind. -->
  <xsl:template match="*[*]">
    <xsl:variable name="subTree">
      <xsl:apply-templates/>
    </xsl:variable>
    <!-- Positioniere diesen Knoten horizontal abhängig von der mittleren Position seiner Kindknoten -->
    <xsl:variable name="thisX" select="sum($subTree/*/@tree:THISX) div count($subTree/*)"/>
    <xsl:variable name="maxX" select="$subTree/*[last( )]/@tree:MAXX"/>
    <!-- Positioniere diesen Knoten vertikal abhängig von seiner Tiefe -->
    <xsl:variable name="thisY" select="($vertSpace + $nodeHeight) * count(ancestor-or-self::*)"/>
    <xsl:variable name="maxY">
      <xsl:call-template name="emath:max">
        <!-- Verwenden Sie exsl:node-set($subTree), falls Ihr XSLT-Prozessor die Version 1.0 hat. -->
        <xsl:with-param name="nodes" select="$subTree/*/@tree:MAXY"/>
      </xsl:call-template>
    </xsl:variable>
    <!-- Wir platzieren den Elternknoten und seine Kindknoten sowie die Verbindungen in eine Gruppe. Außerdem fügen wir zur Gruppe ein paar Verwaltungsattribute hinzu, um im Baum Information nach oben weitergeben zu können. -->
    <g tree:THISX="{$thisX}" tree:MAXX="{$maxX}" tree:MAXY="{$maxY}">
      <rect x="{$thisX - $nodeWidth}" y="{$thisY - $nodeHeight}" width="{$nodeWidth}" height="{$nodeHeight}" style="fill: none; stroke: black; stroke-width:0.1"/>
      <!-- Zeichne eine Verbindungslinie zwischen dem aktuellen Knoten und dessen Kindknoten -->
      <xsl:call-template name="drawConnections">
        <xsl:with-param name="xParent" select="$thisX - $nodeWidth"/>
        <xsl:with-param name="yParent" select="$thisY - $nodeHeight"/>
        <xsl:with-param name="widthParent" select="$nodeWidth"/>
        <xsl:with-param name="heightParent" select="$nodeHeight"/>
        <xsl:with-param name="children" select="$subTree/g/rect"/>
      </xsl:call-template>
      <!-- Kopiere das SVG des Unterbaums -->
      <xsl:copy-of select="$subTree"/>
    </g>
  </xsl:template>
  <!-- Das passt auf alle Blattknoten -->
  <xsl:template match="*">
    <!-- Positioniere Blattknoten horizontal abhängig von der Anzahl der vorherigen Blattknoten -->
    <xsl:variable name="maxX" select="($horzSpace + $nodeWidth) * (count(preceding::*[not(child::*)] ) + 1)"/>

Puede utilizar count(ancestor-or-self::*) para obtener cada vez el nivel o profundidad. También puede transmitir el nivel actual mediante un parámetro en lugar de recalcularlo:

    <!-- Positioniere diesen Knoten vertikal abhängig von seiner Tiefe -->
    <xsl:variable name="maxY" select="($vertSpace + $nodeHeight) * count(ancestor-or-self::*) "/>
    <g tree:THISX="{$maxX}" tree:MAXX="{$maxX}" tree:MAXY="{$maxY}">
      <rect x="{$maxX - $nodeWidth}" y="{$maxY - $nodeHeight}" width="{$nodeWidth}" height="{$nodeHeight}" style="fill: none; stroke: black; stroke-width:0.1;"/>
    </g>
  </xsl:template>
  <!-- Überschreiben Sie das im importierenden Stylesheet, wenn Sie gerade oder eigene Verbindungslinien haben möchten. -->
  <xsl:template name="drawConnections">
    <xsl:param name="xParent"/>
    <xsl:param name="yParent"/>
    <xsl:param name="widthParent"/>
    <xsl:param name="heightParent"/>
    <xsl:param name="children"/>
    <xsl:call-template name="drawSquareConnections">
      <xsl:with-param name="xParent" select="$xParent"/>
      <xsl:with-param name="yParent" select="$yParent"/>
      <xsl:with-param name="widthParent" select="$widthParent"/>
      <xsl:with-param name="heightParent" select="$heightParent"/>
      <xsl:with-param name="children" select="$children"/>
    </xsl:call-template>
  </xsl:template>
  <!-- Gerade Verbindungen nehmen den kürzesten Pfad vom Zentrum des unteren Elternknotenteils zum Zentrum des oberen Kindknotenteils. -->
  <xsl:template name="drawStraightConnections">
    <xsl:param name="xParent"/>
    <xsl:param name="yParent"/>
    <xsl:param name="widthParent"/>
    <xsl:param name="heightParent"/>
    <xsl:param name="children"/>
    <xsl:for-each select="$children">
      <line x1="{$xParent + $widthParent div 2}" y1="{$yParent + $heightParent}" x2="{@x + $nodeWidth div 2}" y2="{@y}" style="stroke: black; stroke-width:0.1;"/>
    </xsl:for-each>
  </xsl:template>
  <!-- Rechteckige Verbindungen nehmen den kürzesten Pfad vom Zentrum des unteren Elternknotenteils zum Zentrum des oberen Kindknotenteils und bestehen nur aus horizontalen und vertikalen Linien. -->
  <xsl:template name="drawSquareConnections">
    <xsl:param name="xParent"/>
    <xsl:param name="yParent"/>
    <xsl:param name="widthParent"/>
    <xsl:param name="heightParent"/>
    <xsl:param name="children"/>
    <xsl:variable name="midY" select="($children[1]/@y + ($yParent + $heightParent)) div 2"/>
    <!-- vertikale Linie vom Elternknoten -->
    <line x1="{$xParent + $widthParent div 2}" y1="{$yParent + $heightParent}" x2="{$xParent + $widthParent div 2}" y2="{$midY}" style="stroke: black; stroke-width:0.1;"/>
    <!-- horizontale Linie in der Mitte -->
    <line x1="{$children[1]/@x + $children[1]/@width div 2}" y1="{$midY}" x2="{$children[last( )]/@x + $children[1]/@width div 2}" y2="{$midY}" style="stroke: black; stroke-width:0.1;"/>
    <!-- vertikale Linien zu den Kindknoten -->
    <xsl:for-each select="$children">
      <line x1="{@x + $nodeWidth div 2}" y1="{$midY}" x2="{@x + $nodeWidth div 2}" y2="{@y}" style="stroke: black; stroke-width:0.1;"/>
    </xsl:for-each>
  </xsl:template>
</xsl:stylesheet>

Esta hoja dibuja la estructura de cualquier documento XML como un árbol. La figura muestra el resultado con una entrada sencilla.

Estructura XML convertida a SVG

Figura: estructura XML convertida a SVG.

El primer algoritmo sitúa horizontalmente los padres en la posición media de sus hijos. En árboles desequilibrados, la raíz queda descentrada. El siguiente corrige esto y evita atributos ajenos en SVG, pero necesita dos pasadas:

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.1" xmlns:emath="http://www.exslt.org/math" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:tree="http://www.ora.com/XSLTCookbook/ns/tree" xmlns:Math="java:java.lang.Math" extension-element-prefixes="Math" exclude-result-prefixes="Math emath">
  <xsl:script implements-prefix="Math" xmlns:Math="java:java.lang.Math" language="java" src="java:java.lang.Math"/>
  <xsl:include href="../math/math.max.xslt"/>
  <xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes" doctype-public="-//W3C//DTD SVG 1.0/EN" doctype-system="http://www.w3.org/TR/2001/REC-SVG-20010904/DTD/svg10.dtd"/>
  <xsl:variable name="width" select="500"/>
  <xsl:variable name="height" select="500"/>
  <xsl:variable name="nodeWidth" select="2"/>
  <xsl:variable name="nodeHeight" select="1"/>
  <xsl:variable name="horzSpace" select="0.5"/>
  <xsl:variable name="vertSpace" select="1"/>
  <xsl:variable name="strokeWidth" select="0.1"/>
  <xsl:template match="/">
    <!-- 1. Durchgang kopiert die Eingabe mit hinzugefügten Verwaltungsattributen -->
    <xsl:variable name="treeWithLayout">
      <xsl:apply-templates mode="layout"/>
    </xsl:variable>
    <xsl:variable name="maxPos" select="Math:max($treeWithLayout/*/@tree:WEIGHT * ($nodeWidth + $horzSpace), $treeWithLayout/*/@tree:MAXDEPTH * ($nodeHeight + $vertSpace))"/>
    <xsl:variable name="maxDim" select="Math:max($width,$height)"/>
    <xsl:variable name="scale" select="$maxDim div ($maxPos + 1)"/>
    <!-- 2. Durchgang erzeugt SVG -->
    <svg height="{$height}" width="{$width}">
      <g transform="scale({$scale})">
        <xsl:apply-templates select="$treeWithLayout/*" mode="draw">
          <xsl:with-param name="x" select="0"/>
          <xsl:with-param name="y" select="0"/>
          <xsl:with-param name="width" select="$width div $scale"/>
          <xsl:with-param name="height" select="$height div $scale"/>
        </xsl:apply-templates>
      </g>
    </svg>
  </xsl:template>
  <!-- Layoutknoten mit Kindknoten -->
  <xsl:template match="node( )[*]" mode="layout">
    <xsl:variable name="subTree">
      <xsl:apply-templates mode="layout"/>
    </xsl:variable>
    <!-- Den Knoten, die keine Blätter sind, wird die Summe der Gewichte ihrer Kindknoten zugewiesen. -->
    <xsl:variable name="thisWeight" select="sum($subTree/*/@tree:WEIGHT)"/>
    <xsl:variable name="maxDepth">
      <xsl:call-template name="emath:max">
        <xsl:with-param name="nodes" select="$subTree/*/@tree:MAXDEPTH"/>
      </xsl:call-template>
    </xsl:variable>
    <xsl:copy>
      <xsl:copy-of select="@*"/>
      <xsl:attribute name="tree:WEIGHT">
        <xsl:value-of select="$thisWeight"/>
      </xsl:attribute>
      <xsl:attribute name="tree:MAXDEPTH">
        <xsl:value-of select="$maxDepth"/>
      </xsl:attribute>
      <xsl:copy-of select="$subTree"/>
    </xsl:copy>
  </xsl:template>
  <!-- Layoutblattknoten -->
  <xsl:template match="*" mode="layout">
    <xsl:variable name="depth" select="count(ancestor-or-self::*) "/>
    <xsl:copy>
      <xsl:copy-of select="@*"/>
      <!-- Blattknoten erhalten das Gewicht 1 -->
      <xsl:attribute name="tree:WEIGHT">
        <xsl:value-of select="1"/>
      </xsl:attribute>
      <xsl:attribute name="tree:MAXDEPTH">
        <xsl:value-of select="$depth"/>
      </xsl:attribute>
    </xsl:copy>
  </xsl:template>
  <!-- Zeichne Knoten, die keine Blätter sind. -->
  <xsl:template match="node( )[*]" mode="draw">
    <xsl:param name="x"/>
    <xsl:param name="y"/>
    <xsl:param name="width"/>
    <xsl:variable name="thisX" select="$x + $width div 2 - ($nodeWidth+$horzSpace) div 2"/>
    <xsl:variable name="subTree">
      <xsl:call-template name="drawSubtree">
        <xsl:with-param name="nodes" select="*"/>
        <xsl:with-param name="weight" select="@tree:WEIGHT"/>
        <xsl:with-param name="x" select="$x"/>
        <xsl:with-param name="y" select="$y + $nodeHeight + $vertSpace"/>
        <xsl:with-param name="width" select="$width"/>
      </xsl:call-template>
    </xsl:variable>
    <g>
      <rect x="{$thisX}" y="{$y}" width="{$nodeWidth}" height="{$nodeHeight}" style="fill: none; stroke: black; stroke-width:{$strokeWidth};"/>
      <xsl:call-template name="drawConnections">
        <xsl:with-param name="xParent" select="$thisX"/>
        <xsl:with-param name="yParent" select="$y"/>
        <xsl:with-param name="widthParent" select="$nodeWidth"/>
        <xsl:with-param name="heightParent" select="$nodeHeight"/>
        <xsl:with-param name="children" select="$subTree/g/rect"/>
      </xsl:call-template>
      <xsl:copy-of select="$subTree"/>
    </g>
  </xsl:template>
  <!-- Zeichne Blattknoten -->
  <xsl:template match="*" mode="draw">
    <xsl:param name="x"/>
    <xsl:param name="y"/>
    <xsl:param name="width"/>
    <xsl:variable name="thisX" select="$x + $width div 2 - ($nodeWidth+$horzSpace) div 2"/>
    <g>
      <rect x="{$thisX}" y="{$y}" width="{$nodeWidth}" height="{$nodeHeight}" style="fill: none; stroke: black; stroke-width:{$strokeWidth};"/>
    </g>
  </xsl:template>
  <!-- Rekursive Routine zum Zeichnen von Unterbäumen. Alloziert horizontalen Raum abhängig vom Gewicht des Knotens. -->
  <xsl:template name="drawSubtree">
    <xsl:param name="nodes" select="/.."/>
    <xsl:param name="weight"/>
    <xsl:param name="x"/>
    <xsl:param name="y"/>
    <xsl:param name="width"/>
    <xsl:if test="$nodes">
      <xsl:variable name="node" select="$nodes[1]"/>
      <xsl:variable name="ratio" select="$node/@tree:WEIGHT div $weight"/>
      <!-- Zeichne Knoten samt Kindknoten in einem eigenen Raumanteil, abhängig vom aktuellen X-Wert und allozierter Breite. -->
      <xsl:apply-templates select="$node" mode="draw">
        <xsl:with-param name="x" select="$x"/>
        <xsl:with-param name="y" select="$y"/>
        <xsl:with-param name="width" select="$width * $ratio"/>
      </xsl:apply-templates>
      <!-- Bearbeite verbleibende Knoten -->
      <xsl:call-template name="drawSubtree">
        <xsl:with-param name="nodes" select="$nodes[position( ) &gt; 1]"/>
        <xsl:with-param name="weight" select="$weight"/>
        <xsl:with-param name="x" select="$x + $width * $ratio"/>
        <xsl:with-param name="y" select="$y"/>
        <xsl:with-param name="width" select="$width"/>
      </xsl:call-template>
    </xsl:if>
  </xsl:template>
  <!-- Code für Verbindungen ausgelassen. Identisch mit vorherigem Stylesheet. -->
</xsl:stylesheet>

Esta figura muestra el resultado del nuevo algoritmo con la misma entrada XML.

Estructura XML más equilibrada en SVG

Figura: estructura XML más equilibrada en SVG.

Discusión

Estas recetas son incompletas: dibujan solo el esqueleto, sin contenido. Añadir texto identificativo parece natural, pero SVG no lo escala automáticamente, sobre todo si el ancho de los nodos depende de él. La receta Añadir funciones de extensión con Java proporciona una función de extensión Java útil para la disposición SVG.

Hasta ahora, cada nodo de entrada corresponde a un nodo SVG. Una aplicación real filtraría los nodos poco importantes con patrones más específicos que match="node( )[*]" y match="*".

Si la jerarquía XML no modela directamente el árbol deseado, preprocese la entrada para crearlo. Ocurre, por ejemplo, si los atributos codifican las relaciones entre padres e hijos mediante punteros y destinos.

Las hojas admiten dos tipos de conexión. Los ejemplos utilizan ángulos rectos. Para las conexiones directas siguientes, sobrescriba drawConnections para llamar a drawStraightConnections.

Estructura XML en SVG con conexiones directas

Figura: estructura XML en SVG con conexiones directas.

Hay dos problemas de portabilidad. Primero, una extensión Java accede a la función Math:max. Es fácil implementarla en XSLT, pero las hojas SVG suelen necesitar otras extensiones. Segundo, requieren XSLT 1.1, versión abandonada, o posterior para tratar los fragmentos de árbol de resultados como conjuntos de nodos. También puede utilizar la extensión de conversión de su procesador.

Véase también

Para algoritmos sofisticados de dibujo de árboles y grafos, lea Graph Drawing: Algorithms for the Visualization of Graphs de Giuseppe Di Battista, Peter Eades, Roberto Tamassia e Ionnis G. Tollis (Prentice Hall, 1999). Encontrará matemáticas exigentes, no un recetario de algoritmos en pseudocódigo.

  

Volver arriba

<< atrás

siguiente >>

 

 

 

volver arriba