Welcome!

You will be redirected in 30 seconds or close now.

ColdFusion Authors: Yakov Fain, Jeremy Geelan, Maureen O'Gara, Nancy Y. Nee, Tad Anderson

Related Topics: ColdFusion, Industrial IoT, Adobe Flex

ColdFusion: Article

Advanced XML Processing with StAX in ColdFusion

A powerful, fast, and efficient alternative to other ways of XML parsing

Putting support for XML processing in ColdFusion 6.0 was regarded as a major feature upgrade. With the switch to Java, ColdFusion could leverage the existing Java functions in Jakarta Commons and add support for things like Web Services (Axis). However, binding itself to Java also bound ColdFusion to the limitations of the Java feature set.

When MX was released, the Xerxes XML parser was state-of-the-art. Java XML processing has advanced significantly since then. This article will discuss these new developments and show how you, the developer, can leverage them from ColdFusion. Some experience with creating and using Java objects with ColdFusion will help but isn't required.

Conventional CFXML
Let's look at a trivial example of using ColdFusion XML functions to parse an XML object. ColdFusion Developers Journal (CFDJ) provides an RSS feed for published authors with a list of their articles. We will use the RSS feed for Nic Tunney, the developer of ObjectBreeze, as our sample XML. Some people are under the impression that XML has to be stored in a file to be processed but this is not the case.

RSS, ATOM, and even well formed XHTML work quite well. The RSS feed is in XML and contains various elements. Like other RSS feeds, the root element is "rss," with XmlText, XmlAttributes, and the channel as elements under the rss root. These elements are shown in Figure 1.

The channel element contains the information that we're interested in. You will see that the channel element contains repeated "item" elements corresponding to each article Nic Tunney has written for CFDJ. This item element contains the article title, a URL to the article, a publication date, and a description. The Coldfusion code to get this information is simple and is in Listing 1. It results in the output shown in Figure 2.

Here we've used the DOM to extract the information we want. This information could also be extracted using XPath or an XSLT stylesheet. So what's going on here? A CFDump of a ColdFusion XML document using <cfdump var="#MyXML.getClass().getName()#"/> will show that MyXML is a Java object of type org.apache.xerces.dom.DeferredDocumentImpl. ColdFusion has retrieved the entire RSS object and created a DOM (Document Object Model) representation of it in memory. A complete guide to the structure of a ColdFusion XML Object can be found at Click Here!. This is the result we would expect because ColdFusion uses the Xerxes parser (part of the Apache XML Project) to achieve this, and Xerces is a DOM parser.

What does this mean? The first method of parsing for XML was DOM parsing. In this model the entire XML file (or feed) is read and a DOM object is created in memory. For this reason, the DOM is referred to as a "tree-based API" because it creates an object resembling a tree in memory. Although this method is simple and straightforward, it has problems associated with it. This is an example of H.L. Mencken's observation that "For every problem there is a solution which is simple, clean, and wrong." Reading in the entire document is excess processing overhead, especially if we're only interested in part of the document. To add insult to injury, the DOM object created by Xerces can be two to three times larger than the original XML document.

Another issue with this approach is that frequently the developer will need a different data structure than the one made available by the DOM. It's very inefficient to build a DOM tree and then create a new data structure and discard the original. The DOM model fails when the XML source is very large and can crash ColdFusion. Reading and creating the DOM in memory is also...very...slow.

SAX
As a solution to these problems, the xml-users mailing list under the leadership of David Megginson created something called SAX. SAX stands for Simple API for XML. SAX reads the XML feed line-by-line and fires off events based on the type of line read. For this reason SAX is referred to as an "event-based API." Developing in SAX is somewhat odd to the newcomer used to calling functions in the API to achieve his objectives. SAX uses callback functions (your register is a ContentHandler with the parser) that are registered with the SAX parser. The XML processing logic is usually stored inside these callback functions. More specifically, the SAX developer will write a ContentHandler interface that contains methods such as startDocument(), endDocument(), startElement(), etc. corresponding to the events encountered by the SAX parser.

SAX has a very lightweight memory and processing footprint, and is very fast. Now, this is all well and good but there are still some problems. For one, the callback issue. There's no way in ColdFusion to add a ColdFusion function as a called method. This isn't a ColdFusion limitation. Java developers find using callback methods counter-intuitive. It's like driving in reverse. SAX also still processes the entire document. There's a way to stop processing by throwing an error, but that's like stopping your car by ramming it into a crash barrier. It works but it's probably not optimal. Another drawback is that the programmer must keep track of the current state of the document in the code each time he processes an XML document. SAX isn't completely useless to ColdFusion developers, however. For instance, ColdFusion itself probably uses SAX to validate XML documents.

My primary reason for discussing SAX was to introduce you to some basic concepts that are used in another model, StAX, that are very useful to the ColdFusion developer.

StAX
It's commonly said, "The third time's the charm." Although I suspect this has more relevance for interpersonal relationships, it applies equally well to software development. Dissatisfaction with the limitations of SAX led to the development of a third XML processing approach called StAX, and this time the designers got it right. StAX stands for Streaming API for XML. Unlike SAX, StAX is a "pull" parser, which means is that you control the rate at which the XML document is parsed, or if parsing should continue at all, once you've found the information you need. If you've done the operations that you want to do on the document, you can simply stop processing it.

One of the great things about StAX is it can process an XML source of any size. And, it's very, very fast. StAX is implemented by using a standard API, which is then implemented by the specific StAX parser. The StAX standard API is defined by JSR 173, which can be found at www.jcp.org/en/jsr/detail?id=173.

StAX is supported by a number of vendors such as Sun, Oracle, and BEA, each of which has released its own implementation. The Open Source community is also very active in StAX development, with Tatu Salorama's Woodstox being the leader. Woodstox will be the implementation used in the examples that follow. Woodstox is available for download at http://woodstox.codehaus.org/. These examples will use a CFC that I've developed called CFStAX. The purpose of this wrapper is to make it easy to work with StAX even if you're uncomfortable working with Java APIs, and to simplify some of the setup required. CFStAX is available at www.sourceforge.com/projects/cfsynergy. CFStAX uses Woodstox and was developed with the time and help of Tatu Salorama, its author.

StAX offers two models for processing XML, a Stream model and an Event model. These are also referred to as the cursor-style API and the Iterator-style API, respectively. In the Stream Model, the XML source is parsed using the XMLStreamReader object. The XMLStreamReader.next() method returns an integer value corresponding to the event type of the XML object encountered, i.e., start_document, start_element, etc. You can write a series of elseif statements to take various actions based on the event returned by XMLStreamReader.next(). The Stream model is the model most used in StAX primarily because of its simplicity.

Using the Event model, an XMLEventReader delivers XMLEvent objects using its next() method. Again, events of interest can be handled by a series of elseif statements. The XMLEventReader is particularly elegant for doing XML-to-XML transformations. There's a reason in both cases for using a series of elseif statements. A case statement is difficult to implement because of ColdFusion's lack of support for static variables. If we could do cfswitch(XMLStreamReader.getEventType() ) then we could use switch statements.

Examples
Using StAX is easy. The first step is to put the relevant jar files on the classpath. All StAX implementations consist of two files, a reference API that sets up the standard APIs for StAX, and an implementation file that contains how that particular implementation implements the API calls. If you're using Woodstox these files will be STAX2.JAR and wstx-asl-2.9.3.jar (ASL 2.0) or wstx-lgpl-2.9.3.jar (LGPL 2.1). The latter two files differ only in their licensing terms. I put mine on the path C:\JRun4\servers\cfusion\cfusion-ear\cfusion-war\WEB-INF\lib because I don't like to add to the core files. This lets me add and remove testing files from the classpath without having to worry about disturbing the core files.

Once the jar files have been added to the classpath, the jrun service must be restarted. Now that we have set up our system, we can go through some StAX usage examples and see how powerful this technique is.

Reading XML with StAX
For these examples we'll return to the RSS feed we used before to power our CFStAX examples. They're in CFScript because CFScript is syntactically closer to the original Java code and is easier to port existing Java code to, for me anyway. The way our original code looks using the StAX processing model with the Stream Model is in Listing 2. It's a raw implementation to show STaX processing. The CFStax equivalent would encapsulate much of this.

The Event model is similar but uses methods to determine the event properties. See Listing 3. Note that this EventStream code can cause a problem in certain cases, throwing a QName error. This is a known problem and will be addressed in a future release of CFStaX.

Writing and merging XML are other functions frequently used, and are very easy to do using StAX but are beyond the scope of this article. Full examples are available in the documentation provided with CFStAX.

Conclusion
StAX is a powerful, fast, and efficient alternative to other methods of XML parsing and should be in the toolkit of anyone responsible for processing XML on a regular basis.

References
Jeffry Houser. "Using XML in ColdFusion." http://coldfusion.sys-con.com/read/117667.htm

Processing XML with Java (complete book online). www.cafeconleche.org/books/xmljava/

Elliotte Rusty Harold. "An Introduction to StAX." September 17, 2003. www.xml.com/pub/a/2003/09/17/stax.html

Lara D'Abreo. "StAX: DOM Ease with SAX Efficiency."January 11, 2006. www.devx.com/Java/Article/30298

More Stories By Jim Collins

Jim Collins is a ColdFusion Developer with 15 years of experience in IT and software development. He can be reached at [email protected] and his profile is available at https://www.linkedin.com/in/jimcollins.
His blog, covering ColdFusion and Java integration is located at http://www.cfsynergy.com

Comments (1)

Share your thoughts on this story.

Add your comment
You must be signed in to add a comment. Sign-in | Register

In accordance with our Comment Policy, we encourage comments that are on topic, relevant and to-the-point. We will remove comments that include profanity, personal attacks, racial slurs, threats of violence, or other inappropriate material that violates our Terms and Conditions, and will block users who make repeated violations. We ask all readers to expect diversity of opinion and to treat one another with dignity and respect.


IoT & Smart Cities Stories
In his general session at 19th Cloud Expo, Manish Dixit, VP of Product and Engineering at Dice, discussed how Dice leverages data insights and tools to help both tech professionals and recruiters better understand how skills relate to each other and which skills are in high demand using interactive visualizations and salary indicator tools to maximize earning potential. Manish Dixit is VP of Product and Engineering at Dice. As the leader of the Product, Engineering and Data Sciences team at D...
Bill Schmarzo, Tech Chair of "Big Data | Analytics" of upcoming CloudEXPO | DXWorldEXPO New York (November 12-13, 2018, New York City) today announced the outline and schedule of the track. "The track has been designed in experience/degree order," said Schmarzo. "So, that folks who attend the entire track can leave the conference with some of the skills necessary to get their work done when they get back to their offices. It actually ties back to some work that I'm doing at the University of San...
When talking IoT we often focus on the devices, the sensors, the hardware itself. The new smart appliances, the new smart or self-driving cars (which are amalgamations of many ‘things'). When we are looking at the world of IoT, we should take a step back, look at the big picture. What value are these devices providing. IoT is not about the devices, its about the data consumed and generated. The devices are tools, mechanisms, conduits. This paper discusses the considerations when dealing with the...
Bill Schmarzo, author of "Big Data: Understanding How Data Powers Big Business" and "Big Data MBA: Driving Business Strategies with Data Science," is responsible for setting the strategy and defining the Big Data service offerings and capabilities for EMC Global Services Big Data Practice. As the CTO for the Big Data Practice, he is responsible for working with organizations to help them identify where and how to start their big data journeys. He's written several white papers, is an avid blogge...
Dynatrace is an application performance management software company with products for the information technology departments and digital business owners of medium and large businesses. Building the Future of Monitoring with Artificial Intelligence. Today we can collect lots and lots of performance data. We build beautiful dashboards and even have fancy query languages to access and transform the data. Still performance data is a secret language only a couple of people understand. The more busine...
If a machine can invent, does this mean the end of the patent system as we know it? The patent system, both in the US and Europe, allows companies to protect their inventions and helps foster innovation. However, Artificial Intelligence (AI) could be set to disrupt the patent system as we know it. This talk will examine how AI may change the patent landscape in the years to come. Furthermore, ways in which companies can best protect their AI related inventions will be examined from both a US and...
Enterprises have taken advantage of IoT to achieve important revenue and cost advantages. What is less apparent is how incumbent enterprises operating at scale have, following success with IoT, built analytic, operations management and software development capabilities - ranging from autonomous vehicles to manageable robotics installations. They have embraced these capabilities as if they were Silicon Valley startups.
Chris Matthieu is the President & CEO of Computes, inc. He brings 30 years of experience in development and launches of disruptive technologies to create new market opportunities as well as enhance enterprise product portfolios with emerging technologies. His most recent venture was Octoblu, a cross-protocol Internet of Things (IoT) mesh network platform, acquired by Citrix. Prior to co-founding Octoblu, Chris was founder of Nodester, an open-source Node.JS PaaS which was acquired by AppFog and ...
The deluge of IoT sensor data collected from connected devices and the powerful AI required to make that data actionable are giving rise to a hybrid ecosystem in which cloud, on-prem and edge processes become interweaved. Attendees will learn how emerging composable infrastructure solutions deliver the adaptive architecture needed to manage this new data reality. Machine learning algorithms can better anticipate data storms and automate resources to support surges, including fully scalable GPU-c...
Cloud-enabled transformation has evolved from cost saving measure to business innovation strategy -- one that combines the cloud with cognitive capabilities to drive market disruption. Learn how you can achieve the insight and agility you need to gain a competitive advantage. Industry-acclaimed CTO and cloud expert, Shankar Kalyana presents. Only the most exceptional IBMers are appointed with the rare distinction of IBM Fellow, the highest technical honor in the company. Shankar has also receive...