- Use existing controls to simulate a custom menu. In their popular ASP.NET book, Alex Homer and Dave Sussman, et. al. present a case study that creates an XML-based menu using a DataList server control. Their menu works fine for menus one or two levels deep; however, nesting DataList controls to create menus of arbitrary depth is not trivial. For an arbitrary depth menu I’ve found it’s better to use a TreeView control (from Microsoft’s downloadable IE Web Controls, binding it to an XML file containing the hierarchal menu. The TreeNode element that makes up the individual items of this control can contain children of its own type, letting you nest elements to any arbitrary depth. Using a TreeView works fine for Windows Explorer-like GUIs, but severely limits the styles you can produce unless you are willing to re-write the code-behind that renders the control. Furthermore, all events raised by this control are processed on the server by default, which requires server trips for actions that you’d expect to happen on the client, such as selecting, expanding and collapsing nodes.
A New Approach
- To present the menu hierarchy in a simple form such as an XML schema?similar to that in the TreeView control, allowing arbitrary depth with minimal and straight-forward modification.
XML and XSLT to the Rescue
|Figure 1. Desired Menu Structure: Each menuItem element may have a collection of menuItem children. The leaf elements (the last children in a branch) hold URLs for redirecting the browser.
Figure 1 shows a desired menu structure where the element has children of its own type?similar to the TreeNode element of the TreeView control. The leaf elements (the last children in a branch) each point to a URL where the browser is directed when users click a leaf. Because elements can have children of their own type, it is not possible to show a schema diagram for this tree.
A Short Example
Here’s an example that elucidates the methodology. First, you need an XML representation of the menu tree shown in Figure 1. The following XML represents an example menu.
I made a slight modification in the element name from the generic XML tree shown in Figure 1 by changing the top level element to
|Figure 2: Example XulMenu: Here’s how the example menu looks when rendered in a browser.
The top level in this menu has a class=”button” attribute that ties the menu to the “button” style defined using CSS. A menu item with children has one or more
The first item matches the
The next XSL template matches the
element to hold the child elements. Otherwise it creates a leaf element with its href attribute set to the href attribute of the XML element.