JDOM, The Java DOM (3/4) - exploring XML
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:
- You construct a parser-specific implementation of the XMLReader interface
- Your code registers an event handler with the parser
- An InputSource feeds the document into the parser
- 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:
- Library specific code creates a parser
- The parser parses the document and returns a
org.w3c.dom.Document
. - All current implementations store the document in memory.
- DOM methods and interfaces are used to extract data from this object
The JDOM Process
The JDOM process is far simpler:- You construct an instance of either
org.jdom.input.SAXBuilder
ororg.jdom.input.DOMBuilder
- You invoke the builder's
build()
method to build a Document object from a Reader, InputStream, URL, File or String containing a SYSTEM ID. - 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 { builder.build("my.xml"); 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
ADOMBuilder
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 { parser.parse("my.xml"); 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: https://www.webreference.com/xml/column25/3.html
Created: Dec 03, 2000
Revised: Dec 03, 2000