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();
}
}
{
@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();
}
}