将 org.w3c.dom.Document
打印到标准输出的最简单方法是什么?
最佳答案
调用 printDocument(doc, System.out)
,该方法如下所示:
public static void printDocument(Document doc, OutputStream out) throws IOException, TransformerException {
TransformerFactory tf = TransformerFactory.newInstance();
Transformer transformer = tf.newTransformer();
transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no");
transformer.setOutputProperty(OutputKeys.METHOD, "xml");
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");
transformer.transform(new DOMSource(doc),
new StreamResult(new OutputStreamWriter(out, "UTF-8")));
}
(indent-amount
是可选的,可能不适用于您的特定配置)
关于java - 将 org.w3c.dom.Document 漂亮地打印到标准输出的最短方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2325388/