DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports Events Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones AWS Cloud
by AWS Developer Relations
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones
AWS Cloud
by AWS Developer Relations
The Latest "Software Integration: The Intersection of APIs, Microservices, and Cloud-Based Systems" Trend Report
Get the report
  1. DZone
  2. Coding
  3. Languages
  4. Efficient XML Processing Using SAX and Java Enums

Efficient XML Processing Using SAX and Java Enums

Zviki Cohen user avatar by
Zviki Cohen
·
Aug. 06, 08 · Interview
Like (0)
Save
Tweet
Share
18.63K Views

Join the DZone community and get the full member experience.

Join For Free

I 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?

From http://zvikico.typepad.com/problog/

XML Java (programming language) Processing Element

Opinions expressed by DZone contributors are their own.

Popular on DZone

  • The Power of Docker Images: A Comprehensive Guide to Building From Scratch
  • File Uploads for the Web (2): Upload Files With JavaScript
  • Test Execution Tutorial: A Comprehensive Guide With Examples and Best Practices
  • Application Architecture Design Principles

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com
  • +1 (919) 678-0300

Let's be friends: