Wednesday, February 11, 2009

DOM vs JAXB

The DOM API and JAXB (Java Architecture for XML Binding) look a bit similar to me, for the task of mapping Java objects to XML documents (the concept popularly known as, XML data binding).

JAXB essentially does [1],

1. Marshalling of Java objects to XML.

2. Unmarshalling of the XML data to Java objects.

The DOM API also does [2],

1. Transformation of DOM tree to XML (known as the XML serialization process).

2. Transforming of XML documents to a DOM object tree.

At a broad level, the approaches [1] and [2] look similar.

But according to me, following are the differences between the two approaches:

1. The JAXB transformation is driven by a Schema. The JAXB binding compiler generates Java type definitions for the Schema components. With JAXB, the object model (generated by the JAXB framework) maps closely to the concepts in the problem domain (for e.g, there will be a Java class PurchaseOrder corresponding to a Schema type PurchaseOrder).

Whereas with DOM, the Schema does not drive the XML and Java mapping. And, all the elements in an XML document map to the DOM class, org.w3c.dom.Element. The name of the element, the data inside it and other properties of the element are accessible using the methods provided by the DOM API.

2. There are perhaps some performance differences between JAXB and DOM. A study about this has been done by Santiago Pericas-Geertsen, as shared in these blog posts.

http://weblogs.java.net/blog/spericas/archive/2005/12/dom_vs_jaxb_per.html
http://weblogs.java.net/blog/spericas/archive/2005/12/dom_vs_jaxb_per_1.html

Under certain circumstances (to my opinion), the XML data bindings needs can be met by the DOM API (where a Schema does not drive the data binding process, and a raw mapping of XML and Java is required).

1 comment:

ModernPhilosopher said...

Good explanation, thank you!