我只需编写以下愚蠢的类来避免疯狂:
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);
}
}
}
这种便捷方法是否已经存在于Java或公共库中?这看起来有点啰嗦,甚至是所有例外都在“捕获(例外e)”下崩溃的版本。
答案 0 :(得分:0)
试试这个:
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) {
}
答案 1 :(得分:0)
试试dom4j。它是一个优秀的XML库。