I just discovered a neat feature of CF9. Sometimes when calling a built in function or even a custom method, you get returned an array. But sometimes you only need one element in that array. In Perl and other languages its possible to directly access the element you want. I’m glad to see this has been added to ColdFusion9.

For example, lets say you need the second particular element in an XML document. You might fetch some XML with cffeed and then use XMLSearch() to get all the matching elements. Then reference the second element of the resulting array, like this:

<cffeed source = "http://weather.yahooapis.com/forecastrss?p=90210" xmlVar= "myXML">

<cfset Forecasts =
     xmlSearch(myXML,"//*[local-name()='forecast' and namespace-uri()='http://xml.weather.yahoo.com/ns/rss/1.0']")>

<cfset theForecastIwant = Forecasts[2]>

In CF9 you can take a little shortcut, like you can in many other languages:

<cffeed source = "http://weather.yahooapis.com/forecastrss?p=90210" xmlVar= "myXML">

<cfset theForecastIwant =
     "//*[local-name()='forecast' and namespace-uri()='http://xml.weather.yahoo.com/ns/rss/1.0']")[2]>

Nice! This probably happened when the team added the anonymous variables feature.

And if you are wondering, this works fine in Railo 3.1 but not in OpenBD 1.1.

Leave a Reply

You must be logged in to post a comment.