将 org.w3c.dom.Document 漂亮地打印到标准输出的最短方法是什么? [英] What is the shortest way to pretty print a org.w3c.dom.Document to stdout?

查看:60
本文介绍了将 org.w3c.dom.Document 漂亮地打印到标准输出的最短方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

What is the easiest way to pretty print (a.k.a. formatted) a org.w3c.dom.Document to stdout?

推荐答案

调用 printDocument(doc, System.out),该方法如下所示:

Call printDocument(doc, System.out), where that method looks like this:

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

(The indent-amount is optional, and might not work with your particular configuration)

这篇关于将 org.w3c.dom.Document 漂亮地打印到标准输出的最短方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆