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.

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<Person>
<FirstName>Sergey</FirstName>
<LastName>Kargopolov</LastName>
</Person>
<?xml version="1.0" encoding="UTF-8" standalone="no"?> <Person> <FirstName>Sergey</FirstName> <LastName>Kargopolov</LastName> </Person>
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<Person>
       <FirstName>Sergey</FirstName>
       <LastName>Kargopolov</LastName>
</Person>

Create DocumentBuilderFactory

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();

 Create new Document

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
Document doc = docBuilder.newDocument();
DocumentBuilder docBuilder = docFactory.newDocumentBuilder(); Document doc = docBuilder.newDocument();
DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
Document doc = docBuilder.newDocument();

 Create XML Document Root Element

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
// Create Person root element
Element personRootElement = doc.createElement( "Person" );
doc.appendChild( personRootElement );
// Create Person root element Element personRootElement = doc.createElement( "Person" ); doc.appendChild( personRootElement );
// Create Person root element 
Element personRootElement = doc.createElement( "Person" );
doc.appendChild( personRootElement );

Create Child XML Element

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
// Create First Name Element
Element firstNameElement = doc.createElement( "FirstName" );
firstNameElement.appendChild( doc.createTextNode( "Sergey" ) );
personRootElement.appendChild( firstNameElement );
// Create First Name Element Element firstNameElement = doc.createElement( "FirstName" ); firstNameElement.appendChild( doc.createTextNode( "Sergey" ) ); personRootElement.appendChild( firstNameElement );
// 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:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
// Create Last Name Element
Element lastNameElement = doc.createElement( "LastName" );
lastNameElement.appendChild( doc.createTextNode( "Kargopolov" ) );
personRootElement.appendChild( lastNameElement );
// Create Last Name Element Element lastNameElement = doc.createElement( "LastName" ); lastNameElement.appendChild( doc.createTextNode( "Kargopolov" ) ); personRootElement.appendChild( lastNameElement );
// Create Last Name Element
Element lastNameElement = doc.createElement( "LastName" );
lastNameElement.appendChild( doc.createTextNode( "Kargopolov" ) );
personRootElement.appendChild( lastNameElement );

Transform XML Document to String

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
// 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 ) );
// 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 ) );
// 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.

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
// Get the String value of final xml document
personXMLStringValue = writer.getBuffer().toString();
// Get the String value of final xml document personXMLStringValue = writer.getBuffer().toString();
// 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.

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
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);
}
}
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); } }
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 *