Java Programming Tutorials

Java programming tutorials with many code examples!

Java create XML using DOM

Java create XML using DOM

Java allows to work with XML in many different ways. In this post we show how to use Java DOM API to create a document and write it as XML file.

DocumentBuilderFactory and DocumentBuilder

When working with DOM (Document Object Model) in Java one needs to create a DocumentBuilderFactory that allows to access underlying parser. Having DocumentBuilder we can create a new DOM Documents:

Document createDocument() throws ParserConfigurationException {
    DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
    DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
    return docBuilder.newDocument();
}

Document as factory of XML elements

Document is the class that does most of the work when creating XML. It provides API to create new nodes (elements, text nodes, etc.), setting attributes, different other things. Here we create an XML element and a text node, which will be its text content:

Document library = createDocument();
Element books = library.createElement("books");
books.setAttribute("library", "Kraków");
// adding the new element as child of the XML doc:
library.appendChild(books);
Element titleNode = library.createElement("title");
titleNode.appendChild(library.createComment("Great book!"));

Text title = library.createTextNode("Introduction to Algorithms");
titleNode.appendChild(title);

Write DOM as XML to file

Java has an API that allows to convert different objects into XML. The whole thing is located in javax.xml.transform package and is pretty easy to use:

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

  DOMSource source = new DOMSource(doc);

  File xmlFile = new File("/tmp/library.xml");
  StreamResult target = new StreamResult(xmlFile);

  transformer.transform(source, target);
}

Complete example

In this program we use Java API to create a DOM document and write it as an XML file:

package com.farenda.javax;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Text;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
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 WriteXMLUsingDOM {

    public static void main(String[] args) throws Exception {
        Document library = createDocument();
        Element books = addRootElement(library);
        books.appendChild(createBook(library));

        writeToFile(library);
    }

    private static Document createDocument()
            throws ParserConfigurationException {
        DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
        return docBuilder.newDocument();
    }

    private static Element addRootElement(Document library) {
        Element books = library.createElement("books");
        books.setAttribute("library", "Kraków");
        library.appendChild(books);
        return books;
    }

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

    private static Element createTitleNode(Document library) {
        Element titleNode = library.createElement("title");
        titleNode.appendChild(library.createComment("Great book!"));
        Text title = library.createTextNode("Introduction to Algorithms");
        titleNode.appendChild(title);
        return titleNode;
    }

    private static void writeToFile(Document library) throws Exception {
        TransformerFactory transFactory = TransformerFactory.newInstance();
        Transformer transformer = transFactory.newTransformer();
        DOMSource source = new DOMSource(library);
        File xmlFile = new File("/tmp/library.xml");
        StreamResult target = new StreamResult(xmlFile);
        transformer.transform(source, target);
    }
}

The content of the generated library.xml (after reformatting) is the following:

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

Works like a charm! :-)

Share with the World!