| home / experts / xml / column25 |
|
|
The process for parsing an XML document using SAX is fairly straightforward:
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 looks a bit different in that a data structure is created, rather than a stream of events:
org.w3c.dom.Document.
org.jdom.input.SAXBuilder or
org.jdom.input.DOMBuilder
build() method to build a
Document object from a Reader, InputStream, URL, File or
String containing a SYSTEM ID.
Let's look at some code snippets that use JDOM for processing XML documents:
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());
}
You can tell the builder you want it to validate by passing true to its constructor:
SAXBuilder builder = new SAXBuilder(true);
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 {
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: http://www.webreference.com/xml/column25/3.html
Created: Dec 03, 2000
Revised: Dec 03, 2000