Tutorials About

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:

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

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

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

Close TOC
This website uses cookies to improve the user experience and gather statistics. Our advertisers use cookies too (3rd party cookies), to provide more relevant ads. Continued use of this website implies that you accept the use of cookies on this website. We do not share our cookies with our advertisers, and our advertisers do not share cookies with us.