Jenkov.com
Tutorials Books About
Java Xml

1 Java & XML Tutorial
2 Java & XML Tool Overview
3 Java SAX Parser
4 Java SAX DefaultHandler
5 Java SAX Schema Validation
6 Java SAX Parsing Example
7 Java SAX vs. StAX
8 Java StAX
9 Java StAX: XMLInputFactory
10 Java StAX: XMLOutputFactory
11 Java StAX: XMLEventReader - The Iterator API
12 Java StAX: XMLEventWriter - The Iterator Writer API
13 Java StAX: XMLStreamReader - The Cursor API
14 Java StAX: XMLStreamWriter - The Cursor Writer API
15 Java DOM
16 Java DOM: The Document Object
17 Java DOM Schema Validation




Java DOM


The Java DOM API for XML parsing is intended for working with XML as an object graph in memory - a "Document Object Model (DOM)". The parser traverses the XML file and creates the corresponding DOM objects. These DOM objects are linked together in a tree structure. Once the parser is done, you get this DOM object structure back from it. Then you can traverse the DOM structure back and forth as you see fit.

NOTE: This text uses SVG (Scalable Vector Graphics) diagrams. If you are using Internet Explorer you will need the Adobe SVG Plugin do display these diagrams. Firefox 3.0.5+ users and Google Chrome users should have no problems.

Here is an example XML file, and a DOM tree that illustrates the principle of turning XML into DOM:

<book>
    <title>Fun Software</title>
    <author>Jakob Jenkov</author>
    <ISBN>0123456789</ISBN>
</book>

And the corresponding DOM structure:

This Java DOM structure can now be traversed just like you would with any other tree object graph. Remember them graph traversal algorithms from university?

Creating A Java DOM XML Parser

Creating a Java DOM XML parser is done using the javax.xml.parsers.DocumentBuilderFactory class. Here is an example:

DocumentBuilderFactory builderFactory =
        DocumentBuilderFactory.newInstance();
DocumentBuilder builder = null;
try {
    builder = builderFactory.newDocumentBuilder();
} catch (ParserConfigurationException e) {
    e.printStackTrace();  
}

It is the DocumentBuilder instance that is the DOM parser. Using this DOM parser you can parse XML files into DOM objects, as we will see in the next section.

Parsing XML with a Java DOM Parser

Parsing an XML file into a DOM tree using the DocumentBuilder is done like this:

try {
    Document document = builder.parse(
        new FileInputStream("data\\text.xml"));
} catch (SAXException e) {
    e.printStackTrace();
} catch (IOException e) {
    e.printStackTrace();
}

You are now ready to traverse the Document instance you have received from the DocumentBuilder. How to traverse the Document object is covered in the next text (see link below).



Connect with me: Newsletter - Get all my free tips!