Java Programming Tutorials

Java programming tutorials with many code examples!

Java read XML using DOM

Java read XML using DOM

Java DOM API is comfortable to work with not big XML documents. They can be easily loaded and modified in runtime. In this post we show how to do it.

Load XML into DOM using DocumentBuilder

DocumentBuilder has a couple of parse methods that allow to construct DOM (Document Object Model) from an XML file:

Document loadXML(String filename) throws Exception {
    DocumentBuilderFactory docFactory
        = DocumentBuilderFactory.newInstance();
    DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
    return docBuilder.parse(new File(filename));
}

Modify DOM

As in the post about writing XML in Java we can add/remove DOM structure:

void displayBooks(Node books) {
    NodeList childNodes = books.getChildNodes();
    for (int i = 0; i < childNodes.getLength(); ++i) {
        Node book = childNodes.item(i);
        System.out.printf("%s: %s%n",
            book.getNodeName(), book.getTextContent());
    }
}

Element createTitleNode(Document doc) {
    Element titleNode = doc.createElement("title");
    Text title = doc.createTextNode(
        "The passionate programmer");
    titleNode.appendChild(title);
    return titleNode;
}

Write modified DOM to XML file

Writing to DOM back into XML file can be done simply using Transformer from javax.xml.transform package:

void writeToFile(String filename, Document doc) throws Exception {
    TransformerFactory transFactory
        = TransformerFactory.newInstance();
    Transformer transformer = transFactory.newTransformer();

    DOMSource source = new DOMSource(doc);

    File xmlFile = new File(filename);
    StreamResult target = new StreamResult(xmlFile);

    transformer.transform(source, target);
}

Complete example

Initial XML file as generated by program in the post about writing XML:

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<books library="Kraków">
  <book>
    <title><!--Great book!-->Introduction to Algorithms</title>
  </book>
</books>

In the following program we load XML using Java DOM API, modify it by adding a new book element, and write it back:

package com.farenda.javax;

import org.w3c.dom.*;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import java.io.File;

public class ReadXMLUsingDOM {

    public static void main(String[] args) throws Exception {
        String filename = "/tmp/library.xml";

        Document library = loadXML(filename);

        // "books" is the root element:
        Node books = library.getFirstChild();
        displayBooks(books);

        Element newBook = createBook(library);
        books.appendChild(newBook);

        writeToFile(filename, library);
    }

    private static Document loadXML(String filename)
            throws Exception {
        DocumentBuilderFactory docFactory
            = DocumentBuilderFactory.newInstance();
        DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
        return docBuilder.parse(new File(filename));
    }

    private static void displayBooks(Node books) {
        NodeList childNodes = books.getChildNodes();
        for (int i = 0; i < childNodes.getLength(); ++i) {
            Node book = childNodes.item(i);
            System.out.printf("%s: %s%n",
                    book.getNodeName(),
                    book.getTextContent());
        }
    }

    private static Element createBook(Document doc) {
        Element book = doc.createElement("book");
        book.appendChild(createTitleNode(doc));
        return book;
    }

    private static Element createTitleNode(Document doc) {
        Element titleNode = doc.createElement("title");
        Text title = doc.createTextNode(
            "The passionate programmer");
        titleNode.appendChild(title);
        return titleNode;
    }

    private static void writeToFile(String filename, Document doc)
            throws Exception {
        TransformerFactory transFactory
            = TransformerFactory.newInstance();
        Transformer transformer = transFactory.newTransformer();
        DOMSource source = new DOMSource(doc);
        File xmlFile = new File(filename);
        StreamResult target = new StreamResult(xmlFile);
        transformer.transform(source, target);
    }

}

After running the above program one book has been added:

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<books library="Kraków">
  <book>
    <title><!--Great book!-->Introduction to Algorithms</title>
  </book>
  <book>
    <title>The passionate programmer</title>
  </book>
</books>
Share with the World!