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);
}
记录。
相关链接:
http://www.iteye.com/problems/64178
http://bbs.csdn.net/topics/370057777
http://liuchunqing2001.blog.163.com/blog/static/3082291201382911214196/
http://lavasoft.blog.51cto.com/62575/235272
http://www.educity.cn/wenda/105197.html
http://www.blogjava.net/i369/articles/154264.html
http://bbs.csdn.net/topics/290027113
http://developer.51cto.com/art/200903/117512.htm
http://pridesnow.iteye.com/blog/561958
http://blog.csdn.net/chenghui0317/article/details/11486271
Java创建xml文档笔记(DOM,DOM4J)
http://www.cnblogs.com/lanxuezaipiao/archive/2013/05/17/3082949.html