Jaxb:我如何生成ObjectFactory类? [英] Jaxb: How do I generate ObjectFactory class?
问题描述
我正在使用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.index
的文件,在该软件包中列出要包含在 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类开始也有用例可以利用 <$注释的类似类c $ c> @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实例
您始终可以创建e 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 {
...
}
这篇关于Jaxb:我如何生成ObjectFactory类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!