O'Reilly logo

XSLT Cookbook by Sal Mangano

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Displaying a Hierarchy

Problem

You want to create text output that is indented or annotated to reflect the hierarchal nature of the original XML.

Solution

The most obvious hierarchical representation uses indentation to mimic the hierarchical structure of the source XML. You can create a generic stylesheet, shown in Example 5-27 and Example 5-28, which makes reasonable choices for mapping the information in the input document to a hierarchical output.

Example 5-27. 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"/> <!--Levels indented with two spaces by default --> <xsl:param name="indent" select=" ' ' "/> <xsl:template match="*"> <xsl:param name="level" select="count(./ancestor::*)"/> <!-- Indent this element --> <xsl:call-template name="str:dup" > <xsl:with-param name="input" select="$indent"/> <xsl:with-param name="count" select="$level"/> </xsl:call-template> <!--Process the element name. Default will output local-name --> <xsl:apply-templates select="." mode="name"> <xsl:with-param name="level" select="$level"/> </xsl:apply-templates> <!--Signal the start of processing of attributes. Default will output '(' --> <xsl:apply-templates select="." mode="begin-attributes"> <xsl:with-param name="level" select="$level"/> </xsl:apply-templates> <!--Process ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required