Skip to content

Yet another programming solutions log

Sample bits from programming for the future generations.

Technologies Technologies
  • Algorithms and Data Structures
  • Java Tutorials
  • JUnit Tutorial
  • MongoDB Tutorial
  • Quartz Scheduler Tutorial
  • Spock Framework Tutorial
  • Spring Framework
  • Bash Tutorial
  • Clojure Tutorial
  • Design Patterns
  • Developer’s Tools
  • Productivity
  • About
Expand Search Form

Java read XML using DOM

farenda 2016-09-04 0

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!
Categories Java Tags java, java-xml
Previous: Java create XML using DOM
Next: Top 10 sites to practice programming

Recent Posts

  • Java 8 Date Time concepts
  • Maven dependency to local JAR
  • Caesar cipher in Java
  • Java casting trick
  • Java 8 flatMap practical example
  • Linked List – remove element
  • Linked List – insert element at position
  • Linked List add element at the end
  • Create Java Streams
  • Floyd Cycle detection in Java

Pages

  • About Farenda
  • Algorithms and Data Structures
  • Bash Tutorial
  • Bean Validation Tutorial
  • Clojure Tutorial
  • Design Patterns
  • Java 8 Streams and Lambda Expressions Tutorial
  • Java Basics Tutorial
  • Java Collections Tutorial
  • Java Concurrency Tutorial
  • Java IO Tutorial
  • Java Tutorials
  • Java Util Tutorial
  • Java XML Tutorial
  • JUnit Tutorial
  • MongoDB Tutorial
  • Quartz Scheduler Tutorial
  • Software Developer’s Tools
  • Spock Framework Tutorial
  • Spring Framework

Tags

algorithms bash bean-validation books clojure design-patterns embedmongo exercises git gof gradle groovy hateoas hsqldb i18n java java-basics java-collections java-concurrency java-io java-lang java-time java-util java-xml java8 java8-files junit linux lists log4j logging maven mongodb performance quartz refactoring regex rest slf4j solid spring spring-boot spring-core sql unit-tests

Yet another programming solutions log © 2021

sponsored
We use cookies to ensure that we give you the best experience on our website. If you continue to use this site we will assume that you are happy with it.Ok