Create XML Document in Java

With this short blog post I am going to share with you how to create XML document using Java.

Often we need to send HTTP Post request that contains JSON or XML payload. Earlier I have shared a blog post on different ways to create JSON Payload by converting Java objects into JSON. Below is an example of how to use DocumentBuilder from javax.xml.parsers to construct XML document from scratch.

In the example below we are going to create a very simple XML document of the below structure. Once you are able to create this simple XML document, you will be able to enhance it with new elements as needed.

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<Person>
       <FirstName>Sergey</FirstName>
       <LastName>Kargopolov</LastName>
</Person>

Create DocumentBuilderFactory

DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();

 Create new Document

DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
Document doc = docBuilder.newDocument();

 Create XML Document Root Element

// Create Person root element 
Element personRootElement = doc.createElement( "Person" );
doc.appendChild( personRootElement );

Create Child XML Element

// Create First Name Element
Element firstNameElement = doc.createElement( "FirstName" );
firstNameElement.appendChild( doc.createTextNode( "Sergey" ) );
personRootElement.appendChild( firstNameElement );

and we will create a second child element right away:

// Create Last Name Element
Element lastNameElement = doc.createElement( "LastName" );
lastNameElement.appendChild( doc.createTextNode( "Kargopolov" ) );
personRootElement.appendChild( lastNameElement );

Transform XML Document to String

// Transform Document to XML String
TransformerFactory tf = TransformerFactory.newInstance();
Transformer transformer = tf.newTransformer();
StringWriter writer = new StringWriter();

transformer.transform( new DOMSource( doc ), new StreamResult( writer ) );

and we can now get value of String, so that we can use it as we need. For example we can send it as a body of HTTP Request to our RESTful Web Services API endpoint.

// Get the String value of final xml document
personXMLStringValue = writer.getBuffer().toString();

and this is it! I will paste a complete example in a single class file below.

Create XML Document Complete Example

Below is a complete example in the form of single public static void main function. You should be able to run it as is.

package com.appsdeveloperblog.xml;

import java.io.StringWriter;
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 javax.xml.transform.stream.StreamResult;
import org.w3c.dom.Document;
import org.w3c.dom.Element;

/**
 *
 * @author skargopolov
 */
public class PersonXMLDocument {

    public static void main(String[] args) {
        String personXMLStringValue = null;

        DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
        try {
            DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
            Document doc = docBuilder.newDocument();

            // Create Person root element 
            Element personRootElement = doc.createElement("Person");
            doc.appendChild(personRootElement);

            // Create First Name Element
            Element firstNameElement = doc.createElement("FirstName");
            firstNameElement.appendChild(doc.createTextNode("Sergey"));
            personRootElement.appendChild(firstNameElement);

            // Create Last Name Element
            Element lastNameElement = doc.createElement("LastName");
            lastNameElement.appendChild(doc.createTextNode("Kargopolov"));
            personRootElement.appendChild(lastNameElement);

            // Transform Document to XML String
            TransformerFactory tf = TransformerFactory.newInstance();
            Transformer transformer = tf.newTransformer();
            StringWriter writer = new StringWriter();

            transformer.transform(new DOMSource(doc), new StreamResult(writer));

            // Get the String value of final xml document
            personXMLStringValue = writer.getBuffer().toString();

        } catch (ParserConfigurationException | TransformerException e) {
            e.printStackTrace();
        }

        System.out.println("personXMLStringValue = " + personXMLStringValue);

    }

}

I hope this short and simple example of how to create xml document in Java was helpful to you!

If you have questions please comment below. Hopefully myself or other web site visitors will be able to help you out.

Also, checkout the below list of books that will help you learn how to work with XML in Java.


Leave a Reply

Your email address will not be published. Required fields are marked *