5,446,542 members and growing! (17,631 online)
Email Password   helpLost your password?
Languages » XML » XSLT     Beginner

Using XSLT to generate a multi-level tree menu from XML

By MS le Roux

A simple and generic way to use XSLT to generate a multi-level HTML tree menu from an XML source.
XMLNT4, Win2K, Windows, ASP, Dev

Posted: 28 Feb 2002
Updated: 28 Feb 2002
Views: 122,884
Bookmarked: 37 times
Announcements
Want a new Job?



Search    
Advanced Search
Sitemap
18 votes for this Article.
Popularity: 5.17 Rating: 4.12 out of 5
0 votes, 0.0%
1
0 votes, 0.0%
2
2 votes, 22.2%
3
2 votes, 22.2%
4
5 votes, 55.6%
5

Sample Image - TreeFromXMLUsingXSLT.gif

Introduction

This article will demonstrate a simple and generic way to use XSLT to generate a multi-level HTML tree menu from an XML source. JScript is used for expanding and contracting the menu entries. (This requires a minimum of Internet Explorer 5. I have not tested this on any other browsers.)

The XML Source

This is a subset of the source XML (full XML source is in the zip file).

<menu>
 <entry>
  <text>In-House</text>
  <url>InHouse.htm</url>
  <entry>
   <text>Web Development</text>
   <url>WebDev.htm</url>
  </entry>
 </entry>
</menu>

The XSLT

For each menu entry, the XSLT processes it, then drills down until it has processed that entry's last child.

<?xml version="1.0" ?>
<xsl:stylesheet version="1.0" 
  xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

<xsl:template match="/">
 <xsl:for-each select="//menu/entry">
  <xsl:call-template name="SubMenu">
   <xsl:with-param name="strCSS">Parent IsVisible</xsl:with-param>
  </xsl:call-template>
 </xsl:for-each>
</xsl:template>

<xsl:template name="SubMenu">
 <xsl:param name="strCSS" />
 
 <xsl:variable name="strURL" select="url" />
 
 <div class="{$strCSS}">
  <xsl:choose>
   <xsl:when test="count(entry) > 0">
    <!-- Element has children, it can be expanded -->
    <input type="hidden" id="hidIsExpanded" value="0" />
    <label id="lblExpand" class="Expander" onclick="ExpanderClicked()">+
    </label>
   </xsl:when>
   <xsl:otherwise>
    <label class="Expander">  </label>
   </xsl:otherwise>
  </xsl:choose>
  
  <a href="{$strURL}"><xsl:value-of select="text" /></a>
  <xsl:for-each select="entry">
   <xsl:call-template name="SubMenu">
    <xsl:with-param name="strCSS">NotVisible</xsl:with-param>
   </xsl:call-template>
  </xsl:for-each>
 </div>
</xsl:template>

</xsl:stylesheet>

Transforming the XML on the server

ASP is used to perform server-side transformation of the XML.

<%
   dim xmlMenu
   dim xslMenu
   
   'Get the source XML

   set xmlMenu = server.CreateObject("Microsoft.XMLDOM")
   xmlMenu.async = false
   xmlMenu.load server.MapPath("TreeFromXMLUsingXSLT.xml")
   
   'Get the XSLT to transform the XML

   set xslMenu = server.CreateObject("Microsoft.XMLDOM")
   xslMenu.async = false
   xslMenu.load server.MapPath("TreeFromXMLUsingXSLT.xsl")
   
   'Transform the source XML using XSLT

   Response.Write xmlMenu.transformNode(xslMenu)
   
   set xmlMenu = nothing
   set xslMenu = nothing
%>

Controlling the menu entries

Client-side JScript is used to first determine whether a menu entry has been expanded or collapsed, and then adjusts the selected menu entry's style settings.

<script language="jscript">
function ExpanderClicked()
{
    //Get the element that was clicked

    var ctlExpander = event.srcElement;
    var ctlSelectedEntry = ctlExpander.parentElement;
    //Get all the DIV elements that are direct descendants

    var colChild = ctlSelectedEntry.children.tags("DIV");
    if(colChild.length > 0)
    {
        var strCSS;
        //Get the hidden element that 

        //indicates whether or not entry is expanded

        var ctlHidden = ctlSelectedEntry.all("hidIsExpanded");
      
        if(ctlHidden.value == "1")
        {
            //Entry was expanded and is being contracted

            ctlExpander.innerHTML = "+ ";
            ctlHidden.value = "0";
            strCSS = "NotVisible";
        }
        else
        {
            //Entry is being expanded

            ctlExpander.innerHTML = "- ";
            ctlHidden.value = "1";
            strCSS = "IsVisible";
        }
        //Show all the DIV elements that are direct children

        for(var intCounter = 0; intCounter < colChild.length; intCounter++)
        {
            colChild[intCounter].className = strCSS;
        }
    }
}
</script>

Style setting

CSS settings are used to specify if a menu entry should be visible or hidden. The IsVisible class sets the element to be displayed, as a block element. The NotVisible class sets the element to be hidden.

body
{
   font-family: Verdana;
   font-size: x-small;
}
.IsVisible
{
   display: block;
}
.NotVisible
{
   display: none;
}
.Expander
{
   cursor: hand;
   font-family: Courier;
}
.Parent DIV
{
   margin-Left: 15px !important;
}

The last setting (.Parent DIV) indicates that only the elements below the one with the "Parent" class, will have a margin. This is to prevent the root menu entries from also having a margin.

Using images instead of + and -

It is fairly simple to show images instead of a "+" and "-" next to each entry. To do this, alter the XSLT and replace the <label> element that is next to the link, with an <img> element. In the JScript, instead of setting the InnerHTML property of the ctlExpander variable, set the src attribute to show a different image. Here is an example:

Sample Image - TreeFromXMLUsingXSLT2.gif

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here

About the Author

MS le Roux


I live in the Northern Suburbs of Cape Town (South Africa).

Occupation: Web Developer
Location: South Africa South Africa

Other popular XML articles:

Article Top
Sign Up to vote for this article
You must Sign In to use this message board.
FAQ FAQ Noise ToleranceSearch Search Messages 
 Layout  Per page   
 Msgs 1 to 23 of 23 (Total in Forum: 23) (Refresh)FirstPrevNext
Subject  Author Date 
GeneralCross-browser compatible JavaScript-codememberKarl-Johan G3:09 14 Apr '08  
GeneralHow to use attribute to be a condition?membermathuros_paiboon6:27 18 Jul '05  
GeneralHow to use attribute to be a conditionmembermathuros_paiboon6:15 18 Jul '05  
GeneralIs it possible to create Tabular treememberKrisBabu1:05 30 Jul '04  
GeneralBug??memberHyperJ7:12 29 Oct '03  
Generalmozillasusswill_mad2:52 23 Jul '03  
GeneralRe: mozillamembermrameshchandra0:36 7 May '05  
GeneralRe: mozillamemberscotiniotis8:58 28 Jun '07  
GeneralTransfom using javascriptmemberfrostie23:58 23 Feb '03  
GeneralRe: Transfom using javascriptmemberMS le Roux2:01 24 Feb '03  
GeneralRe: Transfom using javascriptmemberfrostie6:02 24 Feb '03  
GeneralRe: Transfom using javascriptmemberfrostie6:04 24 Feb '03  
GeneralRe: Transfom using javascriptmemberfrostie6:30 24 Feb '03  
GeneralPersistencememberDACS0:01 5 Jul '02  
GeneralCan't get it working!memberchris B0:27 14 Jun '02  
GeneralRe: Can't get it working!memberMS le Roux21:25 17 Jun '02  
GeneralRe: Can't get it working!memberStephenWilliams1:09 9 Dec '02  
GeneralPictures?memberDomenic [CPUA 0x1337]4:06 1 Mar '02  
GeneralRe: Pictures?memberMarSCoZa4:15 1 Mar '02