java - 将 org.w3c.dom.Document 漂亮地打印到标准输出的最短方法是什么?

标签 java xml dom w3c

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/

相关文章:

c# - 在 C# 中对 XPathNodeIterator 的内容进行排序

javascript - 如何在不丢失其状态的情况下在 DOM 中移动 iFrame?

java - 用户加入语音通话时的 Discord Bot 消息

java - 无法获取 JDBC 连接;嵌套异常是 java.sql.SQLException : Cannot load JDBC driver class 'org.hsql.jdbcDriver'

java - 捕获事务方法内的异常后超出锁等待超时

javascript - jquery 中的 on() 函数不起作用

php - 如何获取 $node 中的 html 而不仅仅是 $nodeValue

java - 我如何在输入 Android EditText 时调用函数

java - 如何指定jgitflow发布完成触发的自动构建的构建选项?

javascript - Android 4.3 默认浏览器 : xmlDoc. 评估抛出 INVALID_EXPRESSION_ERR:DOM Xpath 异常 51