1

我有以下代码:

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

它工作正常。

我也有以下代码:

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

在这种情况下执行对 marshal 的调用会产生以下异常:

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

两种情况下的 jaxbElement 是相同的。

为什么第一个示例有效,而第二个示例失败?

4

1 回答 1

1

我无法重现您看到的异常,以下对我有用。

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;
    }

}

演示

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

}

输出

<?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>
于 2013-01-13T11:48:03.300 回答