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 ...
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.