Efficient XML Processing Using SAX and Java Enums
Join the DZone community and get the full member experience.
Join For FreeI had a chance to do some XML crunching lately. I used a design pattern for this purpose which is both efficient and elegant. I'm not sure who thought of this first, so I won't name it after myself (:-), but it's well worth writing about it.
Very Short Introduction to XML Processing in Java
To refresh your memory, here's a short overview of the popular ways for working with XMLs in Java. Briefly, there are two leading methods:
- SAX - Simple API for XML - event driven method where you write a processor which receives events while the XML is being read. This is also known as "stream parser". Events include Start Document, Start Element, End Element, etc.
- DOM - Document Object Model - means the XML is modeled a graph of nodes that may be traversed by code with methods like Get Children, Get Parent, etc.
The SAX approach is considered very fast and memory efficient, while the DOM is usually easier to handle by code, especially if the processing requires information from multiple nodes. On top of these two approaches there are many add-on tools that make the developer life a lot easier but usually take their performance toll. Most noticeably, the simplest approach, IMHO, is to take tools like JAXB or XML-Beans, which bind the XML into instances of custom classes which are modeled automatically according to the XML structure definition (DTD or Schema).
Choosing SAX
If you're looking for efficient XML processing, SAX is the way to go. It's the hard-core method: you don't get much and you pay accordingly. Writing an XML processor with SAX means implementing an interface called ContentHandler
. Here's an example:
class MyContentHandler implements org.xml.sax.ContentHandler {
public void startDocument() throws SAXException {
...
}
public void startElement(String uri, String localName, String name,
Attributes atts) throws SAXException {
...
}
public void endElement(String uri, String localName, String name)
throws SAXException {
...
}
...
}
If your XML has many types of elements to handle, your startElement
method is going to be a lengthy method with a very ugly string matching if/else
block. For example, parsing XHTML would look a bit like this:
public void startElement(String uri, String localName, String name,
Attributes atts) throws SAXException {
String lowerCaseName = localName.toLowerCase();
if (lowerCaseName.equals("html")) {
...
} else if (lowerCaseName.equals("head")) {
...
} else if (lowerCaseName.equals("title")) {
...
} ...
}
You wanted hard core and you got it.
Enums to the Rescue
One of my favorite features in Java 5 is enumerations (enums). Since I started using them, I keep finding new uses and new design patterns which are more elegant with enums. If you're not fully familiar with enums, stop reading this article and spend the time trying out the Enums - it will be worth it.
The solution I offer is simple: each element has a corresponding enum constant which holds the code for handling that particular elements. The enum constant name will have the same name as the element name. The correct constant is selected using the Enum static method valueOf. It's a very elegant code which looks like this:
private enum ElementType {
html {
void startElement(Attributes atts) throws SAXException {
...
}
},
head {
void startElement(Attributes atts) throws SAXException {
...
}
},
title {
void startElement(Attributes atts) throws SAXException {
...
}
};
abstract void startElement(Attributes atts) throws SAXException;
}
public void startElement(String uri, String localName, String name,
Attributes atts) throws SAXException {
try {
ElementType.valueOf(ElementType.class, localName.toLowerCase())
.startElement(atts);
} catch (IllegalArgumentException e) {
...
}
}
The above code is based on the built-in valueOf
method for choosing the right constant. The solution I presented is also limited by the fact that enum constants must have Java identifier names. Most noticeably, you cannot use a dash in the element name.
The Hash Table Alternative
If you look at the implementation of the valueOf
method in java.lang.Enum
, you'll see that it is working with a hash table behind the scenes, with enum constant names as keys. In fact, the same solution, less elegant, could be achieved by working with such a map, which holds instances, possibly anonymous classes, that implement an interface for handling the element (much like the enums above).
private interface ElementHandler {
void startElement(Attributes atts) throws SAXException;
}
private static final Map<String, ElementHandler> elements;
static {
elements = new HashMap<String, ElementHandler>();
elements.put("head", new ElementHandler(){
public void startElement(Attributes atts) throws SAXException {
...
}});
...
}
public void startElement(String uri, String localName, String name,
Attributes atts) throws SAXException {
ElementHandler elementHandler = elements.get(localName.toLowerCase());
if (elementHandler != null) {
elementHandler.startElement(atts);
} else {
...
}
}
The above is simpler than using if/else
, but it's not as elegant as using enums. As to performance, it depends on the map implementation and the number of element types in the XML. In case you have just a few element type, if/else
will be more efficient for sure. Nevertheless, I'm not sure that's worth the awkward code involved. The enum option seems to me the easiest to maintain and expand.
What do you think?
Opinions expressed by DZone contributors are their own.
Comments