Java XML Tutorial

How to write XML file in Java – (JDOM)

This tutorial shows how to use the JDOM to write data to an XML file.

Table of contents

P.S Tested with JDOM 2.0.6

1. Download JDOM 2.x

Maven for JDOM.

pom.xml

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

2. Write XML String to Console

The below example uses JDOM XMLOutputter to write an XML string to a system console output stream.

WriteXmlJDom1.java

package com.mkyong.xml.jdom;

import org.jdom2.Document;
import org.jdom2.JDOMException;
import org.jdom2.input.SAXBuilder;
import org.jdom2.output.Format;
import org.jdom2.output.XMLOutputter;

import java.io.IOException;
import java.io.StringReader;

public class WriteXmlJDom1 {

    public static void main(String[] args)
        throws JDOMException, IOException {

        writeSimpleXml();

    }

    private static void writeSimpleXml() throws JDOMException, IOException {

        String xml = "<root><child id=\"100\">mkyong</child></root>";
        SAXBuilder sb = new SAXBuilder();
        Document doc = sb.build(new StringReader(xml));

        // default in compact mode
        // XMLOutputter xmlOutputter = new XMLOutputter();

        // pretty print format
        XMLOutputter xmlOutputter = new XMLOutputter(Format.getPrettyFormat());

        // output to console
        xmlOutputter.output(doc, System.out);

    }

}

Output

Terminal

<?xml version="1.0" encoding="UTF-8"?>
<root>
  <child id="100">mkyong</child>
</root>

3. Write XML to a file

The JDOM XMLOutputter output support both Writer or OutputStream.

3.1 Below example Write XML to a file via FileOutputStream.


  XMLOutputter xmlOutputter = new XMLOutputter();

  // output to any OutputStream
  try(FileOutputStream fileOutputStream =
              new FileOutputStream("c:\\test\\file.xml")){
      xmlOutputter.output(new Document(), fileOutputStream);
  }

3.2 Below example write XML to a file via FileWriter.


  XMLOutputter xmlOutputter = new XMLOutputter();

  // output to any Writer
  try(FileWriter fileWriter =
              new FileWriter("c:\\test\\file.xml")){
      xmlOutputter.output(new Document(), fileWriter);
  }

3.3 Review the XMLOutputter.output overloaded methods:

JDOM XMLOutputter

4. Write XML attribute, comment, CDATA and etc

The below example uses JDOM to write XML elements, attributes, comments, CDATA to an output stream.

WriteXmlJDom3.java

package com.mkyong.xml.jdom;

import org.jdom2.CDATA;
import org.jdom2.Comment;
import org.jdom2.Document;
import org.jdom2.Element;
import org.jdom2.JDOMException;
import org.jdom2.output.Format;
import org.jdom2.output.XMLOutputter;

import java.io.IOException;
import java.io.OutputStream;

public class WriteXmlJDom3 {

  public static void main(String[] args) throws IOException {

      writeXml(System.out);

  }

  private static void writeXml(OutputStream output) throws IOException {

      Document doc = new Document();
      doc.setRootElement(new Element("company"));

      Element staff = new Element("staff");
      // add xml attribute
      staff.setAttribute("id", "1001");

      staff.addContent(new Element("name").setText("mkyong"));
      staff.addContent(new Element("role").setText("support"));
      staff.addContent(new Element("salary")
              .setAttribute("curreny", "USD").setText("5000"));

      // add xml comments
      staff.addContent(new Comment("for special characters like < &, need CDATA"));

      // add xml CDATA
      staff.addContent(new Element("bio")
              .setContent(new CDATA("HTML tag <code>testing</code>")));

      // append child to root
      doc.getRootElement().addContent(staff);

      Element staff2 = new Element("staff");
      staff2.setAttribute("id", "1002");
      staff2.addContent(new Element("name").setText("yflow"));
      staff2.addContent(new Element("role").setText("admin"));
      staff2.addContent(new Element("salary")
              .setAttribute("curreny", "EUD").setText("8000"));
      // add xml CDATA
      staff2.addContent(new Element("bio")
              .setContent(new CDATA("a & b")));

      // append child to root
      doc.getRootElement().addContent(staff2);

      XMLOutputter xmlOutputter = new XMLOutputter();

      // pretty print
      xmlOutputter.setFormat(Format.getPrettyFormat());
      xmlOutputter.output(doc, output);

  }

}

Output

Terminal

<?xml version="1.0" encoding="UTF-8"?>
<company>
  <staff id="1001">
    <name>mkyong</name>
    <role>support</role>
    <salary curreny="USD">5000</salary>
    <!--for special characters like < &, need CDATA-->
    <bio><![CDATA[HTML tag <code>testing</code>]]></bio>
  </staff>
  <staff id="1002">
    <name>yflow</name>
    <role>admin</role>
    <salary curreny="EUD">8000</salary>
    <bio><![CDATA[a & b]]></bio>
  </staff>
</company>

5. Change XML encoding

This code snippets change the XML encoding to ISO-8859-1.

.java

  XMLOutputter xmlOutputter = new XMLOutputter();
  // change xml encoding
  xmlOutputter.setFormat(Format.getPrettyFormat().setEncoding("ISO-8859-1"));
  xmlOutputter.output(doc, output);

Output

Terminal

<?xml version="1.0" encoding="ISO-8859-1"?>
<root></root>

Note
More JDOM2 examples – JDOM2 A Primer

6. Download Source Code

$ git clone https://github.com/mkyong/core-java

$ cd java-xml

$ cd src/main/java/com/mkyong/xml/jdom/

7. References

About Author

author image
Founder of Mkyong.com, love Java and open source stuff. Follow him on Twitter. If you like my tutorials, consider make a donation to these charities.

Comments

Subscribe
Notify of
1 Comment
Most Voted
Newest Oldest
Inline Feedbacks
View all comments
Antonio Diéguez
8 years ago

not enough, XMLOutputter uses a default charset(UTF8 if you dont specify), but if you use FileWriter that will use the default (or setted) file encoding of the jvm in the platform (which may be very different). So you have to use FileOutputStream not FileWriter (or use FileWriter and change the default file encoding but its ugly)