Document document = DocumentHelper.createDocument();
Element root = document.addElement("root");
Element author1 = root.addElement("author").addAttribute("name",
"James").addAttribute("location", "UK").addText(
"James Strachan");
Element author2 = root.addElement("author").addAttribute("name",
"中").addAttribute("location", "US").addText(
"Bob McWhirter");
OutputFormat format = OutputFormat.createPrettyPrint();
format.setEncoding("GB2312");
XMLWriter writer = new XMLWriter(new FileWriter("output.xml"),format);
writer.write(document);
writer.close();
// Pretty print the document to System.out
writer = new XMLWriter(System.out,format);
writer.write(document);
// Compact format to System.out
format = OutputFormat.createCompactFormat();
format.setEncoding("GB2312");
writer = new XMLWriter(System.out, format);
writer.write(document);
如果使用
document.setXMLEncoding("GB2312");
然后用
XMLWriter writer = new XMLWriter(new FileWriter("output.xml"));
writer.write(document);
输出的话,是没有效果的,生成的还是UTF-8的