1

I want to create tree view structure from XML data. Can any one please help me how do I achieve this using XSLT.

XML File:

   <?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/xsl" href="filename.xsl"?>
<node text="Path1">
  <node text="Folder1">
    <node text="File1.java" />
    <node text="File2.java" />
    <node text="Folder2">
        <node text="File3.java" />
        <node text="File4.java" />
    </node>
  </node>
  <node text="Folder3" > </node>
</node>

Output:

Path1
  |-Folder1
      |-File1.java
      |-File2.java
      |-Folder2
         |-File3.java
         |-File4.java
  |-Folder3
      |-File5.java

2 Answers 2

1

for browser view as list you can use this code

XSLT

    <xsl:template match="node">
    <ul>
        <li><xsl:value-of select="@text"/></li>
        <xsl:for-each select="child::node">
            <ul>
                <li>
                    <xsl:value-of select="@text"/>                
                    <xsl:apply-templates select="node()"/>
                </li>
            </ul>
        </xsl:for-each>
    </ul>
</xsl:template>

Output

<ul>
   <li>Path1</li>
   <ul>
      <li>Folder1
        <ul>
            <li>File1.java</li>
         </ul>
        <ul>
            <li>File2.java</li>
         </ul>
        <ul>
            <li>Folder2</li>
            <ul>
               <li>File3.java</li>
            </ul>
            <ul>
               <li>File4.java</li>
            </ul>
         </ul>
      </li>
   </ul>
   <ul>
      <li>Folder3 </li>
   </ul>
</ul>

Sign up to request clarification or add additional context in comments.

2 Comments

Thank you so much Rupesh. It's working like charm. I received one more requirement i.e., making the tree view Expand and Collapse onClick. Any idea?
For expand and collapse you should use javascript
1

Try this

    <xsl:template match="/">
    <xsl:for-each select="descendant-or-self::*">
        <xsl:for-each select="ancestor::*">
            <xsl:text>&#160;&#160;&#160;&#160;&#160;</xsl:text>
        </xsl:for-each>
        <xsl:text>|</xsl:text>
    <xsl:value-of select="@text"/>
        <xsl:text>&#xa;</xsl:text>
    </xsl:for-each>
</xsl:template>

2 Comments

Thanks Rupesh for quick response. It's displaying in single line instead of Tree View format. Any clue? My ultimate goal is to display the tree view in the browser. Can you use <ui> and <li> tags to achieve this?
I am ok to alter my xml file to achieve Tree View kind of output.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.