首先附上一段没有改代码之前我的xml文件解析前后其中一段内容对比:
解析前:
<quoteString>N</quoteString>
<sql>-- SQL statement here
update test_column_comment
set name = 'test execute sql'</sql>
<set_params>N</set_params>
解析后:
<quoteString>N</quoteString>
<sql>-- SQL statement here update test_column_comment set name = 'test execute sql'</sql>
<set_params>N</set_params>
以下是我之前的代码:
public void writeFile(Map<String, Document> files, HttpServletResponse response) {
BufferedInputStream bis = null;
BufferedOutputStream bos = null;
try {
ZipOutputStream zos = new ZipOutputStream(response.getOutputStream());
bos = new BufferedOutputStream(zos);
for (Map.Entry<String, Document> entry : files.entrySet()) {
// 每个文件名
String fileName = entry.getKey();
// 这个文件的字节
Document file = entry.getValue();
OutputFormat format = OutputFormat.createPrettyPrint();
format.setEncoding("utf-8");
StringWriter stringWriter = new StringWriter();
/*XMLWriter xmlWriter = new XMLWriter(stringWriter, format);
xmlWriter.write(file);*/
XMLWriter hrxmlWriter = new XMLWriter(stringWriter, format);
hrxmlWriter.write(file);
hrxmlWriter.flush();
InputStream inputStream = new ByteArrayInputStream(stringWriter.toString().getBytes(StandardCharsets.UTF_8));
bis = new BufferedInputStream(inputStream);
zos.putNextEntry(new ZipEntry(fileName));
int len = 0;
byte[] buf = new byte[10 * 1024];
while ((len = bis.read(buf, 0, buf.length)) != -1) {
bos.write(buf, 0, len);
}
bos.flush();
}
} catch (IOException e) {
logger.error("文件写入失败,请检查!错误原因为:" + e.toString());
e.printStackTrace();
}finally {
close(bis,bos );
}
}
解决:我将OutpuFormat对象实例化部分的代码改成:OutputFormat format = new OutputFormat();
然后问题得以解决,之前xml中使用OutputFormat format = OutputFormat.createPrettyPrint();来实例化,我们来看一下OutputFormat.createPrettyPrint()方法就明白了:
/**
* A static helper method to create the default pretty printing format. This
* format consists of an indent of 2 spaces, newlines after each element and
* all other whitespace trimmed, and XMTML is false.
*
* 创建默认的漂亮打印格式的静态助手方法。 格式由2个空格,每个元素后的换行符和所有其他空格修
* 剪的缩进组成,并且XMTML为false。
* @return DOCUMENT ME!
*/
public static OutputFormat createPrettyPrint() {
OutputFormat format = new OutputFormat();
format.setIndentSize(2);
format.setNewlines(true);
format.setTrimText(true);
format.setPadText(true);
return format;
}
所以使用无参的构造方法就避免了对换行和空格修剪等的不必要特殊处理;createPrettyPrint方法是为了美化xml格式,换成无参构造方法虽然能解决换行变空格的问题,但是输出的xml是没有经过美化的,这种方式适合那种原来的xml就是美化过的或者对xml格式要求不高待xml输出之后再自行美化的;
这个解决方案也是有利有弊吧,觉得看个人需求,如果有更好的解决方案欢迎留言