Java XML Tutorial

How to write XML file in Java – (DOM Parser)

This tutorial shows how to use the Java built-in DOM APIs to write data to an XML file.

Table of contents

P.S Tested with Java 11

1. Write XML to a file

Steps to create and write XML to a file.

  1. Create a Document doc.
  2. Create XML elements, attributes, etc., and append to the Document doc.
  3. Create a Transformer to write the Document doc to an OutputStream.
WriteXmlDom1.java

package com.mkyong.xml.dom;

import org.w3c.dom.Document;
import org.w3c.dom.Element;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.*;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import java.io.OutputStream;

public class WriteXmlDom1 {

    public static void main(String[] args)
            throws ParserConfigurationException, TransformerException {

        DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder docBuilder = docFactory.newDocumentBuilder();

        // root elements
        Document doc = docBuilder.newDocument();
        Element rootElement = doc.createElement("company");
        doc.appendChild(rootElement);

        doc.createElement("staff");
        rootElement.appendChild(doc.createElement("staff"));

        //...create XML elements, and others...

        // write dom document to a file
        try (FileOutputStream output =
                     new FileOutputStream("c:\\test\\staff-dom.xml")) {
            writeXml(doc, output);
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    // write doc to output stream
    private static void writeXml(Document doc,
                                 OutputStream output)
            throws TransformerException {

        TransformerFactory transformerFactory = TransformerFactory.newInstance();
        Transformer transformer = transformerFactory.newTransformer();
        DOMSource source = new DOMSource(doc);
        StreamResult result = new StreamResult(output);

        transformer.transform(source, result);

    }
}

Output

Terminal

<?xml version="1.0" encoding="UTF-8" standalone="no"?><company><staff>mkyong</staff></company>

2. Pretty Print XML

2.1 By default, the Transformer outputs the XML in a compact format.

Terminal

<?xml version="1.0" encoding="UTF-8" standalone="no"?><company><staff>mkyong</staff></company>

2.2 We can set the OutputKeys.INDENT in Transformer to enable the pretty print format.


  TransformerFactory transformerFactory = TransformerFactory.newInstance();
  Transformer transformer = transformerFactory.newTransformer();

  // pretty print XML
  transformer.setOutputProperty(OutputKeys.INDENT, "yes");

  DOMSource source = new DOMSource(doc);
  StreamResult result = new StreamResult(output);

  transformer.transform(source, result);

Output

Terminal

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<company>
  <staff>mkyong</staff>
</company>

3. Write XML elements, attributes, comments CDATA, etc

The below example uses a DOM parser to create and write XML to an OutputStream.

WriteXmlDom3.java

package com.mkyong.xml.dom;

import org.w3c.dom.CDATASection;
import org.w3c.dom.Comment;
import org.w3c.dom.Document;
import org.w3c.dom.Element;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.*;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;

public class WriteXmlDom3 {

  public static void main(String[] args)
          throws ParserConfigurationException, TransformerException {

      DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
      DocumentBuilder docBuilder = docFactory.newDocumentBuilder();

      // root elements
      Document doc = docBuilder.newDocument();
      Element rootElement = doc.createElement("company");
      doc.appendChild(rootElement);

      // staff 1001

      // add xml elements
      Element staff = doc.createElement("staff");
      // add staff to root
      rootElement.appendChild(staff);
      // add xml attribute
      staff.setAttribute("id", "1001");

      // alternative
      // Attr attr = doc.createAttribute("id");
      // attr.setValue("1001");
      // staff.setAttributeNode(attr);

      Element name = doc.createElement("name");
      // JDK 1.4
      //name.appendChild(doc.createTextNode("mkyong"));
      // JDK 1.5
      name.setTextContent("mkyong");
      staff.appendChild(name);

      Element role = doc.createElement("role");
      role.setTextContent("support");
      staff.appendChild(role);

      Element salary = doc.createElement("salary");
      salary.setAttribute("currency", "USD");
      salary.setTextContent("5000");
      staff.appendChild(salary);

      // add xml comment
      Comment comment = doc.createComment(
              "for special characters like < &, need CDATA");
      staff.appendChild(comment);

      Element bio = doc.createElement("bio");
      // add xml CDATA
      CDATASection cdataSection =
              doc.createCDATASection("HTML tag <code>testing</code>");
      bio.appendChild(cdataSection);
      staff.appendChild(bio);

      // staff 1002
      Element staff2 = doc.createElement("staff");
      // add staff to root
      rootElement.appendChild(staff2);
      staff2.setAttribute("id", "1002");

      Element name2 = doc.createElement("name");
      name2.setTextContent("yflow");
      staff2.appendChild(name2);

      Element role2 = doc.createElement("role");
      role2.setTextContent("admin");
      staff2.appendChild(role2);

      Element salary2 = doc.createElement("salary");
      salary2.setAttribute("currency", "EUD");
      salary2.setTextContent("8000");
      staff2.appendChild(salary2);

      Element bio2 = doc.createElement("bio");
      // add xml CDATA
      bio2.appendChild(doc.createCDATASection("a & b"));
      staff2.appendChild(bio2);

      // print XML to system console
      writeXml(doc, System.out);

  }

  // write doc to output stream
  private static void writeXml(Document doc,
                               OutputStream output)
          throws TransformerException {

      TransformerFactory transformerFactory = TransformerFactory.newInstance();
      Transformer transformer = transformerFactory.newTransformer();

      // pretty print
      transformer.setOutputProperty(OutputKeys.INDENT, "yes");

      DOMSource source = new DOMSource(doc);
      StreamResult result = new StreamResult(output);

      transformer.transform(source, result);

  }
}

Output

Terminal

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<company>
  <staff id="1001">
      <name>mkyong</name>
      <role>support</role>
      <salary currency="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 currency="EUD">8000</salary>
      <bio>
          <![CDATA[a & b]]>
      </bio>
  </staff>
</company>

4. DOM FAQs

Some DOM parser commonly asked questions.

4.1 How to disable the XML declaration?

We can configure the OutputKeys.OMIT_XML_DECLARATION to disblae the XML declaration.


  // hide the xml declaration
  // hide <?xml version="1.0" encoding="UTF-8" standalone="no"?>
  transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");

4.2 How to change the XML encoding?

We can configure the OutputKeys.ENCODING to change the XML encoding.


  // set xml encoding
  // <?xml version="1.0" encoding="ISO-8859-1" standalone="no"?>
  transformer.setOutputProperty(OutputKeys.ENCODING,"ISO-8859-1");

4.3 How to pretty-print the XML?

We can configure the OutputKeys.INDENT to enable the pretty print XML.


  // pretty print
  transformer.setOutputProperty(OutputKeys.INDENT, "yes");

4.4 How to hide the XML declaration `standalone=”no”`?

We can configure the document.setXmlStandalone(true) to hide the XML declaration standalone="no".


  TransformerFactory transformerFactory = TransformerFactory.newInstance();
  Transformer transformer = transformerFactory.newTransformer();

  // pretty print
  transformer.setOutputProperty(OutputKeys.INDENT, "yes");

  // hide the standalone="no"
  doc.setXmlStandalone(true);

  DOMSource source = new DOMSource(doc);
  StreamResult result = new StreamResult(output);

  transformer.transform(source, result);

4.5 How to change the XML declaration version?

We can configure the document.setXmlVersion("version") to change the XML declaration version.


  // set xml version
  // <?xml version="1.1" encoding="ISO-8859-1" standalone="no"?>
  doc.setXmlVersion("1.1");

5. Download Source Code

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

$ cd java-xml

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

6. 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
8 Comments
Most Voted
Newest Oldest
Inline Feedbacks
View all comments
Carlos Anies
2 years ago

Hi Mykong

INSTEAD OF PRINTING THE TRANSFORMED XML BY CONSOLE, I WOULD NEED TO SAVE IT IN A STRING TO PUT IT IN A SOAP REQUEST, HOW CAN I DO IT?

Example request:

<as_xml_peticion><![CDATA[
      <GESADWS_PETICION>
      <CABECERA>
      <NOTIFICADOR>API_EDOMUS</NOTIFICADOR>
      <NOTIFICACION>ActualizaContrato</NOTIFICACION>
      <VERSION>1</VERSION>
      <CINSTALL>EDOMUS27255</CINSTALL>
      </CABECERA>
     
      <PETICION>
      </PETICION>
     
      </GESADWS_PETICION>]]></as_xml_peticion>

salony
9 months ago

how can i have multiple root element?
something like :
<CurrentStatus>
<status>FinalSentOK</status>
<StatusGranularity>
<Phase>Final</Phase>
<Action>Sent</Action>
</CurrentStatus>
<Second><one></one></Second>

Deepika
1 year ago

thanks a lot for the code to write to XML. Helped me a lot.
I found that FileOutputStream needs to be closed after writing to XML i.e., output.close(); Without closing this, I encountered issues when processing this file further.

Steve
1 year ago

Thanks! This totally got me out of the water.

Indra
1 year ago

Thanks for this code. I have a for loop of 100 times, where 5 xml elements are being formed for each. So, the expected output is to have a XML file with 100 blocks (5 elements each). Currently, the last for loop’s content is being stored and showing just 1 block in XML. Can you help how can I put the blocks into same XML?

Omar Sweidan
1 year ago

Hi, @mkyong!

The pretty-printing is not working for me with the example code you gave.
Can you please update the code?

Arun Raj
9 years ago

thanks it helped me.

Mario Silvano
10 years ago

Thanks man!, you did a great job!