没有由JAXB生成的@XmlRootElement [英] No @XmlRootElement generated by JAXB

查看:147
本文介绍了没有由JAXB生成的@XmlRootElement的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试从FpML(Finanial产品标记语言)4.5版生成Java类。生成了大量代码,但我无法使用它。尝试序列化一个简单的文档,我得到这个:

I'm trying to generate Java classes from the FpML (Finanial Products Markup Language) version 4.5. A ton of code is generated, but I cannot use it. Trying to serialize a simple document I get this:

javax.xml.bind.MarshalException
  - with linked exception: [com.sun.istack.SAXException2: unable
  to marshal type
  "org.fpml._2008.fpml_4_5.PositionReport"
  as an element because it is missing an
  @XmlRootElement annotation]

实际上没有类有@XmlRootElement注释,那么什么我可以做错吗?我将xjc(JAXB 2.1)指向fpml-main-4-5.xsd,然后包含所有类型。

In fact no classses have the @XmlRootElement annotation, so what can I be doing wrong?. I'm pointing xjc (JAXB 2.1) to fpml-main-4-5.xsd, which then includes all types.

推荐答案

为了将其他人已经陈述或暗示过的内容联系在一起,JAXB XJC决定是否将 @XmlRootElement 注释放在生成的类上的规则是非常重要的( 参见本文)。

To tie together what others have already stated or hinted at, the rules by which JAXB XJC decides whether or not to put the @XmlRootElement annotation on a generated class are non trivial (see this article).

@XmlRootElement 之所以存在,是因为JAXB运行时需要某些信息才能编组/解组给定对象,特别是XML元素名称和命名空间。你不能只将任何旧物体传递给Marshaller。 @XmlRootElement 提供此信息。

@XmlRootElement exists because the JAXB runtime requires certain information in order to marshal/unmarshal a given object, specifically the XML element name and namespace. You can't just pass any old object to the Marshaller. @XmlRootElement provides this information.

注释只是一种方便,但是 - JAXB不需要它。替代方法是使用 JAXBElement 包装器对象,它提供与 @XmlRootElement 相同的信息,但是以一个对象,而不是一个注释。

The annotation is just a convenience, however - JAXB does not require it. The alternative to is to use JAXBElement wrapper objects, which provide the same information as @XmlRootElement, but in the form of an object, rather than an annotation.

然而, JAXBElement 对象构造起来很难,因为你需要知道XML元素名称和命名空间,业务逻辑通常不会。

However, JAXBElement objects are awkward to construct, since you need to know the XML element name and namespace, which business logic usually doesn't.

值得庆幸的是,当XJC生成类模型时,它还会生成一个名为 ObjectFactory 的类。这部分是为了向后兼容JAXB v1,但它也是XJC放置生成的工厂方法的地方,这些方法在您自己的对象周围创建 JAXBElement 包装器。它为您处理XML名称和命名空间,因此您无需担心它。您只需要查看 ObjectFactory 方法(对于大型模式,可以有数百个)来查找所需的方法。

Thankfully, when XJC generates a class model, it also generates a class called ObjectFactory. This is partly there for backwards compatibility with JAXB v1, but it's also there as a place for XJC to put generated factory methods which create JAXBElement wrappers around your own objects. It handles the XML name and namespace for you, so you don't need to worry about it. You just need to look through the ObjectFactory methods (and for large schema, there can be hundreds of them) to find the one you need.

这篇关于没有由JAXB生成的@XmlRootElement的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆