Share this page to your:
Mastodon

I am trying to output an XML Document (org.w3c.doc.Document) from Java. I always forget how to do this, somehow it doesn’t work with the way I think. So I googled and found this code:

TransformerFactory factory = TransformerFactory.newInstance();
Transformer transformer = factory.newTransformer();
DOMSource source = new DOMSource(document);
StreamResult result = new StreamResult(System.out);
transformer.transform(source, result);

But this gave me a NullPointerException down in the org.apache.xml.utils.TreeWalker.
Huh? I seemed to recall that there was a better way to do this than calling a dummy xsl transform, which is what the above code does. A bit more searching and I found the method I’ve used previously:

XMLSerializer serializer = new XMLSerializer();
serializer.setOutputByteStream(System.out)
serializer.serialize(doc);

And that works fine. It seems there is a bug in the tree walker class triggered when text nodes are empty. Not much detail but I found it here.

Previous Post Next Post