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 create XML using DOM

farenda 2016-09-03 0

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!
Categories Java Tags java, java-xml
Previous: Prime numbers – Sieve of Eratosthenes in Java
Next: Java read XML using DOM

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