将 org.w3c.dom.Document 打印到 stdout 的最短方法是什么?
将漂亮的打印(又名格式化)到标准输出的最简单方法是什么?org.w3c.dom.Document
将漂亮的打印(又名格式化)到标准输出的最简单方法是什么?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
怎么样:
OutputFormat format = new OutputFormat(doc);
format.setIndenting(true);
XMLSerializer serializer = new XMLSerializer(System.out, format);
serializer.serialize(doc);