How to Create XML File in Java – JDOM Parser

In the previous articles, we have learned How to read XML file in Java using JDOM parser and How to Update or Modify XML file in Java – JDOM Parser. In this article, we will learn how to create an XML file using JDOM parser in Java.
JDOM Document provides methods to easily create elements and attributes. XMLOutputter class can be used to write the Document to an OutputStream or Writer object.
For this example, we will create a list of the User element and then write it to an XML file.

Development Process Steps

  1. The output create_jdom_users.xml File
  2. Program to create XML file in Java using JDOM Parser.

1. The output create_jdom_users.xml File

At the end of this example, following XML file will be created.
<?xml version="1.0" encoding="UTF-8"?>
 <User id="1">
 <User id="2">
 <User id="3">
 <User id="3">

2. Program to create XML file in Java using JDOM Parser

Let's develop a program to create XML file in Java using JDOM Parser.
package net.javaguides.javaxmlparser.jdom;


import org.jdom2.Attribute;
import org.jdom2.Document;
import org.jdom2.Element;
import org.jdom2.output.Format;
import org.jdom2.output.XMLOutputter;

public class CreateXMLFile {

    public static void main(String[] args) {

        try {
            Document doc = new Document();
            doc.setRootElement(new Element("Users"));

            doc.getRootElement().addContent(createUserXMLElement("1", "Ramesh", "Fadatare", "28", "Male"));
            doc.getRootElement().addContent(createUserXMLElement("2", "Tom", "Cruise", "45", "Male"));
            doc.getRootElement().addContent(createUserXMLElement("3", "Tony", "Stark", "40", "Male"));
            doc.getRootElement().addContent(createUserXMLElement("3", "Amir", "Khan", "50", "Male"));

            // new XMLOutputter().output(doc, System.out);
            XMLOutputter xmlOutput = new XMLOutputter();
            // xmlOutput.output(doc, System.out);
            // display nice nice
            xmlOutput.output(doc, new FileWriter("create_jdom_users.xml"));

            System.out.println("File Saved!");
        } catch (IOException io) {

    private static Element createUserXMLElement(String id, String firstName, String lastName, String age,
        String gender) {
        Element user = new Element("User");
        user.setAttribute(new Attribute("id", id));
        user.addContent(new Element("firstName").setText(firstName));
        user.addContent(new Element("lastName").setText(lastName));
        user.addContent(new Element("age").setText(age));
        user.addContent(new Element("gender").setText(gender));
        return user;

Free Spring Boot Tutorial | Full In-depth Course | Learn Spring Boot in 10 Hours

Watch this course on YouTube at Spring Boot Tutorial | Fee 10 Hours Full Course