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
The platform combines the strengths of Singtel's extensive, intelligent network capabilities with Microsoft's cloud expertise to create a unique solution that sets new standards for IoT applications," said Mr Diomedes Kastanis, Head of IoT at Singtel. "Our solution provides speed, transparency and flexibility, paving the way for a more pervasive use of IoT to accelerate enterprises' digitalisation efforts. AI-powered intelligent connectivity over Microsoft Azure will be the fastest connected pat...
There are many examples of disruption in consumer space – Uber disrupting the cab industry, Airbnb disrupting the hospitality industry and so on; but have you wondered who is disrupting support and operations? AISERA helps make businesses and customers successful by offering consumer-like user experience for support and operations. We have built the world’s first AI-driven IT / HR / Cloud / Customer Support and Operations solution.
Codete accelerates their clients growth through technological expertise and experience. Codite team works with organizations to meet the challenges that digitalization presents. Their clients include digital start-ups as well as established enterprises in the IT industry. To stay competitive in a highly innovative IT industry, strong R&D departments and bold spin-off initiatives is a must. Codete Data Science and Software Architects teams help corporate clients to stay up to date with the mod...
At CloudEXPO Silicon Valley, June 24-26, 2019, Digital Transformation (DX) is a major focus with expanded DevOpsSUMMIT and FinTechEXPO programs within the DXWorldEXPO agenda. Successful transformation requires a laser focus on being data-driven and on using all the tools available that enable transformation if they plan to survive over the long term. A total of 88% of Fortune 500 companies from a generation ago are now out of business. Only 12% still survive. Similar percentages are found throug...
Druva is the global leader in Cloud Data Protection and Management, delivering the industry's first data management-as-a-service solution that aggregates data from endpoints, servers and cloud applications and leverages the public cloud to offer a single pane of glass to enable data protection, governance and intelligence-dramatically increasing the availability and visibility of business critical information, while reducing the risk, cost and complexity of managing and protecting it. Druva's...
BMC has unmatched experience in IT management, supporting 92 of the Forbes Global 100, and earning recognition as an ITSM Gartner Magic Quadrant Leader for five years running. Our solutions offer speed, agility, and efficiency to tackle business challenges in the areas of service management, automation, operations, and the mainframe.
The Jevons Paradox suggests that when technological advances increase efficiency of a resource, it results in an overall increase in consumption. Writing on the increased use of coal as a result of technological improvements, 19th-century economist William Stanley Jevons found that these improvements led to the development of new ways to utilize coal. In his session at 19th Cloud Expo, Mark Thiele, Chief Strategy Officer for Apcera, compared the Jevons Paradox to modern-day enterprise IT, examin...
With 10 simultaneous tracks, keynotes, general sessions and targeted breakout classes, @CloudEXPO and DXWorldEXPO are two of the most important technology events of the year. Since its launch over eight years ago, @CloudEXPO and DXWorldEXPO have presented a rock star faculty as well as showcased hundreds of sponsors and exhibitors! In this blog post, we provide 7 tips on how, as part of our world-class faculty, you can deliver one of the most popular sessions at our events. But before reading...
DSR is a supplier of project management, consultancy services and IT solutions that increase effectiveness of a company's operations in the production sector. The company combines in-depth knowledge of international companies with expert knowledge utilising IT tools that support manufacturing and distribution processes. DSR ensures optimization and integration of internal processes which is necessary for companies to grow rapidly. The rapid growth is possible thanks, to specialized services an...
At CloudEXPO Silicon Valley, June 24-26, 2019, Digital Transformation (DX) is a major focus with expanded DevOpsSUMMIT and FinTechEXPO programs within the DXWorldEXPO agenda. Successful transformation requires a laser focus on being data-driven and on using all the tools available that enable transformation if they plan to survive over the long term. A total of 88% of Fortune 500 companies from a generation ago are now out of business. Only 12% still survive. Similar percentages are found throug...