http://tech.ccidnet.com/art/3737/20050111/456953_1.html
Dom 4j 格式化xml補充
作爲一個優秀的XML framework的Dom4j,本身提供了格式化文件的一些方法,讓我們看看如何可以更方便的處理。
本文涉及如何格式化xml輸出,設置輸出字符集,以及XMLWriter不同的writer方法的區別。
Dom4j提供的格式化xml方法:
OutputFormat format = OutputFormat.createPrettyPrint();
XMLWriter writer = new XMLWriter( out, format );
writer.write( document );
writer.close();
這裏創建一個 OutputFormat 類,用來作爲生成XMLWriter的參數。然後創建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();
}
在這裏我們創建一個StringWriter類,把XMLWriter輸出到StringWriter,然後返回Xml的文本內容。
在這裏也許你會很奇怪,爲什麼不用XMLWriter的 write(String text) 方法, 而是採用write(Document doc)方法呢,下面我們可以做一個試驗。
<?xml version="1.0" encoding="gb2312"?>
<DSTreeRoot text="root根" open="true">
<DsTree text="節點1" open="true"/>
<DsTree text="節點2" open="true"/>
</DSTreeRoot>
<?xml version="1.0" encoding="UTF-8"?> <DSTreeRoot text="root根" open="true"><DsTree text="節點1"
open="true"/><DsTree text="節點2" open="true"/></DSTreeRoot>
我們可以看到,使用第二種方法,輸出並沒有進行格式化,並且輸出結果進行了html的轉換。詳細你可以查看dom4j的源碼,在格式化String方法中,默認採用轉換方法。
最後在提一點,方法format.setEncoding("gb2312")可以設置輸出內容的字符集,也包含了xml文件頭聲明<?xml version="1.0" encoding="gb2312"?>。