public static String formatXml(String str) throws Exception{
Document document = null;
document = DocumentHelper.parseText(str);
//格式化输出格式
OutputFormat format = OutputFormat.createPrettyPrint();
format.setEncoding("gb2312");
StringWriter writer = new StringWriter();
//格式化输出流
XMLWriter xmlWriter = new XMLWriter(writer,format);
//将document写入到输出流
xmlWriter.write(document);
xmlWriter.close();
//输出到控制台
System.out.println(writer.toString());
return writer.toString();
}
可根据需要更改编码。