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 =
    TransformerFactory.newInstance();
Transformer identityTransformer = tFactory.newTransformer();
identityTransformer.transform(
  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 java.io.FileWriter;

import java.io.IOException;

import org.w3c.dom.DOMImplementation;
import org.w3c.dom.Document;
import org.w3c.dom.bootstrap.DOMImplementationRegistry;
import org.w3c.dom.ls.DOMImplementationLS;
import org.w3c.dom.ls.LSOutput;
import org.w3c.dom.ls.LSSerializer;


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

Document doc = impl.createDocument("http://www.example.com", "fred", null);

LSOutput output = feature.createLSOutput();
output.setCharacterStream(
    new FileWriter("/tmp/output.xml"));
LSSerializer serializer = feature.createLSSerializer();
serializer.write(
    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: