Creating a Tree Diagram

Problem

You want to show the hierarchical structure of your data as a tree.

Solution

This section presents two different algorithms for rendering a tree. Neither is the most sophisticated algorithm available, but both give reasonable results.

If all the trees you needed to render were balanced, then rendering a tree would be easy because you would need to divide the available horizontal space by the number of nodes at each level and the vertical space by the number of levels.[20] Unfortunately, real-world trees are not as symmetrical. You need an algorithm that considers the breadth of each branch.

The first technique makes only one pass over the tree. However, to accomplish this, it needs to embed foreign bookkeeping attributes into the resulting SVG. This example places these attributes in a namespace to ensure they will not conflict with SVG-specific attributes:

<?xml version="1.0" encoding="UTF-8"?> <xsl:stylesheet <!-- v. 1.1 is defunct but works in Saxon to enable the --> <!-- xsl:script feature. --> 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" ...

Get XSLT Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.