jaxb

Here’s a simple use case which I imagine happens a lot:

You’re writing a Java application. It requires storing data in xml and retrieving this data from xml. It used to work like this:

The above process is tedious. An important reason for this is that neither SAX nor DOM are very javaish. DOM was designed to work well with limited languages such as javascript. Hence everything is a Node. That sort of sucks if you have a language that supports inheritance and interfaces. Instead of using java language features you have to write code to check what kind of node you are dealing with and use tedious calls to extract information. In short, the DOM api sucks big time from an OO perspective.

SAX is worse, it is a very low level API that requires you to write event handlers to get data out of it. The only nice thing about it is that works ‘on the fly’, so you can prevent buffering the entire thing in memory.

Neither are very nice to work with in the above scenario. In most cases all I want to do is something like this:


Document foo = Document.parse("foo.xml", FooInterface.class);
FooInterface fooBean = (FooInterface)foo.getBean();
Bar barBean = (Bar)fooBean.getBar();
barBean.setFooBar("foobar!");
Document.writeXml("foo.xml", fooBean);

In short I want to unserialize some xml, do stuff with it and then serialize it back and not spend to much time thinking about how that should be implemented. There are of course some problems with this:

Here’s how sun expects people to solve the above problem (using JAXB):

This solution has a number of problems:

In short, like so many xml based tools, JAXB is an overarchitected solution that doesn’t actually have much advantages over hand parsed and unparsed stuff for the simple use cases that are so common. I’ve written plenty of xml parser code based on the DOM api and I’ve decided to keep doing that. In fact, in the time I used to figure out the above I could have written it for what I am currently building.