1

javax.xml.bind.MarshalException - with linked exception: [javax.xml.stream.XMLStreamException: Can not output XML declaration, after other output has already been done.] at com.sun.xml.bind.v2.runtime.MarshallerImpl.write(MarshallerImpl.java:330) at com.sun.xml.bind.v2.runtime.MarshallerImpl.marshal(MarshallerImpl.java:178)

Here is my code snippet:

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

Do you have any ideas why this occurs? Thanks in advance

1 Answers1

0

You need to specify JAXB_FRAGMENT property on the Marshaller to avoid this problem. This property lets JAXB know it's marshalling into the middle of a document and that it shouldn't write the header.

For More Information

bdoughan
  • 142,244
  • 22
  • 280
  • 377