JAXP Write XML using DOM

0

In this article, we will programmatically create a DOM object tree using DOM provided APIs.

The first thing that we require is an instance of DocumentBuilderFactory.

We call the static method newInstance() to Obtain a new instance of DocumentBuilderFactory.

DocumentBuilderFactory documentBuilderFactory 
= DocumentBuilderFactory.newInstance();

We are going to add structure to the document using APIs so for now all we need is the root of the document.
In order to obtain Document object, we need to obtain instance of DocumentBuilder. We need DocumentBuilder so that one can obtain DOM Document instances from an XML document.

DocumentBuilder documentBuilder = documentBuilderFactory
                .newDocumentBuilder();

In our example, we will not parse any XML instead we will write one.
Since we don’t have any existing XML, we need to first create an empty document.
We obtain a new instance of a DOM using newDocument().

Document document = documentBuilder.newDocument();
Document document = documentBuilder.newDocument();

Once we have the DOM object we will build the tree using APIs provided by Document object.

We will convert an array of employee beans into Document Object.

Employee:

package com.javarticles.sax;

public class Employee {
    private String name;
    private Integer age;
    private Integer id;

    Employee(Integer id, String name, Integer age) {
        this.id = id;
        this.name = name;
        this.age = age;
    }

    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public Integer getAge() {
        return age;
    }
    public void setAge(Integer age) {
        this.age = age;
    }
    public Integer getId() {
        return id;
    }
    public void setId(Integer id) {
        this.id = id;
    }
    public String toString() {
        return "Employee(id:"+ id + ", name:" + name + ", age:" + age + ")";
    }
}

The XML structure we want to build is:

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<employees><![CDATA[Document contains
[3] employees]]><employee id="1">
	<name>Joe</name>
	<age>34</age><!--Emp Joe, id is 1 -->
</employee>
	<employee id="2">
		<name>Sam</name>
		<age>24</age><!--Emp Sam, id is 2 -->
	</employee>
	<employee id="3">
		<name>John</name>
		<age>44</age><!--Emp John, id is 3 -->
	</employee>
</employees>

We need to do the following:

  1. Create a parent element employees.

    Element employeesElement = document.createElement("employees");
    
  2. Add employees element to document.
    document.appendChild(employeesElement);
    
  3. Add CDATA to it.
    Node cdata = document.createCDATASection("Document contains\n["
                    + employees.length + "] employees");
    employeesElement.appendChild(cdata);
    
  4. Add one or more child element employee to it.
    for (Employee employee : employees) {
        Element employeeElement = document.createElement("employee");
        employeesElement.appendChild(employeeElement);
        ...
    }
    
  5. Add id attribute to employee element.
    employeeElement.setAttribute(
    "id", String.valueOf(employee.getId()));
    
  6. Next add child elements name and age to employee element.
    Element nameElement = document.createElement("name");
    Element ageElement = document.createElement("age");
    employeeElement.appendChild(nameElement);
    employeeElement.appendChild(ageElement);
    
  7. Set name and age content to the above created elements.
    nameElement.appendChild(
    document.createTextNode(employee.getName()));
    ageElement.appendChild(
    document.createTextNode(String.valueOf(employee.getAge())));
    
  8. Add a comment for each employee element.
    Node comment = document.createComment("Emp " + employee.getName()
                        + ", id is " + employee.getId());
    

Once the DOM is built, we transform the DOM tree into an XML file.

TransformerFactory transformerFactory = TransformerFactory
                .newInstance();
Transformer transformer = transformerFactory.newTransformer();
DOMSource source = new DOMSource(document);
FileOutputStream fos = new FileOutputStream("employee.xml");
BufferedOutputStream bos = new BufferedOutputStream(fos);
StreamResult result = new StreamResult(bos);

transformer.transform(source, result);

DOMWriterExample:

package com.javarticles.sax;

import java.io.BufferedOutputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

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

public class DOMWriterExample {
    public static void main(String[] args) throws ParserConfigurationException,
            TransformerException, FileNotFoundException {
        DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory
                .newInstance();
        DocumentBuilder documentBuilder = documentBuilderFactory
                .newDocumentBuilder();
        Document document = documentBuilder.newDocument();
        Employee[] employees = new Employee[] { new Employee(1, "Joe", 34),
                new Employee(2, "Sam", 24), new Employee(3, "John", 44) };

        Element employeesElement = document.createElement("employees");
        document.appendChild(employeesElement);
        Node cdata = document.createCDATASection("Document contains\n["
                + employees.length + "] employees");
        employeesElement.appendChild(cdata);

        for (Employee employee : employees) {
            Element employeeElement = document.createElement("employee");
            Element nameElement = document.createElement("name");
            Element ageElement = document.createElement("age");

            Node comment = document.createComment("Emp " + employee.getName()
                    + ", id is " + employee.getId());

            employeesElement.appendChild(employeeElement);
            employeeElement.appendChild(nameElement);
            employeeElement.appendChild(ageElement);
            employeeElement.appendChild(comment);

            employeeElement
                    .setAttribute("id", String.valueOf(employee.getId()));

            nameElement
                    .appendChild(document.createTextNode(employee.getName()));
            ageElement.appendChild(document.createTextNode(String
                    .valueOf(employee.getAge())));
        }

        TransformerFactory transformerFactory = TransformerFactory
                .newInstance();
        Transformer transformer = transformerFactory.newTransformer();
        DOMSource source = new DOMSource(document);
        FileOutputStream fos = new FileOutputStream("employee.xml");
        BufferedOutputStream bos = new BufferedOutputStream(fos);
        StreamResult result = new StreamResult(bos);

        transformer.transform(source, result);
    }
}

Download source code

This was an example about writing XML using DOM.

You can download the source code here: domWriterExample.zip

About Author

Ram’s expertise lies in test driven development and re-factoring. He is passionate about open source technologies and loves blogging on various java and open-source technologies like spring.
You can reach him at [email protected]

Comments are closed.