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);
        }

 

dom4j-out-01

 

首先使用 OutputFormat 和 Writer 來進行輸出。

 

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

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章