zoukankan      html  css  js  c++  java
  • Dom4j 如何输出 Document 中的内容到文本

    假设我们先定义一个 Dom4j 中的 Document 对象。

    Document document = DocumentHelper.createDocument();
    

    如果我们想将 document 中的内容输出的话,我们是不能用 document.toString() 这个方法的,因为这个方法输出的是 document 这个对象的引用。

    因此我们需要使用:

    document.asXML()
    

    来将 document 对象中的数据转换为可以读的字符串。

    格式化输出

    但是 asXML() 这个方法的输出是不会格式化的,所有的字符串全部都在 1 行里面。

    因此如果我们需要格式化输出的话,应该使用下面的代码:

            try {
                OutputFormat format = OutputFormat.createPrettyPrint();
                format.setEncoding("utf-8");
    
                Writer out = new StringWriter();
                XMLWriter writer = new XMLWriter(out, format);
                writer.write(document);
                writer.close();
                logger.debug("{}", out);
    
            } catch (IOException e) {
                logger.error("Write XML Error.", e);
            }
    

    首先使用 OutputFormat 和 Writer 来进行输出。

    https://www.ossez.com/t/dom4j-document/13757

  • 相关阅读:
    计算机英语
    NSQ学习记录
    Java学习记录-注解
    VS插件开发

    双链表
    顺序表
    顺序队列
    顺序栈

  • 原文地址:https://www.cnblogs.com/huyuchengus/p/15355087.html
Copyright © 2011-2022 走看看