This article is supposed to start you off for writing applications which read and write XML data in Java. In 80% of cases when somebody needs to start such and application from scratch, he doesn’t need too much theory about XML, instead he wants to have a piece of code that simply shows how to handle it. So, here it is. You will see below two programs, first reading an XML and second writing it using DOM.

First the reader. We will read in the following XML file:

<?xml version="1.0" encoding="UTF-8"?>
<root testAttr="testValue">
	<child>data1</child>
	<child>data2</child>
</root>

And here the code that reads it:

1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
31:
32:
33:
34:
35:
36:
37:
38:
39:
40:
41:
42:
43:
44:
45:
46:
47:
48:
49:
50:
61:
62:
63:
64:
65:
import java.io.File;

import javax.xml.parsers.*;

//You may be surprised by the presence of org.* packages.
//But don't be afraid, you will not have to attach any
//additional libraries. These packages come with the
//standard Java 1.6.
import org.w3c.dom.*;

public class XMLRead {
    public static void main(String[] args) throws Exception  {

        //The two lines below are just for getting an
        //instance of DocumentBuilder which we use
        //for parsing XML data
        DocumentBuilderFactory factory =
            DocumentBuilderFactory.newInstance();
        DocumentBuilder builder = factory.newDocumentBuilder();

        //Here we do the actual parsing
        Document doc = builder.parse(new File("test.xml"));

        //Here we get the root element of XML and print out
        //the value of its 'testAttr' attribute
        Element rootElement = doc.getDocumentElement();
        System.out.println("testAttr for root element: "
            + rootElement.getAttribute("testAttr"));

        //Here we get a list of all elements named 'child'
        NodeList list = rootElement.getElementsByTagName("child");

        //Traversing all the elements from the list and printing
        //out its data
        for (int i = 0; i < list.getLength(); i++) {
            //Getting one node from the list.
            //BTW, we used method getElementsByTagName so every entry
            //in the list is effectively of type 'Element', so you could
            //cast it directly to 'Element' if you needed to.
            Node childNode = list.item(i);
            System.out.println("data in child number "+
                i+": "+childNode.getTextContent());
        }
    }
}

If you run it you will receive output like this:

testAttr for root element: testValue
data in child number 0: data1
data in child number 1: data2

Now the writer. It will create one simple XML file with one tag inside.

1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
31:
32:
33:
34:
35:
36:
37:
38:
39:
40:
41:
42:
43:
44:
45:
46:
47:
48:
49:
50:
61:
62:
63:
64:
65:
66:
67:
68:
import java.io.*;

import javax.xml.parsers.*;
import javax.xml.transform.*;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.w3c.dom.*;

public class XMLWrite {
    public static void main(String[] args)  throws Exception {

        DocumentBuilderFactory factory =
            DocumentBuilderFactory.newInstance();
        DocumentBuilder builder = factory.newDocumentBuilder();

        // Here instead of parsing an existing document we want to
        // create a new one.
        Document testDoc = builder.newDocument();

        // This creates a new tag named 'testElem' inside
        // the document and sets its data to 'TestContent'
        Element el = testDoc.createElement("testElem");
        el.setTextContent("TestContent");
        testDoc.appendChild(el);

        // The XML document we created above is still in memory
        // so we have to output it to a real file.
        // In order to do it we first have to create
        // an instance of DOMSource
        DOMSource source = new DOMSource(testDoc);

        // PrintStream will be responsible for writing
        // the text data to the file
        PrintStream ps = new PrintStream("test2.xml");
        StreamResult result = new StreamResult(ps);

        // Once again we are using a factory of some sort,
        // this time for getting a Transformer instance,
        // which we use to output the XML
        TransformerFactory transformerFactory = TransformerFactory
            .newInstance();
        Transformer transformer = transformerFactory.newTransformer();

        // The actual output to a file goes here
        transformer.transform(source, result);
    }
}

When you run it, file “test2.xml” will be created and its inside will look like this:

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<testElem>TestContent</testElem>

We showed here the simplest possible way of using standard Java XML-DOM. You can read much more about processing XML files in Java from here. There is also a way to handle XMLs even easier using Xerces, which we hope to cover on this blog some other time.