Create an XML file in Java

It is possible to Create an XML file in Java with the DOM, however it is necessary to create the document with the DocumentBuilder class, and then create each element with the Element class. Finally you will use the Transformer class to generate a text file with the content of the XML.

ยป See more examples

package com.geekole; // Name of your java package

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;

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

 * @author

public class CreateXMLFile {

  public static void main(String argv[]) {
    try {
      DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
      DocumentBuilder docBuilder = docFactory.newDocumentBuilder();

      //Root element
      Document doc = docBuilder.newDocument();
      Element rootElement = doc.createElement("root");

      //First element
      Element element1 = doc.createElement("element1");

      //An attribute is added to the element node and its value
      Attr attr = doc.createAttribute("id");
      attr.setValue("attribute value");

      Element element2 = doc.createElement("element2");
      element2.setTextContent("Element 2 content");

      //Write the XML content to a file
      TransformerFactory transformerFactory = TransformerFactory.newInstance();
      Transformer transformer = transformerFactory.newTransformer();
      DOMSource source = new DOMSource(doc);
      StreamResult result = new StreamResult(new File("/path/test.xml"));

      transformer.transform(source, result);

    } catch (ParserConfigurationException pce) {
    } catch (TransformerException tfe) {

Although there are other ways to create an XML document, this is one of the most used. The result will be an XML file like the following:

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
    <element1 id="attribute value"/>
    <element2>Element 2 content</element2>
Create an XML file in Java