Element rootElement = document.addElement("data");
document.setXMLEncoding("GBK"); //默認utf-8
...
使用“document.setXMLEncoding”這樣設置而生成的xml文件仍然是utf-8編碼。
需要使用OutputFormat設置輸出文件編碼格式。
public static void writeXMLFile(Document document,File file,String Encoding){ try { OutputFormat format = OutputFormat.createPrettyPrint();//美化輸出 不想美化可以使用new OutputFormat(); format.setEncoding(Encoding.toUpperCase()); OutputStream out = new FileOutputStream(file); XMLWriter writer = new XMLWriter(out,format); writer.write(document); writer.close(); }catch (IOException e) { e.printStackTrace(); }
使用“OutputFormat”,可以設置xml輸出文件編碼,並且xml文件聲明處也會跟著改變。
引用別人答案:解釋“document.setXMLEncoding”和“format.setEncoding”設置編碼的區別
public class TestXML{ @Test public void test() throws IOException{ Document doc = new DefaultDocument(); doc.addElement("root"); // 這裡打印出來是默認的utf-8 System.out.println(doc.asXML()); doc.setXMLEncoding("utf-16"); // 這裡打印出來是修改後的utf-16 System.out.println(doc.asXML()); // 這裡沒有設置編碼格式默認保存的是utf-8,看一下dom4j的源碼就知道了 saveXML(doc, "D:\temp\test\test1.xml", null); // 這裡設置了所以保存以後編碼格式是big5 saveXML(doc, "D:\temp\test\test2.xml", "big5"); } private void saveXML(Document doc, String filePath, String encode) throws IOException{ OutputFormat format = new OutputFormat(); if (null != encode){ format.setEncoding(encode.toUpperCase()); } XMLWriter xmlWriter = new XMLWriter(new FileOutputStream(filePath),format); xmlWriter.write(doc); xmlWriter.flush(); xmlWriter.close(); }}
最後要說一下:
XMLWriter可以傳入OutputStream或者Writer
XMLWriter writer = new XMLWriter(OutputStream, OutputFormat);
XMLWriter writer = new XMLWriter(Writer, OutputFormat);
最初試著傳入了new FileWriter(file),如下
try {
XMLWriter writer = new XMLWriter(new FileWriter(f), format);
writer.write(document);
writer.close();
result = fileName;
} catch (IOException e) { // TODO Auto-generated catch block
e.printStackTrace();
}
但是得到的結果並不對。修改為如下後,結果正確。
try {
OutputFormat format = OutputFormat.createPrettyPrint();
XMLWriter xmlWriter = new XMLWriter(new FileOutputStream(f), format);
xmlWriter.write(document);
xmlWriter.flush();
xmlWriter.close();
result = fileName;
} catch (IOException e) { // TODO Auto-generated catch block
e.printStackTrace();
LOG.error("trans for XML error:", e);
}
記錄。
dom4j+xpath讀取xml文件配置Oracle數據庫連接 http://www.linuxidc.com/Linux/2013-04/83405.htm
Struts2+jQuery+Dom4j實現服務器返回Xml文檔 http://www.linuxidc.com/Linux/2012-07/65680.htm
Java使用dom4j解析XML字符串 http://www.linuxidc.com/Linux/2013-07/87734.htm