JAXB输出问题:奇怪的异常

JAXB输出问题:奇怪的异常,jaxb,marshalling,xml-binding,Jaxb,Marshalling,Xml Binding,javax.xml.bind.MarshalException -除此之外: [javax.xml.stream.XMLStreamException:在完成其他输出后,无法输出xml声明。] 位于com.sun.xml.bind.v2.runtime.MarshallerImpl.write(MarshallerImpl.java:330) 位于com.sun.xml.bind.v2.runtime.MarshallerImpl.marshall(MarshallerImpl.java:178

javax.xml.bind.MarshalException -除此之外: [javax.xml.stream.XMLStreamException:在完成其他输出后,无法输出xml声明。] 位于com.sun.xml.bind.v2.runtime.MarshallerImpl.write(MarshallerImpl.java:330) 位于com.sun.xml.bind.v2.runtime.MarshallerImpl.marshall(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();
OutputStream output=newbytearrayoutputstream();
XMLOutputFactory xof=XMLOutputFactory.newInstance();
XMLStreamWriter xsw=xof.createXMLStreamWriter(输出);
QName root=新的QName(“返回”);
JAXBElement je=新的JAXBElement(root,Customer.class,Customer);
xsw.writeStartDocument();
setDefaultNamespace(“S”);
writeStarteElement(“S”、“信封”、“信封”http://schemas.xmlsoap.org/soap/envelope/");
writeStarteElement(“S”,“Body”,”http://schemas.xmlsoap.org/soap/envelope/");
writeStarteElement(“ns0”、“findCustomerResponse”、”http://service.jaxws.blog/");
context=JAXBContext.newInstance(Customer.class);
Marshaller=context.createMarshaller();
setProperty(marshaller.JAXB_格式的_输出,Boolean.TRUE);
元帅,元帅(je,xsw);
xsw.writeEndDocument();
xsw.close();
if(输出!=null)
返回output.toString();

你知道为什么会这样吗?提前感谢

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

了解更多信息