ColdFusion - XmlAttributes and StructKey names
I’ve been playing around with the Tumblr API for a while, reading in tags and other things. I wanted to start storing my content, for later use, or in case anything ever happened to Tumblr. The last thing I need is to wake up one morning and discover a giant ad running on my site. For some time now, I have been reading and parsing the JSON version of the API. But, if I really wanted to interact with my ColdFusion server and store data, I needed to start taking a more in-depth look at the standard XML API. The first thing I noticed, is that there are lots of XML elements that have dashes. I’m not a fan of using dashes for anything, especially not XML element names. In a past life, I did use underscores a great deal, but I now have moved entirely to camel case conventions.
In any case, dashes have always caused problems for me, especially when parsing XML with ColdFusion. If we read in the API like this:
<cfset myDoc=XMLParse("http://tumblr.themadness.org/api/read?start=#startAt#&num=50")>
We’ll get back a piece of data like this:
You’ll notice that post->XmlAttributes contains an element called “unix-timestamp”. I prefer to use unixtime whenever possible. It’s more portable and easier to work with.
Normally, I would do something such as this to loop over all the records:<cfset numRecs = arrayLen(myDoc.tumblr.posts.post)>
<cfloop from="1" to="#numRecs#" index="i">
#mydoc.tumblr.posts.post[i].XmlAttributes.type#
<cfloop>
However, if you reference unix-timestamp this way, it will generate an error. Instead, it needs to be referenced as: #mydoc.tumblr.posts.post[i].XmlAttributes['unix-timestamp']#
Like everything else in ColdFusion, XML data is nothing more than a structure, and can always be referenced the same way as other structures. Once you more away from thinking of ColdFusion as just a tag system, and think of it more as a scripting language based around structures, you can accomplish almost anything with it.







