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();
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);
}
Posted by mikescode