作為一個(gè)優(yōu)秀的XML framework的Dom4j,本身提供了格式化文件的一些方法,讓我們看看如何可以更方便的處理。
本文涉及如何格式化xml輸出,設置輸出字符集,以及XMLWriter不同的writer方法的區別。
Dom4j提供的格式化xml方法:
OutputFormat format = OutputFormat.createPrettyPrint(); XMLWriter writer = new XMLWriter( out, format ); writer.write( document ); writer.close();
這里創(chuàng )建一個(gè) OutputFormat 類(lèi),用來(lái)作為生成XMLWriter的參數。然后創(chuàng )建XMLWriter,調用 write 方法輸出 格式化后的 Xml 。
如果你想得到Xml 返回的內容,而不是直接輸入到output流里面,可以這樣處理:
public static String format(Document document){
StringWriter writer = new StringWriter();
OutputFormat format = OutputFormat.createPrettyPrint();
format.setEncoding("gb2312");
XMLWriter xmlwriter = new XMLWriter( writer, format );
try {
xmlwriter.write(document);
} catch (Exception e) {
e.printStackTrace();
}
return writer.toString();
}
在這里我們創(chuàng )建一個(gè)StringWriter類(lèi),把XMLWriter輸出到StringWriter,然后返回Xml的文本內容。
在這里也許你會(huì )很奇怪,為什么不用XMLWriter的 write(String text) 方法, 而是采用write(Document doc)方法呢,下面我們可以做一個(gè)試驗。
使用write(Document doc)的結果:
<?xml version="1.0" encoding="gb2312"?>
<DSTreeRoot text="root根" open="true">
<DsTree text="節點(diǎn)1" open="true"/>
<DsTree text="節點(diǎn)2" open="true"/>
</DSTreeRoot>
使用write(String text)的結果:
<?xml version="1.0" encoding="UTF-8"?> <DSTreeRoot text="root根" open="true"><DsTree text="節點(diǎn)1" open="true"/><DsTree text="節點(diǎn)2" open="true"/></DSTreeRoot>