Simple Java DOM XML Example

copyright 2004 by Terrance Gene Davis (http://genedavissoftware.com/)

A Simple XML Document

Unfortunately DOM XML documents in Java have a reputation for being
hard to create. This simply isn’t true. The construction process is
very wordy though, but if you have a cheat sheet (like this tutorial),
then they really aren’t so bad.

I’m going to show you a base example that does everything that most
documents need to do. It has a root element. The root contains
another element that is its child. The root contains a comment too.

The child element has a name-value attribute. The child also contains
some arbitrary text.

If you have ever written a simple web page you will find this very
similar in format. XML documents are very human friendly. Here is
the simple XML Document we’ll create. You can base extremely complex
documents off of this base example.

<root>
<!--Just a thought-->
<child name="value">Filler, ... I could have had a FOO!</child>
</root>

Now I do make the assumption that you know what XML is. You create your own
mark-up language using the rules of XML. XML is not the tags, but the format
of the tags. If that makes no sense, start with a tutorial that explains
what XML is. XML is really quite fun when you get use to it.

Parts of the Java DOM Document

Now as I said earlier, there are several classes used when handling XML and
they are spread across several packages. I wouldn’t bother memorizing them.
They will commit themselves to memory if you spend a significant amount of
time using them. If you only use them once in a while, just remember where
to find a good tutorial to review when you need to.

Now before you start looking at the code, you should realize that only three
tasks occur in it. First you need a DOM document to put your XML into. Second,
the XML is assembled in tree fashion with the root element at the top. The
root is added to the Document object. Other elements can be added to the root,
and attributes are added to any elements. Comments and Text may be added to
any of the elements. Third you need to transform your XML tree into something
like an OutputStream or Writer.

The Code

So here is the code. You can pretty much tell what is going on. Just look
at the comments if something isn’t clear.

import java.io.*;

import org.w3c.dom.*;

import javax.xml.parsers.*;

import javax.xml.transform.*;
import javax.xml.transform.dom.*;
import javax.xml.transform.stream.*;

public class DomXmlExample {

    /**
     * Our goal is to create a DOM XML tree and then print the XML.
     */
    public static void main (String args[]) {
        new DomXmlExample();
    }

    public DomXmlExample() {
        try {
            /////////////////////////////
            //Creating an empty XML Document

            //We need a Document
            DocumentBuilderFactory dbfac = DocumentBuilderFactory.newInstance();
            DocumentBuilder docBuilder = dbfac.newDocumentBuilder();
            Document doc = docBuilder.newDocument();

            ////////////////////////
            //Creating the XML tree

            //create the root element and add it to the document
            Element root = doc.createElement("root");
            doc.appendChild(root);

            //create a comment and put it in the root element
            Comment comment = doc.createComment("Just a thought");
            root.appendChild(comment);

            //create child element, add an attribute, and add to root
            Element child = doc.createElement("child");
            child.setAttribute("name", "value");
            root.appendChild(child);

            //add a text element to the child
            Text text = doc.createTextNode("Filler, ... I could have had a foo!");
            child.appendChild(text);

            /////////////////
            //Output the XML

            //set up a transformer
            TransformerFactory transfac = TransformerFactory.newInstance();
            Transformer trans = transfac.newTransformer();
            trans.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
            trans.setOutputProperty(OutputKeys.INDENT, "yes");

            //create string from xml tree
            StringWriter sw = new StringWriter();
            StreamResult result = new StreamResult(sw);
            DOMSource source = new DOMSource(doc);
            trans.transform(source, result);
            String xmlString = sw.toString();

            //print xml
            System.out.println("Here's the xml:nn" + xmlString);

        } catch (Exception e) {
            System.out.println(e);
        }
    }
}