How to Create XML File in Java - (DOM Parser)

In this article, we will learn how to create an XML file in Java using DOM XML Parser. The DOM provides many handy classes to create an XML file easily. Firstly, you have to create a Document with DocumentBuilder class, define all the XML content – node, attribute with Element class. In last, use the Transformer class to output the entire XML content to stream output, typically a File.

Development Process Steps

  1. The users.xml Output File
  2. Java DOM Parser to create an XML file in Java

1. The users.xml Output File

At the end of the example, the following XML file named “users.xml” will be created.
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<Users>
    <User id="1">
        <firstName>Ramesh</firstName>
        <lastName>Fadatare</lastName>
        <age>28</age>
        <gender>Male</gender>
    </User>
    <User id="2">
        <firstName>John</firstName>
        <lastName>Cena</lastName>
        <age>45</age>
        <gender>Male</gender>
    </User>
    <User id="3">
        <firstName>Tom</firstName>
        <lastName>Cruise</lastName>
        <age>40</age>
        <gender>Male</gender>
    </User>
</Users>

2. Java DOM Parser to create an XML file in Java

Let's create a program to create an XML file in Java using DOM Parser.
package net.javaguides.javaxmlparser.dom;

import java.io.File;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
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 CreateXMLFileInJava {
    public static void main(String[] args) {
        DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder dBuilder;
        try {
            dBuilder = dbFactory.newDocumentBuilder();
            Document doc = dBuilder.newDocument();
            // add elements to Document
            Element rootElement = doc.createElement("Users");
            // append root element to document
            doc.appendChild(rootElement);

            // append first child element to root element
            rootElement.appendChild(createUserElement(doc, "1", "Ramesh", "Fadatare", "28", "Male"));

            // append second child
            rootElement.appendChild(createUserElement(doc, "2", "John", "Cena", "45", "Male"));

            // append third child
            rootElement.appendChild(createUserElement(doc, "3", "Tom", "Cruise", "40", "Male"));

            // for output to file, console
            TransformerFactory transformerFactory = TransformerFactory.newInstance();
            Transformer transformer = transformerFactory.newTransformer();
            // for pretty print
            transformer.setOutputProperty(OutputKeys.INDENT, "yes");
            DOMSource source = new DOMSource(doc);

            // write to console or file
            StreamResult console = new StreamResult(System.out);
            StreamResult file = new StreamResult(new File("create_users.xml"));

            // write data
            transformer.transform(source, console);
            transformer.transform(source, file);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private static Node createUserElement(Document doc, String id, String firstName, String lastName, String age,
        String gender) {
        Element user = doc.createElement("User");

        // set id attribute
        user.setAttribute("id", id);

        // create firstName element
        user.appendChild(createUserElements(doc, user, "firstName", firstName));

        // create lastName element
        user.appendChild(createUserElements(doc, user, "lastName", lastName));

        // create age element
        user.appendChild(createUserElements(doc, user, "age", age));

        // create gender element
        user.appendChild(createUserElements(doc, user, "gender", gender));

        return user;
    }

    // utility method to create text node
    private static Node createUserElements(Document doc, Element element, String name, String value) {
        Element node = doc.createElement(name);
        node.appendChild(doc.createTextNode(value));
        return node;
    }
}
An output of the above program:
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<Users>
<User id="1">
<firstName>Ramesh</firstName>
<lastName>Fadatare</lastName>
<age>28</age>
<gender>Male</gender>
</User>
<User id="2">
<firstName>John</firstName>
<lastName>Cena</lastName>
<age>45</age>
<gender>Male</gender>
</User>
<User id="3">
<firstName>Tom</firstName>
<lastName>Cruise</lastName>
<age>40</age>
<gender>Male</gender>
</User>
</Users>
Note that for debugging, you can change the StreamResult to output the XML content to your console.
Write to console or file:
StreamResult console = new StreamResult(System.out);
StreamResult file = new StreamResult(new File("create_users.xml"));
transformer.transform(source, console); // to console
transformer.transform(source, file); // to file

Check out related articles

>> How to Read XML File in Java using DOM Parser 
>> How to Modify Existing XML File in Java using DOM Parser

Comments