Monday, April 6, 2009

Another way to write out an XML document in Java

This comes from the "you learn something everyday" department as I am currently reviewing a book on XML and JDeveloper. Now Java has some perfectly good APIs to load XML documents; but nothing standard to write them out again. Mostly you either end up casting to a particular implementation class or using the XLST with an identity transformer.

TransformerFactory tFactory =
Transformer identityTransformer = tFactory.newTransformer();
  new DOMSource(document),
  new StreamResult(...));

It turns out that in version 3.0 of DOM they added support for APIs to load and save XML documents. They do suffer from the non-Java weirdness of all the DOM apis; but you can use then to write out an XML document:



import org.w3c.dom.DOMImplementation;
import org.w3c.dom.Document;
import org.w3c.dom.bootstrap.DOMImplementationRegistry;

DOMImplementation impl = DOMImplementationRegistry.newInstance()
    .getDOMImplementation("Core 3.0");
DOMImplementationLS feature = (DOMImplementationLS)impl.getFeature("LS", "3.0");

Document doc = impl.createDocument("", "fred", null);

LSOutput output = feature.createLSOutput();
    new FileWriter("/tmp/output.xml"));
LSSerializer serializer = feature.createLSSerializer();
    doc, output);

Unfortunately I still think that the XLST code is more compact. You might consider the DOM version if you want to be more obvious in your intent.

No comments: