JDOM, The Java DOM (3/4) - exploring XML | WebReference


JDOM, The Java DOM

Comparing the SAX, DOM and JDOM way

The SAX Process

The process for parsing an XML document using SAX is fairly straightforward:

  1. You construct a parser-specific implementation of the XMLReader interface
  2. Your code registers an event handler with the parser
  3. An InputSource feeds the document into the parser
  4. As the document is read, the parser calls back the methods in the registered event handler, mirroring the structure of the underlying XML document

This event based API has some shortcomings in that you might not have all the information you need at the time of a given callback or that , inversely, you have to store information locally in order to act on it later.

The DOM Process

The DOM process looks a bit different in that a data structure is created, rather than a stream of events:

  1. Library specific code creates a parser
  2. The parser parses the document and returns a org.w3c.dom.Document.
  3. All current implementations store the document in memory.

The JDOM Process

The JDOM process is far simpler:
  1. You construct an instance of either org.jdom.input.SAXBuilder or org.jdom.input.DOMBuilder
  2. You invoke the builder's build() method to build a Document object from a Reader, InputStream, URL, File or String containing a SYSTEM ID.
  3. A JDOMException is thrown when the document cannot be built

Work with the resulting Document object

Let's look at some code snippets that use JDOM for processing XML documents:

Well-formedness checking

import org.jdom.JDOMException;
import org.jdom.input.SAXBuilder;
SAXBuilder builder = new SAXBuilder();
  try {
    System.out.println(" is well formed.");
  catch (JDOMException e) { // indicates a well-formedness or other error
    System.out.println(" is not well formed: + e.getMessage());

Validity checking

You can tell the builder you want it to validate by passing true to its constructor:

  SAXBuilder builder = new SAXBuilder(true);

Building with DOM instead of SAX

A DOMBuilder works pretty much the same way as a SAXBuilder, just that an intermediate step is necessary to turn a org.w3c.dom.Document into a org.jdom.Document: DOMBuilder Example
import org.jdom.*;
import org.jdom.input.DOMBuilder;
import org.apache.xerces.parsers.*;
  DOMBuilder builder = new DOMBuilder(true);
  DOMParser parser = new DOMParser();  // Parser specific class
  try {
    org.w3c.dom.Document domDoc  = parser.getDocument();
    org.jdom.Document    jdomDoc = builder.build(domDoc);
    System.out.println(" is valid.");
  catch (Exception e) { // indicates a well-formedness or validity error
    System.out.println(" is not valid:" + e.getMessage());

On to a JDOM summary...


Produced by Michael Claßen
All Rights Reserved. Legal Notices.

URL: http://www.webreference.com/xml/column25/3.html
Created: Dec 03, 2000
Revised: Dec 03, 2000