当我将 Java 对象编码到 XML 中时,在根标记结束后会添加一些额外的字符。
以下是我将 XML 解码后生成的 java 对象保存到文件中的方法:
public void saveStifBinConv(ConversionSet cs, String xmlfilename) {
FileOutputStream os = null;
try {
os = new FileOutputStream(xmlfilename);
this.marshaller.marshal(cs, new StreamResult(os));
}
catch (IOException e) {
log.fatal("IOException when marshalling STIF Bin Conversion XML file");
throw new WmrFatalException(e);
}
finally {
if (os != null) {
try {
os.close();
}
catch (IOException e) {
log.fatal("IOException when closing FileOutputStream");
throw new WmrFatalException(e);
}
}
}
}
多余的字符被填充在根标签的结束标签之后。
添加的字符是 XML 中的一些字符。示例:tractor-to-type><bin-code>239</bin-code><allowed>YES</allowed></extractor-to></extractor-mapping><extractor-mapping><e
我使用 Spring OXM 的 Jaxb2Marshaller
和 JAXB 2。
谢谢;)
最佳答案
这是因为我在保存 XML
时执行了 2 个步骤:
- 将
XML
编码到FileOutputStream
,生成XML
文件 - 然后在步骤 1 中的
XML
文件上打开FileInputStream
,并将FileInputStream
写入ServletOutputStream
一定发生了缓冲区下溢
。
解决方案
将 XML
直接编码到 ServletOutputStream
(供 Web 用户下载 XML
文件)。
JAXBContext jc = JAXBContext.newInstance(pkg);
Marshaller m = jc.createMarshaller();
m.marshal(cs, os);
其中os
是一个ServletOutputStream
。
//return an application file instead of html page
response.setContentType("text/xml");//"application/octet-stream");
response.setHeader("Content-Disposition", "attachment;filename="
+ xmlFilename);
OutputStream out = null;
out = response.getOutputStream();
关于java - JAXB - 根标签结束后添加额外字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6743694/