Java & XML
Java & XML Introduction
Java & XML Tool Overview
 
Java SAX
Java SAX DefaultHandler
Java SAX Schema Validation
Java SAX Example
Java SAX vs. StAX
 
Java StAX
Java StAX XMLInputFactory
Java StAX XMLOutputFactory
Java StAX XMLEventReader
Java StAX XMLEventWriter
Java StAX XMLStreamReader
Java StAX XMLStreamWriter
 
Java DOM Parser
Java DOM Document Object
Java DOM Schema Validation
 


Java DOM

Connect with me:  
  Jenkov.com - News

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

NextNext : Java DOM Document Object

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