Saving an XML DOM with JAXP


To save an XML DOM document with JAXP, use an identity Transformer with a DOMSource and a StreamResult.

Document d;
Transformer t = TransformerFactory.newInstance().newTransformer();
t.transform(new DOMSource(d), new StreamResult(new File("output-file")));

It’s elegant, if verbose. One bug that’s been around since the start, however (as noted by Elliotte Rusty Harold in the footer to a related example) is that namespaces are silently ignored. Looks like the fixed Apache XML code has finally been rolled into J2SDK 5.0, but that’s still not the live release being served by Java.com, so the quickest workaround I know of is to bring in a better XML serializer; by habit, I go for David Megginson’s XMLWriter: it deals well with namespaces, and it’s been generously placed in the public domain, so there are no licensing concerns.

Transformer t = TransformerFactory.newInstance().newTransformer();
XMLWriter xw = new XMLWriter(new FileWriter("output-file"));
t.transform(new DOMSource(d), new SAXResult(xw));

Roll on, Free Java...

(Music: Slayer, “Filler”)
(More from this year, or the front page? [K])