Java Reference
In-Depth Information
Example 19−2: ListServlets2.java (continued)
exception.getMessage());
throw(exception);
}
}
Compiling and Running the Example
The ListServlets2 example uses the Xerces-J parser from the Apache XML Pro-
ject. You can download this open-source parser by following the download links
from http://xml.apache.or g/ . Once you have downloaded Xerces-J, unpack the dis-
tribution in a convenient location on your system. In that distribution, you should
find a xerces.jar file. This file must be in your classpath to compile and run the
ListServlets2.java example. Note that the xerces.jar file and the parsers.jar file from
the JAXP distribution both contain versions of the SAX and DOM classes; you
should avoid having both files in your classpath at the same time.
Parsing and Manipulating with
JAXP and DOM
The first two examples in this chapter used the SAX API for parsing XML docu-
ments. We now turn to another commonly used parsing API, the DOM, or Docu-
ment Object Model. The DOM API is a standard defined by the World Wide Web
Consortium (W3C); its Java implementation consists of the org.w3c.dom package
and its subpackages. The current version of the DOM standard is Level 1. As of
this writing, the DOM Level 2 API is making its way through the standardization
process at the W3C.
The Document Object Model defines the API of a parse tree for XML documents.
The org.xml.dom.Node interface specifies the basic features of a node in this parse
tree. Subinterfaces, such as Document , Element , Entity , and Comment , define the
features of specific types of nodes. A program that uses the DOM parsing model is
quite different from one that uses SAX. With the DOM, you have the parser read
your XML document and transform it into a tree of Node objects. Once parsing is
complete, you can traverse the tree to find the information you need. The DOM
parsing model is useful if you need to make multiple passes through the tree, if
you want to modify the structure of the tree, or if you need random access to an
XML document, instead of the sequential access provided by the SAX model.
Example 19-3 is a listing of the program WebAppConfig.java . Like the first two
examples in this chapter, WebAppConfig reads a web.xml web application deploy-
ment descriptor. This example uses a DOM parser to build a parse tree, then per-
forms some operations on the tree to demonstrate how you can work with a tree
of DOM nodes.
The WebAppConfig() constructor uses the JAXP API to obtain a DOM parser and
then uses that parser to build a parse tree that represents the XML file. The root
node of this tree is of type Document . This Document object is stored in an instance
field of the WebAppConfig object, so it is available for traversal and modification by
Search WWH ::




Custom Search