我有以下代码:
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 是相同的。
为什么第一个示例可以工作,而第二个示例却失败?
最佳答案
我无法重现您所看到的异常,以下内容对我有用。
福
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>
关于java - 使用 JAXB 编码时出现 "Unrecognizable signature"错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14287378/