1

当我将 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 OXMJaxb2Marshaller和 JAXB 2。

谢谢 ;)

4

1 回答 1

1

这是因为我做了两个步骤来保存XML

  1. 编组XML到 a FileOutputStream,产生一个XML文件
  2. 然后在步骤 1 中打开文件FileInputStream上的a 并将其写入aXMLFileInputStreamServletOutputStream

一定有buffer underflow事情发生。

解决方案

直接编组XML到一个ServletOutputStream(供网络用户下载XML文件)。

        JAXBContext jc = JAXBContext.newInstance(pkg);
        Marshaller m = jc.createMarshaller();
        m.marshal(cs, os);

哪里osServletOutputStream

    //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();
于 2011-08-25T06:42:24.450 回答