HTML5 Zone is brought to you in partnership with:

Raymond Camden is a developer evangelist for Adobe. His work focuses on web standards, mobile development and Cold Fusion. He's a published author and presents at conferences and user groups on a variety of topics. He is the happily married proud father of three kids and is somewhat of a Star Wars nut. Raymond can be reached via his blog at www.raymondcamden.com or via email at raymondcamden@gmail.com Raymond is a DZone MVB and is not an employee of DZone and has posted 254 posts at DZone. You can read more from them at their website. View Full User Profile

ColdFusion Quickie - Turning a set of XML nodes into a string.

01.04.2013
| 2562 views |
  • submit to reddit

Yesterday a reader sent me a question concerning XML handling and ColdFusion, and while it was rather simple, I thought others might like to see a quick demo of it as well. Imagine for a minute this simple XML data.

<article title="The Title">
  <author>
		<name>Raymond Camden</name>
		<email>raymondcamden@gmail.com</email>
	</author>
	<body>
		<paragraph>
			This is some text. Woot.
		</paragraph>
		<paragraph>
			Another paragraph of text.
		</paragraph>
		<paragraph>
			Getting tired of making stuff up.
		</paragraph>
		<paragraph>
			I should be working on my presentation.
		</paragraph>
	</body>
</article>

The XML above describes a simple article. You've got a title, an author object, and paragraphs of text each as their own XML node. The reader simply wanted to know how to get those paragraphs into one string variable. You may be tempted to do this:

<cfset paragraphs = articleOb.article.body.paragraph>

But doing so returns you one XML node.

One of the oddities of ColdFusion's XML handling is that it treats some things as a singular value and some things like an array. So if I take the same "address" and run arrayLen() on it, like so...

<cfdump var="#arrayLen(articleOb.article.body.paragraph)#">

I'll get 4. This is the clue then that tells us to simply loop over them like an array and append each value to a string.

<cfset text = "">
<cfloop index="p" array="#articleOb.article.body.paragraph#">
  <cfset text &= "<p>" & p.xmlText & "</p>">
</cfloop>

<cfoutput>#text#</cfoutput>

Note that I've also wrapped the values in P tags to help me display it later.



Published at DZone with permission of Raymond Camden, author and DZone MVB. (source)

(Note: Opinions expressed in this article and its replies are the opinions of their respective authors and not those of DZone, Inc.)