Java Reference
In-Depth Information
Sidebar 21.1 Java XML API
The collection of Java APIs for handling XML documents is called JAXP (Java API
for XML Processing). There are two alternative strategies to process an XML doc-
ument. The first consists in building an internal representation, called Document
Object Model (DOM), and performing all the processing upon it. This solution and
the related classes have been standardized by the W3C (www.w3c.org). The second
strategy consists in providing the implementation of an interface whose methods
are called when the parser encounters a given XML element; it is supported by the
SAX API (Simple API for XML). In this context we will focus on the DOM approach.
JAXP is part of the Java Enterprise Edition class libraries.
The main interfaces that make up the DOM API (org.w3c.dom) are represented
in Figure 21.9. They are structured according to the composite pattern. The base
interface is
Node
which can contain children
nodes
and can be parent of other
nodes, allowing a hierarchical objects structure.
children
*
parent
Node
1
Document
Attr
Element
attributes
*
1
Figure 21.9
Essential XML DOM classes
Interface
Document
represents a complete XML document, that is the result of
parsing an XML file. Interface
Element
represents any XML element (<TAG... />);
its attributes are represented by interface
Attr
. The relationships are implemented
by means of interface
NodeList
, which is not shown in Figure 21.9.
Given a
Node
within a document structure, it is easy to navigate to its children
and print them, either using the
NodeList
interface:
NodeList children
#
node.getChildNodes();
for(int i
#
0; i<children.getLength();
!!
i){
Node child
#
children.item(i);
System.out.println(child);
}