Java and XML quick start tips

I see a lot of code that makes using Java and XML libraries overly verbose and complex. It bothers me because Java has a ton of XML support packaged right into the JRE. However, there’s a couple simple things that aren’t no brainer one-liners that I wanted to post.

Creating a new DOM document. For better or for worse, Java wasn’t interested in making a simple DOM Document bean that you can initialize with Document document = new Document(). But, you shouldn’t be wasting more than three lines on your document initialization:

DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document doc = builder.newDocument();
Printing XML DOM. You’d think spitting your DOM out to a string would be simply encapsulated in toString() or some other single function. Unless your using some higher level library like XMLBeans, this isn’t so true. However, it does buy you a lot of flexibility with how to output your xml. This is the simplest way I’ve encountered:
protected void printXmlDocument(Document document, Writer writer) throws TransformerException {
 TransformerFactory transformerFactory = TransformerFactory.newInstance();
 transformerFactory.setAttribute("indent-number", 2);
 Transformer transformer = transformerFactory.newTransformer();
 transformer.setOutputProperty(OutputKeys.INDENT, "yes");
 DOMSource source = new DOMSource(document);
 StreamResult result = new StreamResult(writer);
 transformer.transform (source, result);
}
Note that above I included two extra lines to provide some nice pretty printing with 2 space indents. If you omit these lines you can output your XML with even less code, but it’ll all be one string.
Well, that’s all that was on my mind, but those are two blocks of code I find myself referencing all the time.

Leave a Reply