It’s a huge annoyance when you’re working with XML and after parsing the web service’s XML or deserializing the XML from BlazeDS, you see in your debugger that the output is [#document: null]. When I was still fresh out of the woods, I thought that [#document: null] is null, but as it turns out, it isn’t. The toString() method on the Document object is trying to communicate that the Document’s root element’s “node value” is not defined. Unfortunately, it chooses to represent that as [#document: null], which is just plain confusing.

If I’d read the Node documentation earlier, which states clearly that for the Document interface, the nodeName is “#document” and the nodeValue is null, it would have saved me many hours of frustration. If the XML API you’re working with returns you this output, you’d have to recurse through all the nodes and build the XML yourself. One way of avoiding this is to use JDOM:

import java.io.StringWriter;
import java.io.IOException;
import org.jdom.*;
import org.jdom.output.*;
import org.jdom.input.*;

public String buildXML(org.w3c.dom.Document xmlDoc) throws IOException
{
    xmlDoc.getDocumentElement().normalize();
    DOMBuilder domBuilder = new DOMBuilder();
    Document jdomDocument = domBuilder.build(xmlDoc);
    XMLOutputter xmlOutputter = new XMLOutputter(Format.getPrettyFormat());
    StringWriter stringWriter = new StringWriter();
    xmlOutputter.output(jdomDocument, stringWriter);
    String xmlString = stringWriter.toString();
    return xmlString;
}