Recursive XSLT For Nested XML Nodes In ColdFusion

Posted December 11, 2007 at 7:01 PM

Tags: ColdFusion

Earlier today, Jacob Munson brought up the task of outputting an XML menu (as HTML) without knowing ahead of time how deeply nested the menus and sub menus might be. As I have been doing a lot with both recursion and XSLT (XML transformations) in ColdFusion lately, it was the first thing that popped into my mind. XSLT is not the friendliest language to learn, so I thought I would put up a little example of recursion in XSLT and ColdFusion.

Instead of working with a menu, I am going to work with a task list. This is basically the same thing, but I simply couldn't think of any good menu examples. Here, we are going to define a set of tasks by breaking them down into smaller and smaller sub tasks. This XML document will be stored inside of a ColdFusion XML document object created using the CFXML tag:

 Launch code in new window » Download code as text file »

  • <!--- Define the nested tasks. --->
  • <cfxml variable="xmlTasks">
  •  
  • <tasks>
  •  
  • <task>
  • <name>Breakfast</name>
  • <task>
  • <name>Cook Eggs</name>
  •  
  • <task>
  • <name>Crack Eggs</name>
  •  
  • <task>
  • <name>Crack Egg 1</name>
  • </task>
  • <task>
  • <name>Crack Egg 2</name>
  • </task>
  • <task>
  • <name>Crack Egg 3</name>
  • </task>
  • <task>
  • <name>Crack Egg 4</name>
  • </task>
  • </task>
  • <task>
  • <name>Beat Eggs</name>
  •  
  • <task>
  • <name>Beat Clockwise</name>
  •  
  • <task>
  • <name>Beat</name>
  • </task>
  • <task>
  • <name>Beat</name>
  • </task>
  • <task>
  • <name>Beat</name>
  • </task>
  • </task>
  • <task>
  • <name>Beat Counter Clockwise</name>
  •  
  • <task>
  • <name>Beat</name>
  • </task>
  • <task>
  • <name>Beat</name>
  • </task>
  • <task>
  • <name>Beat</name>
  • </task>
  • </task>
  • </task>
  • <task>
  • <name>Put Eggs In Pan</name>
  • </task>
  • <task>
  • <name>Put Eggs on Plate</name>
  • </task>
  • </task>
  • <task>
  • <name>Eat Eggs</name>
  • <task>
  • <name>Put In Mouth</name>
  •  
  • <task>
  • <name>Put On Fork</name>
  • </task>
  • <task>
  • <name>Move For To Mouth</name>
  • </task>
  • </task>
  • <task>
  • <name>Chew Eggs</name>
  • </task>
  • <task>
  • <name>Swallow</name>
  • </task>
  • </task>
  • </task>
  •  
  • </tasks>
  •  
  • </cfxml>

As you can see, our only root Task is eating breakfast. This task is then sub-divided into smaller, more manageable tasks. Each of those tasks may or may not be further sub-divided, so on and so forth.

Now, we want to take that ColdFusion XML document object and transform it into some XHTML. Of course, since we don't know how deeply nested the XML DOM tree is going to be, we have to provide a way to continually traverse it in a depth-first manner until we hit a leaf and then continue on to the next available branch until all task nodes have been explored. And, as we have seen from previous posts, this is an ideal situation for recursion.

Our recursion will define the current Task node by outputting the name and then outputting each of the child task nodes. Each of the child task nodes will be output by the same method (or template in our case). So, in typical recursion style, our XSLT template for Task is used to define itself.

Recursion is hard to visualize, so let's just take a look at the XSLT. This XSLT is transformed using my XSLT ColdFusion custom tag, which basically creates the XML transformation and executes it all in one go:

 Launch code in new window » Download code as text file »

  • <!--- Transform the XML and output the result. --->
  • <cf_xslt xml="#xmlTasks#">
  •  
  • <!--- Document type declaration. --->
  • <?xml version="1.0" encoding="ISO-8859-1"?>
  •  
  • <xsl:transform
  • version="1.0"
  • xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  •  
  •  
  • <!---
  • Start out by matching the root element. This will
  • prevent the task node template from matching on
  • its own (we only want task nodes to match when we
  • explicitly apply templates).
  • --->
  • <xsl:template match="tasks">
  •  
  • <!--- Begin our initial task list. --->
  • <ol>
  • <!---
  • Now, apply the task template to all
  • top-level tasks in the task list.
  • --->
  • <xsl:apply-templates select="task" />
  • </ol>
  •  
  • </xsl:template>
  •  
  •  
  • <!--- Matches a task node. --->
  • <xsl:template match="task">
  •  
  • <!--- Output the task. --->
  • <li>
  • <span>
  • <xsl:value-of select="name" />
  • </span>
  •  
  • <!---
  • Check to see if there are any sub tasks
  • that need their own list.
  • --->
  • <xsl:if test="task">
  •  
  • <!---
  • Start a new sub-task list and then
  • RECURSIVELY apply the task template
  • to each of the sub-task nodes.
  • --->
  • <ol>
  • <xsl:apply-templates select="task" />
  • </ol>
  •  
  • </xsl:if>
  • </li>
  •  
  • </xsl:template>
  •  
  •  
  • </xsl:transform>
  •  
  • </cf_xslt>

Our XSLT first matches the Tasks XML node. This template outputs the first ordered list element (OL) and then applies the Task template to each of the top-level task nodes. Then, for each Task node, we output the name and recursively re-apply the Task template to each of the sub-tasks. Remember, the whole point of recursion is that some piece of functionality is defined in part by self-executing.

Running the above code, we get the following output:

  1. Breakfast
    1. Cook Eggs
      1. Crack Eggs
        1. Crack Egg 1
        2. Crack Egg 2
        3. Crack Egg 3
        4. Crack Egg 4
      2. Beat Eggs
        1. Beat Clockwise
          1. Beat
          2. Beat
          3. Beat
        2. Beat Counter Clockwise
          1. Beat
          2. Beat
          3. Beat
      3. Put Eggs In Pan
      4. Put Eggs on Plate
    2. Eat Eggs
      1. Put In Mouth
        1. Put On Fork
        2. Move For To Mouth
      2. Chew Eggs
      3. Swallow

All in all, the XSLT for a problem like this is extremely small; possibly smaller than the functionally equivalent ColdFusion recursion you might see. Now, in our task list, we just output a task name, but certainly, it would be a small jump to create a menu system that had Text and Href nodes that created links as part of the menu definitions.

Download Code Snippet ZIP File

Post Comment  |  Ask Ben  |  Permalink  |  Other Searches  |  Print Page




Reader Comments

Dec 12, 2007 at 7:29 AM // reply »
25 Comments

Hi Ben,

Great post. I had taken a look at XSLT about a year ago, but dropped it due to lack of time and having the impression that it was more complicated than it was worth.

This post, however, sends me back to my books. Thanks for taking the time to post this.


Dec 12, 2007 at 7:51 AM // reply »
6,516 Comments

@Francois,

If you are interested, I wrote up a little tutorial a while:

http://www.bennadel.com/index.cfm?dax=blog:952.view

I am only recently into XSLT, but it seems like a really powerful tool if given the right scenario.


Dec 12, 2007 at 4:44 PM // reply »
1 Comments

Perfect timing! i was just starting to work on this exact problem. You just saved me a ton of time. :) I'm pretty comfortable with XPath (thanks to jQuery) but XSLT has always been a bit of a hurdle. Great post.


Dec 12, 2007 at 4:50 PM // reply »
6,516 Comments

@Ken,

Good timing indeed. If you run into any problems, let me know.


May 2, 2008 at 5:33 AM // reply »
1 Comments

I have been using xslt for menu's lately. Previously to get the hierarchical tree of <ul> and <li> I had to use recursive functions containing queries which meant hundreds of queries being triggered. To get round this I created a flat node structure e.g.

<nodes>
<cfquery name="getNodes">
<node nodeID="#nodeID#" nodeParentID="#nodeParentID#" nodeName="#nodeName#" />
</cfquery>
</nodes>

Then using the XSLT I transformed this structure into a hierarchical tree of nodes.

<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
<xsl:template match="nodes">
<!-- Starts the tree -->
<ul>
<xsl:apply-templates/>
</ul>

</xsl:template>

<xsl:template match="//node[@nodeParentID=0]">

<xsl:call-template name="process-branch">
<xsl:with-param name="nodeID"><xsl:value-of select="@nodeID"/></xsl:with-param>
<xsl:with-param name="nodeParentID"><xsl:value-of select="@nodeParentID"/></xsl:with-param>
<xsl:with-param name="nodeName"><xsl:value-of select="@nodeName"/></xsl:with-param>
</xsl:call-template>

</xsl:template>

<xsl:template name="process-branch">
<xsl:param name="nodeID"/>
<xsl:param name="nodeParentID"/>
<xsl:param name="nodeName"/>

<xsl:choose>

<xsl:when test="count(//node[@nodeParentID=current()/@nodeID])=0">
<li><xsl:value-of select="@nodeName" /></li>
</xsl:when>

<xsl:otherwise>
<li><xsl:value-of select="@nodeName" />
<ul>
<xsl:for-each select="//node[@nodeParentID=current()/@nodeID]">

<xsl:call-template name="process-branch">
<xsl:with-param name="nodeID"><xsl:value-of select="@nodeID"/></xsl:with-param>
<xsl:with-param name="nodeParentID"><xsl:value-of select="@nodeParentID"/></xsl:with-param>
<xsl:with-param name="nodeName"><xsl:value-of select="@nodeName"/></xsl:with-param>
</xsl:call-template>

</xsl:for-each>
</ul>
</li>
</xsl:otherwise>

</xsl:choose>

</xsl:template>

</xsl:stylesheet>


Mar 17, 2009 at 3:27 PM // reply »
2 Comments

Hi Ben

Your post is very smart, i have a recursive logic using java objects and i was looking for to adept it to a web infrastructure using xml, i just had to make some adjusts on your post to adequate to my need.
...Here go an unlimited tree menu structure using that xml:

<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
<xsl:output method="html"/>

<xsl:template match="tasks">
<xsl:apply-templates select="task" />
</xsl:template>

<xsl:template match="task">

<xsl:if test="task=false()">
<li>
<a>
<xsl:attribute name="href">
<xsl:value-of select="href" />
</xsl:attribute>

<xsl:value-of select="name" />
</a>
</li>
<xsl:apply-templates select="task" />
</xsl:if>

<xsl:if test="task=true()">

<li>
<a>
<xsl:attribute name="href">
<xsl:value-of select="href" />
</xsl:attribute>

<xsl:value-of select="name" />
</a>
<ul>
<xsl:apply-templates select="task" />
</ul>
</li>
</xsl:if>
</xsl:template>
</xsl:stylesheet>


Mar 25, 2009 at 10:14 PM // reply »
6,516 Comments

@Marco,

Looks good.


Viv
Apr 8, 2009 at 8:46 AM // reply »
1 Comments

How do we process the nested tags for same value. For e.g.

<Style value="Italics">
<Style value="Bold">
<Style value="Underline>
Text
</Style>
</Style>
</Style>

I want the output to be

<span style="font-style:italic; font-weight:bold; text-decoration:underline>Text</span>


Apr 8, 2009 at 9:32 AM // reply »
2 Comments

@Viv,

Just make a research on how to use style or css (are the same) plus javascript plus html code, if i try to explain it here...i will make some mess.
there is some way to use css inside xsl, but i didn' went so deep on it yet.

for example:
...html code above
<div id="id" class="style_class">
<< your html code >>
</div>

<style>
.style_class ul{ setups}
.style_class ul li {setups}
.style_class ul li a{setups}
.style_class ul li ul li a{setups}
...and so on
</style>
..html code below

your div tag you can populate it using javascript reading xml plus xsl and the style class you configure it acording to the html tags that was declared.
if you have a simple html page it is easy to work straight in the html page, but if you have a more complex html page or xsl structure maybe it will be easier to setup it using xsl.


ab
Nov 19, 2009 at 4:05 AM // reply »
3 Comments

swwweeet. i figured it was possible. tried a for-each with no luck


Nov 19, 2009 at 10:11 AM // reply »
6,516 Comments

@AB,

Awesome.


Post Comment  |  Ask Ben

Recent Blog Comments
Nov 21, 2009 at 5:15 PM
Using ColdFusion Structures To Remove Duplicate List Values
@Jose Galdamez, Oh heh yeah I didn't paste the whole code. I should have defined the vars -- my bad. It's fixed thou. Thanks. ... read »
Nov 21, 2009 at 4:49 PM
Styling The ColdFusion 8 WriteToBrowser CFImage Output
Great work yet again Ben! Whilst I didn't use this whole code, I copied some of your regex code for a similar problem with the lack of an alt attribute and unescaped ampersands in CFIMAGE for Railo 3 ... read »
Nov 21, 2009 at 1:13 PM
My First ColdFusion Builder Extension - Encrypting And Decrypting CFM / CFC Files
@Ben, Because I am pedantic, I just want to make sure that everyone knows there is absolutely no encryption going on. There is only encoding and obfuscation. The cfencode tool only obfuscates your C ... read »
Nov 21, 2009 at 12:28 PM
Using ColdFusion Structures To Remove Duplicate List Values
@Jody I can't seem to get your code sample to work. If you are still having problems, try this code out and see if it gets you what you wanted. <!--- Comma delimited list with various duplicates ... read »
Nov 21, 2009 at 11:03 AM
Groovy Operator Overloading Does Not Work In The ColdFusion Context
Hi Ben, Thanks for this informative post. Now I am reading ur old posts too ... read »
Nov 21, 2009 at 10:56 AM
HostMySite.com Has The Best ColdFusion Hosting
@Mehul, Yes very nice people, however several downtimes per day which was not acceptable. Hence we had to move out. I am glad you are having good luck with them so far. ... read »
Nov 20, 2009 at 11:32 PM
Five Months Without Hungarian Notation And I'm Loving It
I've used headless camel case for years for not only ColdFusion variables, but also SQL tables and fields... pretty much everything involving code. I also subscribe to the "don't abbreviate and clea ... read »