问题描述
我正在使用 Java 6、JaxB 2 和 SpringSource Tool Suite(与 Eclipse 相同).我编写了几个 Java 类,我使用 JaxB 从中生成 XML 模式.但是,我注意到为了使用 JaxB 从 Java 对象生成 XML 文档的能力,我需要一个 ObjectFactory.
I'm using Java 6, JaxB 2 and SpringSource Tool Suite (same as Eclipse). I had a couple of Java classes I wrote, from which I used JaxB to generate an XML schema. However, I'm noticing in order to use JaxB's ability to generate an XML document from Java objects, I need an ObjectFactory.
final Marshaller marshaller = jaxbContext.createMarshaller(); // Here is where I don't have an ObjectFactory defined final JAXBElement<WebLeads> webLeadsElement = (new ObjectFactory()).createWebLeads(webLeadsJavaObj);
如何在不破坏我现在已有的类的情况下生成 ObjectFactory?
How can I generate an ObjectFactory without blowing away the classes I already have now?
推荐答案
更新
这个问题可能是指ObjectFactory在创建JAXBContext中的作用.如果您在上下文路径上引导 JAXBContext,那么它将检查该位置中的 ObjectFactory 以确定该包中的类:
This question may be referring to the role of ObjectFactory in creating a JAXBContext. If you bootstrap a JAXBContext on a context path then it will check for an ObjectFactory in that location in order to determine the classes in that package:
- http://bdoughan.blogspot.com/2010/09/processing-atom-feeds-with-jaxb.html
如果您没有 ObjectFactory 但仍希望在上下文路径上创建 JAXBContext 您可以包含一个名为 jaxb.in??dex 在该包中列出要包含在 JAXBContext 中的文件(引用的类将自动拉入):
If you do not have an ObjectFactory but still wish to create you JAXBContext on a context path you can include a file called jaxb.index in that package listing files to be included in the JAXBContext (referenced classes will automatically pulled in):
- http://bdoughan.blogspot.com/2010/08/using-xmlanyelement-to-build-generic.html
或者,您可以在类数组而不是上下文路径上引导您的 JAXBContext:
Alternatively you can bootstrap you JAXBContext on an array of classes instead of a context path:
- http://bdoughan.blogspot.com/2010/11/jaxb-and-inheritance-using-xsitype.html
是否需要 ObjectFactory
ObjectFactory 不是必需的,尽管即使从 Java 类开始,也有一些用例可以利用带有 @XmlRegistry 以便使用 @XmlElementDecl 注释.
An ObjectFactory is not required, although even when starting from Java classes there are use cases where you can leverage a similar class annotated with @XmlRegistry in order to use the @XmlElementDecl annotation.
创建 JAXBElement 的实例
您始终可以直接创建 JAXBElement:
You can always create the JAXBElement directly:
final JAXBElement<WebLeads> webLeadsElement = new JAXBElement<WebLeads>( new QName("root-element-name"), WebLeads.class, webLeadsJavaObj);
JAXBElement 的替代品
或者由于 JAXBElement 仅用于提供根元素信息,您可以使用 @XmlRootElement 注释您的 WebLeads 类:
Or since JAXBElement is simply used to provide root element information, you can annotate your WebLeads class with @XmlRootElement:
@XmlRootElement(name="root-element-name") public class WebLeads { ... }