XML technologies / XSLT / XSLT Cookbook / From XML to text / Display a hierarchy
(Excerpt from “XSLT Kochbuch” by Sal Mangano)
Problem
You want text indented or annotated to reflect the original XML hierarchy.
Solution
The most obvious display imitates the XML hierarchy through indentation. A generic stylesheet, shown in the next two examples, can make sensible choices for mapping source information to hierarchical output.
Example: text.hierarchy.xslt
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:str="http://www.ora.com/XSLTCookbook/namespaces/strings">
<xsl:include href="../strings/str.dup.xslt"/>
<xsl:include href="../strings/str.replace.xslt"/>
<xsl:output method="text"/>
<!--Die Ebenen werden standardmäßig durch zwei Leerzeichen eingerückt -->
<xsl:param name="indent" select=" ' ' "/>
<xsl:template match="*">
<xsl:param name="level" select="count(./ancestor::*)"/>
<!-- Dieses Element einrücken -->
<xsl:call-template name="str:dup" >
<xsl:with-param name="input" select="$indent"/>
<xsl:with-param name="count" select="$level"/>
</xsl:call-template>
<!--Verarbeiten des Elementnamens. Standardmäßig wird local-name ausgegeben -->
<xsl:apply-templates select="." mode="name">
<xsl:with-param name="level" select="$level"/>
</xsl:apply-templates>
<!--Den Anfang der Verarbeitung der Attribute signalisieren. Standardmäßig wird '(' ausgegeben. -->
<xsl:apply-templates select="." mode="begin-attributes">
<xsl:with-param name="level" select="$level"/>
</xsl:apply-templates>
<!--Verarbeiten der Attribute. Standardmäßig wird name="value" ausgegeben. -->
<xsl:apply-templates select="@*">
<xsl:with-param name="element" select="."/>
<xsl:with-param name="level" select="$level"/>
</xsl:apply-templates>
<!--Das Ende der Verarbeitung der Attribute signalisieren. Standardmäßig wird ')' ausgegeben. -->
<xsl:apply-templates select="." mode="end-attributes">
<xsl:with-param name="level" select="$level"/>
</xsl:apply-templates>
<!-- Verarbeiten des Elementwertes. -->
<!-- Standardmäßig wird der Wert eines Blattelements so formatiert, dass es auf der nächsten Zeile eingerückt ist. -->
<xsl:apply-templates select="." mode="value">
<xsl:with-param name="level" select="$level"/>
</xsl:apply-templates>
<xsl:apply-templates select="." mode="line-break">
<xsl:with-param name="level" select="$level"/>
</xsl:apply-templates>
<!-- Verarbeiten der Kinder -->
<xsl:apply-templates select="*">
<xsl:with-param name="level" select="$level + 1"/>
</xsl:apply-templates>
</xsl:template>
<!--Vorgegebene Behandlung der Elementnamen. -->
<xsl:template match="*" mode="name">[<xsl:value-of select="local-name(.)"/></xsl:template>
<!--Vorgegebene Behandlung des Beginns der Attribute. -->
<xsl:template match="*" mode="begin-attributes">
<xsl:if test="@*"><xsl:text> </xsl:text></xsl:if>
</xsl:template>
<!--Vorgegebene Behandlung der Attribute. -->
<xsl:template match="@*">
<xsl:value-of select="local-name(.)"/>="<xsl:value-of select="."/>"<xsl:text/>
<xsl:if test="position() != last()">
<xsl:text> </xsl:text>
</xsl:if>
</xsl:template>
<!--Vorgegebene Behandlung des Endes der Attribute. -->
<xsl:template match="*" mode="end-attributes">]</xsl:template>
<!--Vorgegebene Behandlung der Elementwerte. -->
<xsl:template match="*" mode="value">
<xsl:param name="level"/>
<!-- Nur Ausgabe der Werte für Blätter. -->
<xsl:if test="not(*)">
<xsl:variable name="indent-str">
<xsl:call-template name="str:dup" >
<xsl:with-param name="input" select="$indent"/>
<xsl:with-param name="count" select="$level"/>
</xsl:call-template>
</xsl:variable>
<xsl:text>
</xsl:text>
<xsl:value-of select="$indent-str"/>
<xsl:call-template name="str:replace">
<xsl:with-param name="input" select="."/>
<xsl:with-param name="search-string" select=" '
' "/>
<xsl:with-param name="replace-string" select="concat('
',$indent-str)"/>
</xsl:call-template>
</xsl:if>
</xsl:template>
<xsl:template match="*" mode="line-break">
<xsl:text>
</xsl:text>
</xsl:template>
</xsl:stylesheet>Example: output for ExpenseReport.xml.
[ExpenseReport statementNum="123"]
[Employee]
[Name]
Salvatore Mangano
[SSN]
999-99-9999
[Dept]
XSLT Hacking
[EmpNo]
1
[Position]
Koch
[Manager]
Großer Chef O'Reilly
[PayPeriod]
[From]
1/1/02
[To]
1/31/02
[Expenses]
[Expense]
[Date]
12/20/01
[Account]
12345
[Desc]
Herumgehangen, anstatt zur Konferenz zu fahren.
[Lodging]
500.00
[Transport]
50.00
[Fuel]
0
[Meals]
300.00
[Phone]
100
[Entertainment]
1000.00
[Other]
300.00
[Expense]
[Date]
12/20/01
[Account]
12345
[Desc]
Am Strand
[Lodging]
500.00
[Transport]
50.00
[Fuel]
0
[Meals]
200.00
[Phone]
20
[Entertainment]
300.00
[Other]
100.00
XSLT 2.0
With XSLT 2.0, improve the code using the built-in XPath 2.0 function replace and the padding function in recipe Generate a column-formatted report.
Discussion
You may dislike this stylesheet’s choices for mapping the source to a hierarchical layout. That is fine: it is intended to be customized. The next two examples may yield results you prefer.
Example: customized ExpenseReport stylesheet.
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:import href="text.hierarchy.xslt"/>
<!--Ignorieren der Attribute -->
<xsl:template match="@*"/>
<xsl:template match="*" mode="begin-attributes"/>
<xsl:template match="*" mode="end-attributes"/>
<xsl:template match="*" mode="name">
<!--Anzeigen des lokalen Elementnamens-->
<xsl:value-of select="local-name(.)"/>
<!--Gefolgt von einem Doppelpunkt und einem Leerzeichen, wenn es sich um ein Blatt handelt -->
<xsl:if test="not(*)">: </xsl:if>
</xsl:template>
<xsl:template match="*" mode="value">
<xsl:if test="not(*)">
<xsl:value-of select="."/>
</xsl:if>
</xsl:template>
</xsl:stylesheet>Example: newly formatted output.
ExpenseReport
Employee
Name: Salvatore Mangano
SSN: 999-99-9999
Dept: XSLT Hacking
EmpNo: 1
Position: Koch
Manager: Großer Chef O'Reilly
PayPeriod
From: 1/1/02
To: 1/31/02
Expenses
Expense
Date: 12/20/01
Account: 12345
Desc: Herumgehangen, anstatt zur Konferenz zu fahren.
Lodging: 500.00
Transport: 50.00
Fuel: 0
Meals: 300.00
Phone: 100
Entertainment: 1000.00
Other: 300.00
Expense
Date: 12/20/01
Account: 12345
Desc: Am Strand
Lodging: 500.00
Transport: 50.00
Fuel: 0
Meals: 200.00
Phone: 20
Entertainment: 300.00
Other: 100.00
Another format, in the next examples, was inspired by Jeni Tennison.
Example: tree-control.xslt
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:import href="text.hierarchy.xslt"/>
<!--Ignorieren der Attribute -->
<xsl:template match="@*"/>
<xsl:template match="*" mode="begin-attributes"/>
<xsl:template match="*" mode="end-attributes"/>
<xsl:template match="*" mode="name">
<!--Anzeigen des lokalen Elementnamens-->
<xsl:text>[</xsl:text>
<xsl:value-of select="local-name(.)"/>
<!--Gefolgt von einer eckigen Klammer und einem Leerzeichen, wenn es sich um ein Blatt handelt -->
<xsl:text>] </xsl:text>
</xsl:template>
<xsl:template match="*" mode="value">
<xsl:if test="not(*)">
<xsl:value-of select="."/>
</xsl:if>
</xsl:template>
<xsl:template match="*" mode="indent">
<xsl:for-each select="ancestor::*">
<xsl:choose>
<xsl:when test="following-sibling::*"> | </xsl:when>
<xsl:otherwise><xsl:text> </xsl:text></xsl:otherwise>
</xsl:choose>
</xsl:for-each>
<xsl:choose>
<xsl:when test="*"> o-</xsl:when>
<xsl:when test="following-sibling::*"> +-</xsl:when>
<xsl:otherwise> `-</xsl:otherwise>
</xsl:choose>
</xsl:template>
<xsl:template match="*" mode="line-break">
<xsl:text>
</xsl:text>
</xsl:template>
</xsl:stylesheet>Example: tree-formatted output.
o-[ExpenseReport]
o-[Employee]
| +-[Name] Salvatore Mangano
| +-[SSN] 999-99-9999
| +-[Dept] XSLT Hacking
| +-[EmpNo] 1
| +-[Position] Koch
| `-[Manager] Großer Chef O'Reilly
o-[PayPeriod]
| +-[From] 1/1/02
| `-[To] 1/31/02
o-[Expenses]
o-[Expense]
| +-[Date] 12/20/01
| +-[Account] 12345
| +-[Desc] Herumgehangen, anstatt zur Konferenz zu fahren.
| +-[Lodging] 500.00
| +-[Transport] 50.00
| +-[Fuel] 0
| +-[Meals] 300.00
| +-[Phone] 100
| +-[Entertainment] 1000.00
| `-[Other] 300.00
o-[Expense]
+-[Date] 12/20/01
+-[Account] 12345
+-[Desc] Am Strand
+-[Lodging] 500.00
+-[Transport] 50.00
+-[Fuel] 0
+-[Meals] 200.00
+-[Phone] 20
+-[Entertainment] 300.00
`-[Other] 100.00
Go further with a stylesheet importing tree-control.xslt and accepting a global parameter listing element names to hide or collapse. Collapsed levels are indicated by the prefix x, as in the next two examples.
Example: stylesheet generating collapsed levels.
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:import href="tree-control.xslt"/>
<xsl:param name="collapse"/>
<xsl:variable name="collapse-test" select="concat(' ',$collapse,' ')"/>
<xsl:template match="*" mode="name">
<xsl:if test="not(ancestor::*[contains($collapse-test,concat(' ',local-name(.),' '))])">
<xsl:apply-imports/>
</xsl:if>
</xsl:template>
<xsl:template match="*" mode="value">
<xsl:if test="not(ancestor::*[contains($collapse-test,concat(' ',local-name(.),' '))])">
<xsl:apply-imports/>
</xsl:if>
</xsl:template>
<xsl:template match="*" mode="line-break">
<xsl:if test="not(ancestor::*[contains($collapse-test,concat(' ',local-name(.),' '))])">
<xsl:apply-imports/>
</xsl:if>
</xsl:template>
<xsl:template match="*" mode="indent">
<xsl:choose>
<xsl:when test="self::*[contains($collapse-test,concat(' ',local-name(.),' '))]">
<xsl:for-each select="ancestor::*">
<xsl:text> </xsl:text>
</xsl:for-each>
<xsl:text> x-</xsl:text>
</xsl:when>
<xsl:when test="ancestor::*[contains($collapse-test,concat(' ',local-name(.),' '))]"/>
<xsl:otherwise>
<xsl:apply-imports/>
</xsl:otherwise>
</xsl:choose>
</xsl:template>
</xsl:stylesheet>Example: output with $collapse="Employee PayPeriod".
o-[ExpenseReport]
x-[Employee]
x-[PayPeriod]
o-[Expenses]
o-[Expense]
| +-[Date] 12/20/01
| +-[Account] 12345
| +-[Desc] Herumgehangen, anstatt zur Konferenz zu fahren.
| +-[Lodging] 500.00
| +-[Transport] 50.00
| +-[Fuel] 0
| +-[Meals] 300.00
| +-[Phone] 100
| +-[Entertainment] 1000.00
| `-[Other] 300.00
o-[Expense]
+-[Date] 12/20/01
+-[Account] 12345
+-[Desc] Am Strand
+-[Lodging] 500.00
+-[Transport] 50.00
+-[Fuel] 0
+-[Meals] 200.00
+-[Phone] 20
+-[Entertainment] 300.00
`-[Other] 100.00
Overriding the base stylesheet allows virtually unlimited tree formats. In object-oriented programming this is called the Template-Method-Pattern. First define an algorithm’s skeleton; subclasses redefine steps without changing its structure. Importing stylesheets play the subclass role in XSLT. The recipe’s strength is not that building a tree is difficult, but that you can reuse its structure while concentrating only on what needs changing.
Copyright © 2006 O'Reilly Verlag GmbH & Co. KG
You may print the online version for your private use.
Otherwise, this chapter from “XSLT Kochbuch” is subject to the same conditions as the bound edition. The work, including all its parts, is protected by copyright. All rights reserved, including reproduction, translation, microfilming, and storage and processing in electronic systems.
O'Reilly Verlag GmbH & Co. KG, Balthasarstraße 81, 50670 Köln, kommentar(at)oreilly.de