一尘不染

漂亮地将org.w3c.dom.Document打印到stdout的最短方法是什么?

java

org.w3c.dom.Document对标准输出进行漂亮打印(也称为格式化)的最简单方法是什么?


阅读 284

收藏
2020-09-09

共1个答案

一尘不染

调用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是可选的,可能不适用于您的特定配置)

2020-09-09