Over a million developers have joined DZone.
Platinum Partner

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

· Web Dev Zone

The Web Dev Zone is brought to you in partnership with Mendix.  Discover how IT departments looking for ways to keep up with demand for business apps has caused a new breed of developers to surface - the Rapid Application Developer.

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">
		<name>Raymond Camden</name>
			This is some text. Woot.
			Another paragraph of text.
			Getting tired of making stuff up.
			I should be working on my presentation.

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>">


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

The Web Dev Zone is brought to you in partnership with Mendix.  Learn more about The Essentials of Digital Innovation and how it needs to be at the heart of every organization.


Published at DZone with permission of Raymond Camden , DZone MVB .

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}