Welcome 微信登录
编程资源 图片资源库 蚂蚁家优选 PDF转换器

首页 / 操作系统 / Linux / Dom4j 改变XML编码

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: emp est est1.xml", null); // 这里设置了所以保存以后编码格式是big5 saveXML(doc, "D: emp est est2.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();}但是得到的结果并不对。修改为如下后,结果正确。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);}记录。 dom4j+xpath读取xml文件配置Oracle数据库连接 http://www.linuxidc.com/Linux/2013-04/83405.htmStruts2+jQuery+Dom4j实现服务器返回Xml文档 http://www.linuxidc.com/Linux/2012-07/65680.htmJava使用dom4j解析XML字符串 http://www.linuxidc.com/Linux/2013-07/87734.htm本文永久更新链接地址:http://www.linuxidc.com/Linux/2015-04/115681.htm