Datasheet

DOM
Let’s look at how you can accomplish the same task using the DOM API. The DOM API is a tree-based
API. The parser provides the application with a tree-structured object graph, which the application can
then traverse to extract the data from the parsed XML document. This process is more convenient than
using SAX, but you pay a price in performance because the parser creates a DOM tree whether you’re
going to use it or not. If you’re using XML to represent data in an application, the DOM tends to be inef-
ficient because you have to get the data you need out of the DOM tree; after that you have no use for the
DOM tree, even though the parser spent time and memory to construct it. We’re going to reuse the class
Book (in Book.java) for this example.
After importing all the necessary classes in lines 10-17, you declare a String constant whose value is the
namespace URI for the book schema (lines 19-21):
1: /*
2: *
3: * DOMMain.java
4: *
5: * Example from "Professional XML Development with Apache Tools"
6: *
7: */
8: package com.sauria.apachexml.ch1;
9:
10: import java.io.IOException;
11:
12: import org.apache.xerces.parsers.DOMParser;
13: import org.w3c.dom.Document;
14: import org.w3c.dom.Element;
15: import org.w3c.dom.Node;
16: import org.w3c.dom.NodeList;
17: import org.xml.sax.SAXException;
18:
19: public class DOMMain {
20: static final String bookNS =
21: "http://sauria.com/schemas/apache-xml-book/book";
22:
In line 24 you create a new DOMParser. Next you ask it to parse the document (line 27). At this point the
parser has produced the DOM tree, and you need to obtain it and traverse it to extract the data you need
to create a Book object (lines 27-29):
23: public static void main(String args[]) {
24: DOMParser p = new DOMParser();
25:
26: try {
27: p.parse(args[0]);
28: Document d = p.getDocument();
29: System.out.println(dom2Book(d).toString());
30:
31: } catch (SAXException se) {
32: System.out.println("Error during parsing " +
33: se.getMessage());
34: se.printStackTrace();
13
Xerces
01 543555 Ch01.qxd 11/5/03 9:40 AM Page 13