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
DocumentBuilderFactory factory = DocumentBuilderFactory
.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
Transformer t = TransformerFactory
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));
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.
Simple usage test
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 ;)