简体   繁体   中英

“Unrecognizable signature” error when marshalling with JAXB

I have the following code:

    javax.xml.bind.Marshaller m = ...
    java.io.OutputStream outputStream = ...
    Object jaxbElement = ...
    m.marshal(jaxbElement, outputStream);

It works fine.

I also have the following code:

    javax.xml.bind.Marshaller m = ...
    java.io.BufferedWriter writer = ...
    Object jaxbElement = ...
    m.marshal(jaxbElement, writer);

Executing the call to marshal in this case gives the following exception:

javax.xml.bind.MarshalException
 - with linked exception:
[java.io.IOException: Unrecognizable signature: "<?xml version="1.0" e".]

jaxbElement in both cases is the same.

Why would the first example work, while the second example fails?

I haven't been able to reproduce the exception you are seeing, the following works for me.

Foo

import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement
public class Foo {

    private String bar;

    public String getBar() {
        return bar;
    }

    public void setBar(String bar) {
        this.bar = bar;
    }

}

Demo

import java.io.*;
import javax.xml.bind.*;
import javax.xml.namespace.QName;

public class Demo {

    public static void main(String[] args) throws Exception {
        JAXBContext jc = JAXBContext.newInstance(Foo.class);

        Foo foo = new Foo();
        foo.setBar("Hello World");
        marshal(jc, foo);

        Object jaxbElement = new JAXBElement<Foo>(new QName("root"), Foo.class, foo);
        marshal(jc, jaxbElement);
    }

    private static void marshal(JAXBContext jc, Object jaxbElement) throws Exception {
        Marshaller m = jc.createMarshaller();
        StringWriter stringWriter = new StringWriter();
        BufferedWriter writer = new BufferedWriter(stringWriter);
        m.marshal(jaxbElement, writer);
        writer.close();
        System.out.println(stringWriter.toString());
    }

}

Output

<?xml version="1.0" encoding="UTF-8" standalone="yes"?><foo><bar>Hello World</bar></foo>
<?xml version="1.0" encoding="UTF-8" standalone="yes"?><root><bar>Hello World</bar></root>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM