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.

@ThingsExpo Stories
"MobiDev is a software development company and we do complex, custom software development for everybody from entrepreneurs to large enterprises," explained Alan Winters, U.S. Head of Business Development at MobiDev, in this SYS-CON.tv interview at 21st Cloud Expo, held Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA.
Major trends and emerging technologies – from virtual reality and IoT, to Big Data and algorithms – are helping organizations innovate in the digital era. However, to create real business value, IT must think beyond the ‘what’ of digital transformation to the ‘how’ to harness emerging trends, innovation and disruption. Architecture is the key that underpins and ties all these efforts together. In the digital age, it’s important to invest in architecture, extend the enterprise footprint to the cl...
Data is the fuel that drives the machine learning algorithmic engines and ultimately provides the business value. In his session at Cloud Expo, Ed Featherston, a director and senior enterprise architect at Collaborative Consulting, discussed the key considerations around quality, volume, timeliness, and pedigree that must be dealt with in order to properly fuel that engine.
Two weeks ago (November 3-5), I attended the Cloud Expo Silicon Valley as a speaker, where I presented on the security and privacy due diligence requirements for cloud solutions. Cloud security is a topical issue for every CIO, CISO, and technology buyer. Decision-makers are always looking for insights on how to mitigate the security risks of implementing and using cloud solutions. Based on the presentation topics covered at the conference, as well as the general discussions heard between sessio...
IoT is rapidly becoming mainstream as more and more investments are made into the platforms and technology. As this movement continues to expand and gain momentum it creates a massive wall of noise that can be difficult to sift through. Unfortunately, this inevitably makes IoT less approachable for people to get started with and can hamper efforts to integrate this key technology into your own portfolio. There are so many connected products already in place today with many hundreds more on the h...
No hype cycles or predictions of zillions of things here. IoT is big. You get it. You know your business and have great ideas for a business transformation strategy. What comes next? Time to make it happen. In his session at @ThingsExpo, Jay Mason, Associate Partner at M&S Consulting, presented a step-by-step plan to develop your technology implementation strategy. He discussed the evaluation of communication standards and IoT messaging protocols, data analytics considerations, edge-to-cloud tec...
Announcing Poland #DigitalTransformation Pavilion
Digital Transformation is much more than a buzzword. The radical shift to digital mechanisms for almost every process is evident across all industries and verticals. This is often especially true in financial services, where the legacy environment is many times unable to keep up with the rapidly shifting demands of the consumer. The constant pressure to provide complete, omnichannel delivery of customer-facing solutions to meet both regulatory and customer demands is putting enormous pressure on...
CloudEXPO | 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.
DXWorldEXPO LLC announced today that All in Mobile, a mobile app development company from Poland, will exhibit at the 22nd International CloudEXPO | DXWorldEXPO. All In Mobile is a mobile app development company from Poland. Since 2014, they maintain passion for developing mobile applications for enterprises and startups worldwide.
The best way to leverage your CloudEXPO | DXWorldEXPO presence as a sponsor and exhibitor is to plan your news announcements around our events. The press covering CloudEXPO | DXWorldEXPO will have access to these releases and will amplify your news announcements. More than two dozen Cloud companies either set deals at our shows or have announced their mergers and acquisitions at CloudEXPO. Product announcements during our show provide your company with the most reach through our targeted audienc...
@DevOpsSummit at Cloud Expo, taking place November 12-13 in New York City, NY, is co-located with 22nd international CloudEXPO | first international DXWorldEXPO and will feature technical sessions from a rock star conference faculty and the leading industry players in the world.
Everything run by electricity will eventually be connected to the Internet. Get ahead of the Internet of Things revolution. In his session at @ThingsExpo, Akvelon expert and IoT industry leader Sergey Grebnov provided an educational dive into the world of managing your home, workplace and all the devices they contain with the power of machine-based AI and intelligent Bot services for a completely streamlined experience.
DXWorldEXPO | CloudEXPO 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.
22nd International Cloud Expo, taking place June 5-7, 2018, at the Javits Center in New York City, NY, and co-located with the 1st DXWorld Expo will feature technical sessions from a rock star conference faculty and the leading industry players in the world. Cloud computing is now being embraced by a majority of enterprises of all sizes. Yesterday's debate about public vs. private has transformed into the reality of hybrid cloud: a recent survey shows that 74% of enterprises have a hybrid cloud ...
In his keynote at 19th Cloud Expo, Sheng Liang, co-founder and CEO of Rancher Labs, discussed the technological advances and new business opportunities created by the rapid adoption of containers. With the success of Amazon Web Services (AWS) and various open source technologies used to build private clouds, cloud computing has become an essential component of IT strategy. However, users continue to face challenges in implementing clouds, as older technologies evolve and newer ones like Docker c...
JETRO showcased Japan Digital Transformation Pavilion at SYS-CON's 21st International Cloud Expo® at the Santa Clara Convention Center in Santa Clara, CA. The Japan External Trade Organization (JETRO) is a non-profit organization that provides business support services to companies expanding to Japan. With the support of JETRO's dedicated staff, clients can incorporate their business; receive visa, immigration, and HR support; find dedicated office space; identify local government subsidies; get...
Dion Hinchcliffe is an internationally recognized digital expert, bestselling book author, frequent keynote speaker, analyst, futurist, and transformation expert based in Washington, DC. He is currently Chief Strategy Officer at the industry-leading digital strategy and online community solutions firm, 7Summits.
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...
In past @ThingsExpo presentations, Joseph di Paolantonio has explored how various Internet of Things (IoT) and data management and analytics (DMA) solution spaces will come together as sensor analytics ecosystems. This year, in his session at @ThingsExpo, Joseph di Paolantonio from DataArchon, added the numerous Transportation areas, from autonomous vehicles to “Uber for containers.” While IoT data in any one area of Transportation will have a huge impact in that area, combining sensor analytic...