[英]Problems with JAXB, Marshal, - unable to marshal type “java.lang.String”
when I run the marshal operation I get the following error: 当我运行marshal操作时,我收到以下错误:
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
This is my function for Marshalling... 这是我编组的功能......
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();
}
Thanks for your interests.. 谢谢你的兴趣..
You can't marshal just a String
as it doesn't have any root element information (hence the exception about the missing @XmlRootElement
annotation), but you can wrap it in an instance of JAXBElement
and then marshal that. 你不能只编组一个
String
因为它没有任何根元素信息(因此有关缺少的@XmlRootElement
注释的例外),但你可以将它包装在JAXBElement
一个实例中,然后编组它。 JAXBElement
is another way to supply this root element information to JAXB. JAXBElement
是向JAXB提供此根元素信息的另一种方法。
Example of Creating the JAXBElement
创建
JAXBElement
示例
JAXBElement<String> jaxbElement =
new JAXBElement(new QName("root-element"),
String.class, string);
If you Generated your Model From an XML Schema 如果您从XML架构生成模型
If you created your object model from an XML Schema. 如果您是从XML Schema创建了对象模型。 And you have a top-level XML element that is a data type like
xs:string
then there will be a convenience method on the generated ObjectFactory
class that will help you create the JAXBElement
instance. 你有一个顶级的XML元素,它是一个像
xs:string
这样的数据类型,然后在生成的ObjectFactory
类上会有一个方便的方法来帮助你创建JAXBElement
实例。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.