Looping over an array with XML objects - CF8 versus CF9

This post is more than 2 years old.

Here is an interesting little issue I ran into. Given the following simple XML (and I'm typing this on the fly so pardon any typos), imagine you want to loop over the people nodes:

<root> <people /> <people /> <people /> </root>

ColdFusion allows you to treat the people nodes as an array. You can access the second people node by using xmlVar.people[2]. Most folks though will typically want to iterate over each person. Using CFLOOP and it's new array syntax, you might do it like so:

<cfloop index="person" array="#people#"> do stuff </cfloop>

While this works perfectly well in ColdFusion 9, in ColdFusion 8 it fails. The person object is a Java object of the class org.apache.xerces.dom.DeferredElementNSImpl. Now I won't pretend to know how that differs exactly from ColdFusion 9, but the point is, you can't use it in the same way you can with ColdFusion 9.

Of course, the fix for ColdFusion 8 is trivial - change your cfloop to:

<cfloop index="x" from="1" to="#arrayLen(people)#"> <cfset person = people[x]>

Raymond Camden's Picture

About Raymond Camden

Raymond is a developer advocate for HERE Technologies. He focuses on JavaScript, serverless and enterprise cat demos. If you like this article, please consider visiting my Amazon Wishlist or donating via PayPal to show your support. You can even buy me a coffee!

Lafayette, LA https://www.raymondcamden.com