使用DOM4J的XMLWriter输出UTF-8编码的XML文件时,出现乱码。
XMLWriter xmlWriter = null;
try {
FileWriter fw = new FileWriter("message.xml");
OutputFormat outFormat = OutputFormat.createPrettyPrint();
outFormat.setEncoding("UTF-8");
outFormat.setTrimText(false);
xmlWriter= new XMLWriter(fw,outFormat);
xmlWriter.write(doc);
} catch (IOException e) {
e.printStackTrace();
}finally{
if(xmlWriter!=null)
xmlWriter.close();
}
doc如果含有中文,会出现乱码的问题,将上面的FileWriter改成FileOutputStream便可以了。
XMLWriter xmlWriter = null;
try {
OutputFormat outFormat = OutputFormat.createPrettyPrint();
outFormat.setEncoding("UTF-8");
outFormat.setTrimText(false);
xmlWriter= new XMLWriter(new FileOutputStream("message.xml"),outFormat);
xmlWriter.write(doc);
} catch (IOException e) {
e.printStackTrace();
}finally{
if(xmlWriter!=null)
xmlWriter.close();
}