Dom4j 改变XML编码 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数据库连接