Janine Polster
Janine Polster

Reputation: 101

output for all nodes in the tree

I'm very new to XSL and I want to print out all element nodes by name in a tree structure. So that:

<root>
          <childX>
                   <childY1/>
                   <childY2/>
          </childX>
          <childX2/>
 </root>

will yield:

root
     +--childX
          +--childY1
          +--childY2
     +--childX2

I tried some loops, but probably need recursion.... what I have so far:

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0"           xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template name="root" match="/">
<html>
<xsl:for-each select="*">
  <xsl:value-of select="local-name()"/><br/>
  +-- <xsl:for-each select="*">
  <xsl:value-of select="local-name()"/><br/>
</xsl:for-each>
</html>
</xsl:template>

would be awesome if you could gimme some hints. thanks!

Upvotes: 0

Views: 467

Answers (1)

Martin Honnen
Martin Honnen

Reputation: 167696

Recursion is done using apply-templates, I am not sure it is a good idea to output HTML and then try to construct a tree structure as plain text (creating a nested list in HTML seems more appropriate) but here you go:

<xsl:template match="/">
  <html>
    <head>
      <title>Example</title>
    </head>
    <body>
        <pre>
            <xsl:apply-templates/>                   
        </pre>  
    </body>
  </html>
</xsl:template>

<xsl:template match="*">
    <xsl:param name="indent" select="'--'"/>
    <xsl:value-of select="concat('+', $indent, ' ', local-name())"/>
    <br/>
    <xsl:apply-templates select="*">
        <xsl:with-param name="indent" select="concat('--', $indent)"/>
    </xsl:apply-templates>
</xsl:template>

Upvotes: 1

Related Questions