当我运行编组操作时,我收到以下错误:
javax.xml.bind.MarshalException
- with linked exception:
[com.sun.istack.internal.SAXException2: unable to marshal type "java.lang.String" as an element because it is missing an @XmlRootElement annotation]
...
Caused by: com.sun.istack.internal.SAXException2: unable to marshal type "java.lang.String" as an element because it is missing an @XmlRootElement annotation
at com.sun.xml.internal.bind.v2.runtime.XMLSerializer.reportError(XMLSerializer.java:237)
at com.sun.xml.internal.bind.v2.runtime.LeafBeanInfoImpl.serializeRoot(LeafBeanInfoImpl.java:126)
at com.sun.xml.internal.bind.v2.runtime.XMLSerializer.childAsRoot(XMLSerializer.java:483)
at com.sun.xml.internal.bind.v2.runtime.MarshallerImpl.write(MarshallerImpl.java:308)
... 6 more
这是我的编组功能......
public StringBuffer Marshaller(Object marshall){ // make marshalling->Java to XML
StringWriter writer = new StringWriter();
try {
JAXBContext jaxbContext=JAXBContext.newInstance(marshall.getClass());
Marshaller jaxbMarshaller=jaxbContext.createMarshaller();
// çıktı
jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
jaxbMarshaller.marshal(marshall, writer);
System.out.println(writer.getBuffer().toString());
} catch (PropertyException e) {
e.printStackTrace();
} catch (JAXBException e) {
e.printStackTrace();
}
return writer.getBuffer();
}
感谢您的兴趣..
答案 0 :(得分:12)
你不能只编组一个String
,因为它没有任何根元素信息(因此缺少@XmlRootElement
注释的例外),但你可以将它包装在JAXBElement
的实例中{1}}然后封送那个。 JAXBElement
是将此根元素信息提供给JAXB的另一种方法。
创建JAXBElement
JAXBElement<String> jaxbElement =
new JAXBElement(new QName("root-element"),
String.class, string);
如果您从XML架构生成模型
如果您是从XML Schema创建了对象模型。并且您有一个顶级XML元素,它是一种数据类型,如xs:string
,那么生成的ObjectFactory
类将有一个方便的方法,可以帮助您创建JAXBElement
实例。< / p>