Element rootElement = document.addElement("data");document.setXMLEncoding("GBK");//默認(rèn)utf-8...
使用document.setXMLEncoding
這樣設(shè)置而生成的xml文件仍然是utf-8
編碼。
需要使用OutputFormat
設(shè)置輸出文件編碼格式。
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
,可以設(shè)置xml輸出文件編碼,并且xml文件聲明處也會跟著改變。
引用別人答案:解釋document.setXMLEncoding
和format.setEncoding
設(shè)置編碼的區(qū)別
public class TestXML{ @Test public void test() throws IOException{ Document doc = new DefaultDocument(); doc.addElement("root"); // 這里打印出來是默認(rèn)的utf-8 System.out.println(doc.asXML()); doc.setXMLEncoding("utf-16"); // 這里打印出來是修改后的utf-16 System.out.println(doc.asXML()); // 這里沒有設(shè)置編碼格式默認(rèn)保存的是utf-8,看一下dom4j的源碼就知道了 saveXML(doc, "D://temp//test//test1.xml", null); // 這里設(shè)置了所以保存以后編碼格式是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或者WriterXMLWriter 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 blocke.printStackTrace();}但是得到的結(jié)果并不對。修改為如下后,結(jié)果正確。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 blocke.printStackTrace();LOG.error("trans for XML error:", e);}
記錄。
相關(guān)鏈接:http://www.companysz.com/problems/64178http://bbs.csdn.net/topics/370057777http://liuchunqing2001.blog.163.com/blog/static/3082291201382911214196/http://lavasoft.blog.51cto.com/62575/235272http://www.educity.cn/wenda/105197.htmlhttp://www.blogjava.net/i369/articles/154264.htmlhttp://bbs.csdn.net/topics/290027113http://developer.51cto.com/art/200903/117512.htmhttp://pridesnow.VEvb.com/blog/561958http://blog.csdn.net/chenghui0317/article/details/11486271Java創(chuàng)建xml文檔筆記(DOM,DOM4J)http://www.companysz.com/lanxuezaipiao/archive/2013/05/17/3082949.html
新聞熱點
疑難解答