Java Tutorials
Building Hadoop MapReduce Jobs In Java
Building XML With Java And DOM
Creating Java Servlets With NetBeans
Basic File Manipulation With Java
Introduction To Java

Building XML With Java And DOM


XML is a flexible data formatting structure that can be used to transfer data between applications amongst other things. XML is commonly used by many web technologies to communicate, for example RSS feeds are an example of an XML document. This tutorial will cover how to build and write XML data structures in Java.

Basic XML Format

Documents start with a special tag that specifies the version of XML document and the document encoding format, ex: . All tags start with a < and end with a >, but only the special XML tag needs the ?. Documents are made up of one or more nodes or nested structures of nodes. Each node is represented by a tag in the document.

<?xml version="1.0" encoding="UTF-8"?>
            <name>John Doe</name>
            <name>Bob Smith</name>

Simple Output

Using the output writer and building by hand. This is the simplest way to write simple XML structures. Simply store the XML structure in a string or send directly to the output writer. First building structures by hand will be covered then the tutorial will explain using DOM with Java.

public class SimpleXMLOut {
    public static void main(String args[]) {
        String[] input = {"John Doe,123-456-7890", "Bob Smith,123-555-1212"};
        String[] line = new String[2];

        System.out.println("<?xml version="1.0" encoding="UTF-8"?>");
        System.out.println("    <members>");
        for (int i=0; i < input.length; i++) {
            line = input[i].split(",");
            System.out.println("        <member>");
            System.out.println("            <name>" + line[0] + "</name>");
            System.out.println("            <phone>" + line[1] + "</phone>");
            System.out.println("        </member>");
        System.out.println("    </members>");

First initialize a string array to hold the data that will build the XML structure and a second string array to hold the data items contained in the line. Now output the XML header tag, root tag, and members tag. Next loop through the data splitting the line on comma. Build the XML tag member and nest the name and phone tags. The name and phone tags contain the data as text nodes. Close the tags and it's done.

Using DOM

Creating a document is done with the DocumentBuilderFactory and DocumentBuilder classes. The method DocumentBuilder.newDocument is used to create the document. Documents are made up of elements which are the base objects of DOM documents. Use the createElement method of the document object, and pass the name of the element as a parameter.

Once an element has been created it must be appended to the document. Use the appendChild function of the parent element or document object passing the child element as a parameter. To nest elements simply use the appendChild method of the element you wish to be the parent of the node.

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.Document;
import org.w3c.dom.Element;

public class DOMBasicDoc {
    public static void main(String args[]) {
        try {
            String[] input = {"John Doe,123-456-7890", "Bob Smith,123-555-1212"};
            String[] line = new String[2];
            DocumentBuilderFactory dFact = DocumentBuilderFactory.newInstance();
            DocumentBuilder build = dFact.newDocumentBuilder();
            Document doc = build.newDocument();
            Element root = doc.createElement("root");
            Element memberList = doc.createElement("members");
            for (int i = 0; i < input.length; i++) {
                line = input[i].split(",");
                Element member = doc.createElement("member");
                Element name = doc.createElement("name");
                Element phone = doc.createElement("phone");
            TransformerFactory tFact = TransformerFactory.newInstance();
            Transformer trans = tFact.newTransformer();

            StringWriter writer = new StringWriter();
            StreamResult result = new StreamResult(writer);
            DOMSource source = new DOMSource(doc);
            trans.transform(source, result);

        } catch (TransformerException ex) {
            System.out.println("Error outputting document");
        } catch (ParserConfigurationException ex) {
            System.out.println("Error building document");

First setup the string array input containing the data to build the XML structure from. The string array line will be used to hold the split CSV input data. Next initialize the DocumentBuilderFactory object. Use the DocumentBuilderFactory to create a DocumentBuilder instance with the newDocumentBuilder() method. Finally create the document with the DocumentBuilder object using the newDocument() method. This is why for small simple structures strings are quicker and easier, using DOM can be verbose.

Building documents is as simple as creating elements and appending them as children where they should go in the document. First create the root element with the document objects createElement() method passing the name of the element as a parameter. Elements are the tags in the XML document. Next use the appendChild method of the document to append the root tag to the document. Now create an element "members". The list of members will be appended to this element. Use the createElement() method of the document object to create the members element. Now use the root element objects appendChild() method to append the members element as a child of the root tag. Always use the appendChild() method of the parent object to which new node should be nested.

Loop through the input array to build the member list. Each time through the loop set the string array input to the comma split values of the input array data. Create a new element member and append it to the members node. Next create child nodes to hold the name and phone number values from the input array. Use createElement() to create name and phone elements. To store a text value in a tag use the createTextNode() method of the document object. Pass the text value as a parameter to the createTextNode() method. Append the text node to the element that will hold the value. Append the name and phone elements to the member tag created on each iteration of the loop.

Now that the document is built it has to be transformed to be displayed as a string or sent to an output stream. First initialize the TransformerFactory and use newTransformer() to create the transformer object. The transformer object will be used to take the DOM and pass it to the output stream. Next initialize a StringWriter object. Then create a StreamResult object and pass it the StringWriter object.

Build a new DOMSource object from the document. Now use the transformer object to transform the DOM to the output stream. Finally to output the XML use the StringWriters toString() method to get the XML as a string. Both the Transformer and the DOM DocumentBuilder throw exceptions, TransformerException and ParserConfigurationException respectively. For the sake of simplicity this tutorial simply passes them to the built in java logger.

 1 2  >> DOM and Attributes
New Content