Search code examples
javajaxb2

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

I use Spring OXM's Jaxb2Marshaller and JAXB 2.

Thanks ;)


Solution

  • This is because I do 2 steps in saving the XML:

    1. marshal the XML to a FileOutputStream, resulting in an XML file
    2. then open a FileInputStream on the XML file in step 1 and write the FileInputStream to a ServletOutputStream

    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();