JAXB - Extra Characters are added after the closing of the root tag
When I marshal Java objects into XML, some extra characters are added after the closing of the root tag.
Here is how I save the resulting java objects after unmarshaling from XML into a file:
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);
}
}
}
}
The extra characters are padded after closing tag of the root tag.
The characters added are some of the characters from the XML. Example: tractor-to-type><bin-code>239</bin-code><allowed>YES</allowed></extractor-to></extractor-mapping><extractor-mapping><e
开发者_如何学Python
I use Spring OXM's Jaxb2Marshaller
and JAXB 2.
Thanks ;)
This is because I do 2 steps in saving the XML
:
- marshal the
XML
to aFileOutputStream
, resulting in anXML
file - then open a
FileInputStream
on theXML
file in step 1 and write theFileInputStream
to aServletOutputStream
There must be a buffer underflow
happening.
Solution
Marshal the XML
directly to a ServletOutputStream
(for web user to download the XML
file).
JAXBContext jc = JAXBContext.newInstance(pkg);
Marshaller m = jc.createMarshaller();
m.marshal(cs, os);
where os
is a 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();
精彩评论