Write XML File in Java using JDom XMLOutputter

JDom has an intuitive API and is therefore easy to use. In this example we explain how you can create a XML file using JDom. First we load the entire Document into memory. When we are satisfied, we can write the entire content to the console (like in this example), or create an XML file using a OutputStream.

JDom Maven Dependencies

In order to use JDom, you need to add it to the class path. When using maven, you can add the following dependency.


Create an XML Document using JDom

Every XML contains a root element. So we start of by creating the courses root Element. Next, we create the actual XML Document JDom representation, which resides in memory. Now the document is available, we can add elements and attributes. Finally, we print the output to the console using the XMLOutputter. We can optionally pass a Format as an argument in the constructor to format the output accordingly. In this example we used the Format.getPrettyFormat(), this will add the correct indentation and break lines in order to make the response more ‘human readable’.

package com.memorynotfound.xml.jdom;

import org.jdom2.Attribute;
import org.jdom2.Document;
import org.jdom2.Element;
import org.jdom2.output.Format;
import org.jdom2.output.XMLOutputter;
import java.io.IOException;

public class WriteXmlJDom {

    public static void main(String... args) throws IOException {

        Element root = new Element("courses");
        Document document = new Document(root);

        Element course = new Element("course");
        course.setAttribute(new Attribute("id", "1"));

        Element name = new Element("name");
        name.setText("Writing XML with JDom");

        Element price = new Element("price");


        XMLOutputter xmlOutputter = new XMLOutputter(Format.getPrettyFormat());
        xmlOutputter.output(document, System.out);

The previous code, generates the following output. Note that we used the System.out to print the XML file to the console. If you wanted to write the XML to a file, you should passed an OutputStream to the second argument of the XMLOutputter.output() method.

<?xml version="1.0" encoding="UTF-8"?>
  <course id="1">
    <name>Writing XML with JDom</name>



You may also like...