Java DOM

Jakob Jenkov
Last update: 2014-05-21

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:

    <title>Fun Software</title>
    <author>Jakob Jenkov</author>

And the corresponding DOM structure:

Book Title Author ISBN

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 =
DocumentBuilder builder = null;
try {
    builder = builderFactory.newDocumentBuilder();
} catch (ParserConfigurationException e) {

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) {
} catch (IOException e) {

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).

Jakob Jenkov

Featured Videos

Java ForkJoinPool

P2P Networks Introduction


Java Persistence
Close TOC
All Tutorial Trails
All Trails
Table of contents (TOC) for this tutorial trail
Trail TOC
Table of contents (TOC) for this tutorial
Page TOC
Previous tutorial in this tutorial trail
Next tutorial in this tutorial trail