Java中的XML输出——DOMImplementationLS是什么?
16lz
2021-01-22
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)".
这种方便方法是否已经存在于Java或公共库中?它看起来冗长得可笑,甚至在这个版本中所有的异常都在一个“catch (Exception e)”下崩溃。
2 个解决方案
#1
0
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) {
}