我有以下代码:
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都相同。
为什么第一个示例有效,而第二个示例失败?
答案 0 :(得分: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>