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) View Comments

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.


Most Recent Comments
CFDJ News Desk 06/20/06 03:31:57 PM EDT

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.

IoT & Smart Cities Stories
The challenges of aggregating data from consumer-oriented devices, such as wearable technologies and smart thermostats, are fairly well-understood. However, there are a new set of challenges for IoT devices that generate megabytes or gigabytes of data per second. Certainly, the infrastructure will have to change, as those volumes of data will likely overwhelm the available bandwidth for aggregating the data into a central repository. Ochandarena discusses a whole new way to think about your next...
DXWorldEXPO LLC announced today that Big Data Federation to Exhibit at the 22nd International CloudEXPO, colocated with DevOpsSUMMIT and DXWorldEXPO, November 12-13, 2018 in New York City. Big Data Federation, Inc. develops and applies artificial intelligence to predict financial and economic events that matter. The company uncovers patterns and precise drivers of performance and outcomes with the aid of machine-learning algorithms, big data, and fundamental analysis. Their products are deployed...
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...
All in Mobile is a place where we continually maximize their impact by fostering understanding, empathy, insights, creativity and joy. They believe that a truly useful and desirable mobile app doesn't need the brightest idea or the most advanced technology. A great product begins with understanding people. It's easy to think that customers will love your app, but can you justify it? They make sure your final app is something that users truly want and need. The only way to do this is by ...
CloudEXPO | DevOpsSUMMIT | DXWorldEXPO are the world's most influential, independent events where Cloud Computing was coined and where technology buyers and vendors meet to experience and discuss the big picture of Digital Transformation and all of the strategies, tactics, and tools they need to realize their goals. Sponsors of DXWorldEXPO | CloudEXPO benefit from unmatched branding, profile building and lead generation opportunities.
Digital Transformation and Disruption, Amazon Style - What You Can Learn. Chris Kocher is a co-founder of Grey Heron, a management and strategic marketing consulting firm. He has 25+ years in both strategic and hands-on operating experience helping executives and investors build revenues and shareholder value. He has consulted with over 130 companies on innovating with new business models, product strategies and monetization. Chris has held management positions at HP and Symantec in addition to ...
Cell networks have the advantage of long-range communications, reaching an estimated 90% of the world. But cell networks such as 2G, 3G and LTE consume lots of power and were designed for connecting people. They are not optimized for low- or battery-powered devices or for IoT applications with infrequently transmitted data. Cell IoT modules that support narrow-band IoT and 4G cell networks will enable cell connectivity, device management, and app enablement for low-power wide-area network IoT. B...
The hierarchical architecture that distributes "compute" within the network specially at the edge can enable new services by harnessing emerging technologies. But Edge-Compute comes at increased cost that needs to be managed and potentially augmented by creative architecture solutions as there will always a catching-up with the capacity demands. Processing power in smartphones has enhanced YoY and there is increasingly spare compute capacity that can be potentially pooled. Uber has successfully ...
SYS-CON Events announced today that CrowdReviews.com has been named “Media Sponsor” of SYS-CON's 22nd International Cloud Expo, which will take place on June 5–7, 2018, at the Javits Center in New York City, NY. CrowdReviews.com is a transparent online platform for determining which products and services are the best based on the opinion of the crowd. The crowd consists of Internet users that have experienced products and services first-hand and have an interest in letting other potential buye...
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...