publicclassTestXML { @Test publicvoidtest()throwsIOException { Documentdoc=newDefaultDocument(); 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"); } privatevoidsaveXML(Documentdoc,StringfilePath,Stringencode) throwsIOException { OutputFormatformat=newOutputFormat(); if(null!=encode) { format.setEncoding(encode.toUpperCase()); } XMLWriterxmlWriter=newXMLWriter(newFileOutputStream(filePath),format); xmlWriter.write(doc); xmlWriter.flush(); xmlWriter.close(); } }
原文链接:https://www.f2er.com/xml/297598.html