Creating Web services with ColdFusion MX, Macromedia’s new application server, is remarkably easy. In this article, I’ll show you that CFMX makes it simple to consume Web services from other systems as well.
Calling a Web service
In a previous article, I demonstrated how to utilize the CFINVOKE tag to call a ColdFusion Component. CFINVOKE is also used to call non-Cold Fusion services from public sites or other sources. For this example, I’ll call Headline Grabber Web service from slashdot.org. This Web service will return an XML packet with information on the latest headlines at Slashdot.org.
Looking for services?
I found this web service at a handy Xmethods repository. You can already find many different web services at this valuable site.
The code to invoke our target Web service is extremely simple, as you can see in Listing A.
This returns the XML data as a variable called SlashdotHeadlines. The XML packet resembles Listing B (formatting added for readability).
Taming the XML
At this point you might think, “So I’ve got the headlines as XML…but now what?” Well, we have a couple of options. ColdFusion MX includes a number of functions and tags devoted to manipulating XML data.
|This is a visual representation of the ColdFusion XML document object structure. I used the CFDUMP tag to generate the table.|
I’ll use the XMLParse() function to parse raw XML into a ColdFusion XML document object as shown in Figure A. Once I’ve parsed the XML object, I can reference any node in it with ColdFusion’s structure syntax, as shown in Listing C.
The code in Listing C outputs the headline of the second story in our XML object:
Transforming the XML
We’re now free to use many of the CFML structure functions on our parsed XML object. We could also loop over it and output the data. And all this has been accomplished with about five lines of CFML code. Another option is to apply an XSL stylesheet transformation to the XML data. CFMX makes this approach a snap, as you can see in Listing D.
If you are interested, the code for our very basic XSL stylesheet is available in Listing E.
The output after the XSL stylesheet has been applied to the XML data would appear as:
Title: Pacebook Tablet PC
Time: 2002-05-18 13:46:26
Title: A Shogi Champion Turns to Chess
Time: 2002-05-18 12:24:37
Title: Zeppelins on Patrol?
Time: 2002-05-18 09:11:37
ColdFusion MX loves XML
As the number of available public Web services grows daily, so does the opportunity to interface with them and save yourself a little time. Thankfully, ColdFusion MX simplifies calls to Web services, and it makes handling the resulting XML data a breeze.