Java: String with XML to DOM Document to String with XML

Published:

Here's how to convert a Java string containing XML into a Document and back using only Java 1.5 built-in classes.

String to Document

public static Document parse(String subject) throws Exception
{
    DocumentBuilderFactory factory = DocumentBuilderFactory
        .newInstance();
    factory.setNamespaceAware(true);

    return factory
        .newDocumentBuilder()
        .parse(new InputSource(new StringReader(subject)));
}

Fairly straight forward when you just know what classes to use.

If you do this more than seldom you should avoid creating new instances of the DocumentBuilderFactory unless you have to. The DocumentBuilder can also be reused if you call the reset method between uses, but not across threads ๐Ÿ™‚

Document (or any Node really) to String

public static String toString(Node subject, boolean omitXmlDeclaration, boolean indent) throws Exception
{
    Transformer t = TransformerFactory
        .newInstance()
        .newTransformer();
    t.setOutputProperty(OutputKeys.INDENT, indent ? "yes" : "no");
    t.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, omitXmlDeclaration ? "yes" : "no");

    StringWriter writer = new StringWriter();
    t.transform(new DOMSource(subject), new StreamResult(writer));
    return writer.toString();

}

Here we take advantage of the newTransformer() method which returns a Transformer which does a simple copy of source to result (identity transform). So to get the string representation of the xml we just feed the transformation result into a StringWriter and voilร . ๐Ÿ™‚

Here, like when parsing, you should avoid recreating the TransformerFactory instance unless absolutely necessary. The Transformer itself can also be reused, but not across threads.

๐Ÿ“ I have ignored all exceptions in both examples here for less clutter, but in real code you should of course deal with those a bit more wisely. ๐Ÿ˜‰

Simple usage test

public static void main(String[] args) throws Exception
{
    String xml = "<foo>bar</foo>";
    Node node = parse(xml);
    out.println(toString(node, true, true));
}

Easy peasy. You might want to stick these methods in a helper class or something, and maybe even add some more versions of the methods. If you for example take a look at the API of the DocumentBuilder.parse method you'll find that it can take files, streams, uris, et cetera, so there are good alternatives if your XML isn't in a string. ๐Ÿ™‚

Either way, have fun! And if you sit there, stuck with Java 1.5, hating dealing with XML and the ugly Java API in general, unable to use 3rd party libraries... at least you can know that you're not alone ๐Ÿ˜‰