Java Reference
In-Depth Information
Table 17-1: org.w3c.dom Interface Node
org.w3c.dom Node_Type
Application
Example
>
DOCUMENT_NODE
Document
The enclosing Document
ELEMENT_NODE
Element
<NAME>...</NAME>
Hello world
TEXT_NODE
Body Text within element
The next section shows how to use some of the widely available DOM parsing tools to process XML
documents.
Using a Java XML API — Xerces and JDOM
A number of tools are available for working with XML in Java. Among the most widely used are the
Xerces package, available for download from apache.org. , and JDOM, available from jdom.org .
Xerces includes fully-validating parsers, implementing the W3C XML and DOM (Level 1 and 2)
standards, as well as the de facto SAX (version 2) standard. Xerces is a large, comprehensive
implementation of the full standard.
JDOM is a totally Java-oriented approach to working with XML. It seeks to provide a robust, light-weight
means of reading and writing XML data. It is certainly rather more intuitive to work with than the Xerces
API, but the differences are minor.
Having worked extensively with both, as well as with my own light-weight, custom XML API, I have
selected Xerces for the examples in the topic for several reasons:
 
Xerces is intended as a complete implementation of the DOM.
 
The sample code is built around Xbeans, from Xbeans.org . The origianl Xbean code uses
Xerces.
 
The Xerces jar contains everything you need to implement all the examples.
Having said all that, I should point out that translating the examples from one API to the other is
relatively simple, since the sample code uses only a small part of the API. The following code snippet
shows the creation of an XML document using the Xerces API. This code is taken from the SystemTime
bean example that you'll find later in this chapter under " Using XBeans as Pluggable XML Processing
Blocks ."
Document doc = new DocumentImpl();
Element root = (Element) doc.createElement("SYSTEMDATE");
doc.appendChild (root);
Element year = (Element) doc.createElement("YEAR");
root.appendChild(year);
year.appendChild(doc.createTextNode(""+calendar.get(Calendar.YEAR)));
The following JDOM equivalent is similar, but quite a bit simpler than the Xerces example, since it is
specifically designed to be a Java-oriented way of working with XML:
Element root = new Element("SYSTEMDATE");
Document doc = new Document(root);
Element year = new Element("YEAR");
root.addContent(year);
year.setText(""+calendar.get(Calendar.YEAR));
Search WWH ::




Custom Search