tags:

views:

180

answers:

2

I just had to write the following stupid class to avoid going insane:

import java.io.OutputStream;

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;

public final class XMLSerializer {
    public static final void writeDocument(Document input, OutputStream output) {
        try {
            DOMImplementationLS ls = 
                (DOMImplementationLS) DOMImplementationRegistry
                .newInstance().getDOMImplementation("LS");
            LSSerializer ser = ls.createLSSerializer();
            LSOutput out = ls.createLSOutput();
            out.setByteStream(output);
            ser.write(input, out);
        } catch (Exception e) { // DIAF Java
            throw new RuntimeException(e);
        }
    }
}

Does this convenience method already exist in Java or a common library? It seems ridiculously long-winded, and that's even the version where all exceptions are collapsed under a "catch (Exception e)".

+1  A: 

Try this:

DOMSource domSource = new DOMSource(input);
StreamResult resultStream = new StreamResult(output);
TransformerFactory transformFactory = TransformerFactory.newInstance();
try {
    serializer.transform(domSource, resultStream);
} catch (javax.xml.transform.TransformerException e) {
}
J-16 SDiZ
A: 

Try dom4j. It is an excellent XML library.

javamonkey79