How do I create an XML document using JDOM?

In this small program you can see how to use JDOM to create a simple xml file. Below you’ll see how to create elements of the xml document, set some text for the element.

After that you can see how to use the XMLOutputter class to write the JDOM document into file and display it on the screen. To make the output better we can apply a Format to our xml document.

package org.kodejava.jdom;

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

import java.io.FileWriter;

public class JDomCreatingXml {
    public static void main(String[] args) {
        // <rows>
        //     <row>
        //         <firstname>Alice</firstname>
        //         <lastname>Starbuzz</lastname>
        //         <address>Sunset Road</address>
        //     </row>
        // </row>
        Document document = new Document();
        Element root = new Element("rows");

        // Creating a child for the root element. Here we can see how to
        // set the text of an xml element.
        Element child = new Element("row");
        child.addContent(new Element("firstname").setText("Alice"));
        child.addContent(new Element("lastname").setText("Starbuzz"));
        child.addContent(new Element("address").setText("Sunset Road"));

        // Add the child to the root element and add the root element as
        // the document content.
        root.addContent(child);
        document.setContent(root);

        try {
            FileWriter writer = new FileWriter("userinfo.xml");
            XMLOutputter outputter = new XMLOutputter();

            // Set the XLMOutputter to pretty formatter. This formatter
            // use the TextMode.TRIM, which mean it will remove the
            // trailing white-spaces of both side (left and right)
            outputter.setFormat(Format.getPrettyFormat());

            // Write the document to a file and also display it on the
            // screen through System.out.
            outputter.output(document, writer);
            outputter.output(document, System.out);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

This program will output the following XML document:

<?xml version="1.0" encoding="UTF-8"?>
<rows>
  <row>
    <firstname>Alice</firstname>
    <lastname>Starbuzz</lastname>
    <address>Sunset Road</address>
  </row>
</rows>

Maven Dependencies

<dependency>
    <groupId>org.jdom</groupId>
    <artifactId>jdom2</artifactId>
    <version>2.0.6.1</version>
</dependency>

Maven Central

Wayan

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.