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();
}
可根据需要更改编码。
本文介绍了一个Java方法,用于格式化XML字符串并将其编码为gb2312格式。该方法使用了第三方库DocumentHelper来解析原始XML字符串,并通过OutputFormat创建了一个格式化的输出。文章详细展示了如何设置输出格式、编码及输出到控制台的过程。
3129

被折叠的 条评论
为什么被折叠?



