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



Learning ColdFusion 9 - ColdFusion 9 tutorials, samples, examples, demos

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,371 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.


Ken Dunnington
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,371 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>


Marco Aurelio Micheletto
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,371 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>


Marco Auelio Micheletto
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.


Post Comment  |  Ask Ben

Recent Blog Comments
Jill
Nov 7, 2009 at 7:58 AM
How To Unformat Your Code (Like A Pro)
LMAO - this was pretty funny! I have to admit - I also love to reformat code so I can read it. My boss used to tell me to leave my OCD at home. Now I don't feel so bad after reading everyone else' ... read »
Nov 6, 2009 at 10:10 PM
How To Unformat Your Code (Like A Pro)
The timing of this post is just uncanny. I spent the last 15-20 minutes manually un-formatting my "Ben Nadel" style code within a CFC of mine. I was really digging the readability a few weeks ago, bu ... read »
Roe
Nov 6, 2009 at 5:11 PM
Passing Arrays By Reference In ColdFusion - SWEEET!
ArraySort also reorders the results of these java obj's ... read »
Nov 6, 2009 at 4:53 PM
How To Unformat Your Code (Like A Pro)
I tried to go *back* the other way. Adding formatting is actually a much more complicated problem than removing formatting. Anyway, here is what I could put together with a minimal amount of time: ... read »
Asaf
Nov 6, 2009 at 2:35 PM
ColdFusion GetPageContext() Massive Exploration
Hi, I actually found this post useful. I recently acquired a SSL certificate for my website and when I switched over to HTTPS Internet Explorer would throw an error when trying to download a dynamic ... read »
Nov 6, 2009 at 2:19 PM
How To Unformat Your Code (Like A Pro)
@Chuck, @Nathan, Well, now I feel like it's a challenge.... I accept. ... read »
Nathan Stanford
Nov 6, 2009 at 2:06 PM
How To Unformat Your Code (Like A Pro)
@Chuck, I would love it as well. I was not joking I am very serious I love well formatted code. ... read »
Chuck
Nov 6, 2009 at 1:54 PM
How To Unformat Your Code (Like A Pro)
Ben great job, I happen to like your coding style and find it very easy to understand and follow. @Nathan, I totally agree, I (like the rest of you I assume) am pretty meticulous when it comes to c ... read »