Industrial IoT Authors: APM Blog, Elizabeth White, Pat Romanski, William Schmarzo, Liz McMillan

Related Topics: Industrial IoT

Industrial IoT: Article

Visiting the DOM

Extending the Visitor Pattern

It is well known that traversing the XML DOM is a sometimes difficult and often tedious task. Executing code based on data retrieved from the DOM is even more complex. This article will demonstrate one way to abstract much of the logic from this repetitive task. The implementation of patterns is a technique that is often used to help simplify and intellectually manage projects, and the Visitor Pattern is appropriate and useful to help solve this problem. Reflection also plays a key role, and is used to determine the executed code based on the DOM node names at runtime.

XML has proven itself to be useful for storing the data for many types of applications (www.oasis-open.org). However, when you get down to it, XML is just a highly structured text file. Applications that use XML as their input format must process the XML file in order to get the data from it. Currently, there are two primary APIs that applications can use to traverse an XML file: DOM and SAX.

Document Object Model
The Document Object Model (DOM) provides the most obvious way of accessing data in an XML file. An XML document is essentially a tree: the root element of the XML document is the root node of the tree, and child elements in the XML document are the children of the root node. The DOM API provides an application with a tree data-structure that directly mirrors the XML file. The DOM API provides the ability to traverse the tree from one node to the next: parent-to-child, child-to-sibling, child-to-parent, etc.

Application developers use the API to write code that traverses the tree and performs processing on the tree's nodes (e.g., extract some piece of data). The trouble with the DOM API is twofold. First (and obviously), application developers must write the code that traverses the tree. However, this is often an unnecessary re-invention of the wheel. Many applications traverse the tree in a standard depth-first approach. It is unfortunate that the developer must spend time writing the actual tree-walking code, when it has been written before by countless developers.

The second drawback of the DOM API is the integration of the tree-walking code with the node-processing code. One of the hallmarks of good software design is the separation of concerns. This means the developer tries to separate the logical pieces of the code into separate methods/functions/modules. The unfortunate design of the DOM API requires that the complex code that walks the XML tree must be interspersed with the, quite possibly, complex code to process individual nodes.

The following code fragment illustrates the complexity of processing XML nodes using the DOM API. In this example we traverse an XML tree grabbing all the "color" elements and swapping the black and white ones.

demoChildNodes = document.getElementsByTagName("color");
for (int i = 0;i < demoChildNodes.getLength(); i++) {


Simple API for XML (SAX)
The Simple API for XML (SAX), first published in 1998, was developed as an event-based API for processing XML. Hot on the heels of the XML specification itself, it was well received by the development community.

SAX works by processing the XML one node at a time, creating a streaming process opposed to a static one. Event handlers are added to an XML document much in the same way they are added to a user interface. Such events are triggered as the application processes the document. Using this technique creates a very fast processing method, with a much smaller memory profile. This makes SAX appropriate for tasks such as searching a document for a specific node, or making small change to the entire document such as search and replace.

The down side is the lack of directional control, the document can only be process red in a "top to bottom" direction. Tasks like reordering nodes and cross-referencing are not practical. Also, while the specific syntax for simple documents (or simple processing tasks) is not overwhelming, SAX does not scale well for more complicated solutions. Listing 1 is a short example (the code for this article is online at www.sys-con.com/xml/sourcec.cfm).

The other drawback to SAX is the granularity of the event handlers. SAX is "coarse-grained" in the sense that large structural XML components invoke the same handler. For example, all "element" nodes would invoke the startElement() method. Many applications require a "finer-grained" event handler. For example, invoke a specific method when an "employee" element is reached.

Visitor Pattern
The problem of separating data-structure traversal from data-structure analysis/process is well-known. One standard technique of ensuring a separation of these components is the Visitor Pattern. One way of understanding the Visitor Pattern is that it allows operations to be added to a class (the pattern is an object-oriented one) without having to actually change the class. However, in the context of tree-walking, the Visitor Pattern is best understood as providing the capability of applying an endless number of node processors to a tree without having to change the definition of the node itself: it separates the node-processing code from the node definition.

For example, assume we have a tree data structure encapsulated in a tree class. This class defines a root node class that has links to its child nodes. Using the Visitor Pattern, we can define a MyVisitor class that has a method visitNode() that performs some kind of processing at each node in the tree. However, the Visitor Pattern allows us to focus the method on the node-processing code itself, and not the tree-traversal code. Once these two classes are defined, we could "apply" our visitor to our tree with the code: my Tree.accept(my Visitor); This would start a depth-first traversal of the tree and at each Node the My Visitor.visitNode()method would be called, allowing us to apply processing to each node.

In the future, if we want to update the processing, we would only need to modify the MyVisitor class. The tree and node classes would remain untouched. If we want to perform a different kind of processing on the tree, we would simply define a MyOther Visitor class with a visitNode() method and then apply our new visitor to the tree with: myTree. accept(my Other Visitor). Once again, the existing tree and node classes are untouched.

Visiting the DOM
We have developed a prototype DOM visitor in Java that supports the Visitor Pattern. The implementation is quite straightforward. A visitoradapter class encapsulates the tree-walking code and provides for standard depth-first traversal. Obviously, this class can be overridden to provide for more complex tree traversals.

The other major component of the prototype is the alteration of the NodeImpl class and the Node interface inside org.w3c.dom, which provides for the implementation of a DOM Node. The only change necessary is the addition of an accept() method that takes a Visitor class as a parameter and invokes the appropriate visitXXX() method in the Visitor class (where XXX is the name of the element). The accept() method uses reflection to determine which method to call in the visitor. Using reflection, the visitor Pattern provides the kind of "fine-grained" visitation that most applications require.

Another benefit of the Visitor Pattern is that it combines useful features of both DOM and SAX. The Visitor Pattern is "event-driven" to the extent the specific methods are called when specific nodes are reached in the tree. Furthermore, within a specific visit method, one can use the DOM API to traverse the tree in nonlinear ways, overcoming a significant limitation of SAX.

Hopefully, you have already begun to see the ease of using the Visitor Pattern as it applies to the XML DOM. Using this Pattern the developer can define numerous DOM analyzers and processors and apply them to a DOM tree. All of the tree-walking code can be handled automatically through the adapter class.

For example, Listing 2 encodes games in a chess library.

Using a Visitor Pattern, one can intuitively visit the nodes in the XML tree and apply processing to selected elements (see Listing 3).

If other kinds of processing need to be done, then the developer must only declare a new visitor class (extending VisitorAdapter) and provide appropriate visitXXX() methods.

Extending the DOM API to support the Visitor Pattern means that XML application developers are freed from writing tree-traversal code and can focus their efforts on the processing of each XML element. Another benefit is that if several operations are required to use the same XML data, the development workload can be easily divided among several programmers. The processing workload can be split among several processors or threads as well.

Extending the Java/Xerces DOM implementation is straight-forward and we urge Sun to consider incorporating our changes into a future release of the API.


  • Gamma, Erich; Helm, Richard; Johnson, Ralph; Vlissides, John. (1995) Design Patterns: Elements of Reusable Object-Oriented Software. Addison-Wesley Professional.
  • Comments (0)

    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.

    @ThingsExpo Stories
    "Space Monkey by Vivent Smart Home is a product that is a distributed cloud-based edge storage network. Vivent Smart Home, our parent company, is a smart home provider that places a lot of hard drives across homes in North America," explained JT Olds, Director of Engineering, and Brandon Crowfeather, Product Manager, at Vivint Smart Home, in this SYS-CON.tv interview at @ThingsExpo, held Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA.
    SYS-CON Events announced today that Conference Guru has been named “Media Sponsor” of the 22nd International Cloud Expo, which will take place on June 5-7, 2018, at the Javits Center in New York, NY. A valuable conference experience generates new contacts, sales leads, potential strategic partners and potential investors; helps gather competitive intelligence and even provides inspiration for new products and services. Conference Guru works with conference organizers to pass great deals to gre...
    The Internet of Things will challenge the status quo of how IT and development organizations operate. Or will it? Certainly the fog layer of IoT requires special insights about data ontology, security and transactional integrity. But the developmental challenges are the same: People, Process and Platform. In his session at @ThingsExpo, Craig Sproule, CEO of Metavine, demonstrated how to move beyond today's coding paradigm and shared the must-have mindsets for removing complexity from the develop...
    In his Opening Keynote at 21st Cloud Expo, John Considine, General Manager of IBM Cloud Infrastructure, led attendees through the exciting evolution of the cloud. He looked at this major disruption from the perspective of technology, business models, and what this means for enterprises of all sizes. John Considine is General Manager of Cloud Infrastructure Services at IBM. In that role he is responsible for leading IBM’s public cloud infrastructure including strategy, development, and offering m...
    "Evatronix provides design services to companies that need to integrate the IoT technology in their products but they don't necessarily have the expertise, knowledge and design team to do so," explained Adam Morawiec, VP of Business Development at Evatronix, in this SYS-CON.tv interview at @ThingsExpo, held Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA.
    To get the most out of their data, successful companies are not focusing on queries and data lakes, they are actively integrating analytics into their operations with a data-first application development approach. Real-time adjustments to improve revenues, reduce costs, or mitigate risk rely on applications that minimize latency on a variety of data sources. In his session at @BigDataExpo, Jack Norris, Senior Vice President, Data and Applications at MapR Technologies, reviewed best practices to ...
    Widespread fragmentation is stalling the growth of the IIoT and making it difficult for partners to work together. The number of software platforms, apps, hardware and connectivity standards is creating paralysis among businesses that are afraid of being locked into a solution. EdgeX Foundry is unifying the community around a common IoT edge framework and an ecosystem of interoperable components.
    Large industrial manufacturing organizations are adopting the agile principles of cloud software companies. The industrial manufacturing development process has not scaled over time. Now that design CAD teams are geographically distributed, centralizing their work is key. With large multi-gigabyte projects, outdated tools have stifled industrial team agility, time-to-market milestones, and impacted P&L stakeholders.
    "Akvelon is a software development company and we also provide consultancy services to folks who are looking to scale or accelerate their engineering roadmaps," explained Jeremiah Mothersell, Marketing Manager at Akvelon, 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.
    "IBM is really all in on blockchain. We take a look at sort of the history of blockchain ledger technologies. It started out with bitcoin, Ethereum, and IBM evaluated these particular blockchain technologies and found they were anonymous and permissionless and that many companies were looking for permissioned blockchain," stated René Bostic, Technical VP of the IBM Cloud Unit in North America, in this SYS-CON.tv interview at 21st Cloud Expo, held Oct 31 – Nov 2, 2017, at the Santa Clara Conventi...
    In his session at 21st Cloud Expo, Carl J. Levine, Senior Technical Evangelist for NS1, will objectively discuss how DNS is used to solve Digital Transformation challenges in large SaaS applications, CDNs, AdTech platforms, and other demanding use cases. Carl J. Levine is the Senior Technical Evangelist for NS1. A veteran of the Internet Infrastructure space, he has over a decade of experience with startups, networking protocols and Internet infrastructure, combined with the unique ability to it...
    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 ...
    "Cloud Academy is an enterprise training platform for the cloud, specifically public clouds. We offer guided learning experiences on AWS, Azure, Google Cloud and all the surrounding methodologies and technologies that you need to know and your teams need to know in order to leverage the full benefits of the cloud," explained Alex Brower, VP of Marketing at Cloud Academy, in this SYS-CON.tv interview at 21st Cloud Expo, held Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clar...
    Gemini is Yahoo’s native and search advertising platform. To ensure the quality of a complex distributed system that spans multiple products and components and across various desktop websites and mobile app and web experiences – both Yahoo owned and operated and third-party syndication (supply), with complex interaction with more than a billion users and numerous advertisers globally (demand) – it becomes imperative to automate a set of end-to-end tests 24x7 to detect bugs and regression. In th...
    "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.
    Coca-Cola’s Google powered digital signage system lays the groundwork for a more valuable connection between Coke and its customers. Digital signs pair software with high-resolution displays so that a message can be changed instantly based on what the operator wants to communicate or sell. In their Day 3 Keynote at 21st Cloud Expo, Greg Chambers, Global Group Director, Digital Innovation, Coca-Cola, and Vidya Nagarajan, a Senior Product Manager at Google, discussed how from store operations and ...
    "There's plenty of bandwidth out there but it's never in the right place. So what Cedexis does is uses data to work out the best pathways to get data from the origin to the person who wants to get it," explained Simon Jones, Evangelist and Head of Marketing at Cedexis, 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.
    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...
    SYS-CON Events announced today that Telecom Reseller 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, NY. Telecom Reseller reports on Unified Communications, UCaaS, BPaaS for enterprise and SMBs. They report extensively on both customer premises based solutions such as IP-PBX as well as cloud based and hosted platforms.
    It is of utmost importance for the future success of WebRTC to ensure that interoperability is operational between web browsers and any WebRTC-compliant client. To be guaranteed as operational and effective, interoperability must be tested extensively by establishing WebRTC data and media connections between different web browsers running on different devices and operating systems. In his session at WebRTC Summit at @ThingsExpo, Dr. Alex Gouaillard, CEO and Founder of CoSMo Software, presented ...