JAXB、Marshal 的问题 - 无法编组类型“java.lang.String”
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/26166751/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Problems with JAXB, Marshal, - unable to marshal type “java.lang.String”
提问by nurdan karaman
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..
谢谢你的兴趣..
回答by bdoughan
You can't marshal just a Stringas it doesn't have any root element information (hence the exception about the missing @XmlRootElementannotation), but you can wrap it in an instance of JAXBElementand then marshal that. JAXBElementis another way to supply this root element information to JAXB.
您不能仅编组 a,String因为它没有任何根元素信息(因此有关缺少@XmlRootElement注释的例外),但您可以将其包装在 of 的实例中JAXBElement,然后编组它。 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. And you have a top-level XML element that is a data type like xs:stringthen there will be a convenience method on the generated ObjectFactoryclass that will help you create the JAXBElementinstance.
如果您从 XML 架构创建对象模型。并且您有一个顶级 XML 元素,它是一种数据类型,xs:string然后在生成的ObjectFactory类上会有一个方便的方法来帮助您创建JAXBElement实例。

