org.w3c.dom.Document对标准输出进行漂亮打印(也称为格式化)的最简单方法是什么?
org.w3c.dom.Document
调用printDocument(doc, System.out),该方法如下所示:
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是可选的,可能不适用于您的特定配置)
indent-amount