我无法重现您看到的异常,以下对我有用。
富
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>