JAXB输出问题:奇怪的异常

时间:2013-10-21 10:35:23

标签: jaxb marshalling xml-binding

javax.xml.bind.MarshalException   - 链接异常: [javax.xml.stream.XMLStreamException:在其他输出完成后,无法输出XML声明。]     at com.sun.xml.bind.v2.runtime.MarshallerImpl.write(MarshallerImpl.java:330)     在com.sun.xml.bind.v2.runtime.MarshallerImpl.marshal(MarshallerImpl.java:178)

这是我的代码段:

OutputStream output = new ByteArrayOutputStream();
            XMLOutputFactory xof = XMLOutputFactory.newInstance();
            XMLStreamWriter xsw = xof.createXMLStreamWriter(output);


            QName root = new QName("return");
            JAXBElement<Customer> je = new JAXBElement<Customer>(root, Customer.class, customer);

            xsw.writeStartDocument();
            xsw.setDefaultNamespace("S");
            xsw.writeStartElement("S", "Envelope", "http://schemas.xmlsoap.org/soap/envelope/");
        xsw.writeStartElement("S", "Body", "http://schemas.xmlsoap.org/soap/envelope/");
        xsw.writeStartElement("ns0", "findCustomerResponse", "http://service.jaxws.blog/");

            context = JAXBContext.newInstance(Customer.class);
            Marshaller marshaller = context.createMarshaller();
            marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
            marshaller.marshal(je, xsw);
            xsw.writeEndDocument();
            xsw.close();
            if(output != null)
            return output.toString();

你有什么想法为什么会这样吗?提前致谢

1 个答案:

答案 0 :(得分:0)

您需要在JAXB_FRAGMENT上指定Marshaller属性以避免此问题。这个属性让JAXB知道它正在编组到文档的中间,并且它不应该写标题。

了解更多信息