JAXB 是否可以首先通过包含进行封送,然后通过 @XmlIDREF 进行封送以供后续引用?
我想知道是否可以注释我的类,以便编组器第一次遇到对象时,它会生成适当类型的 XML 元素,但任何其他对该对象的后续引用都会创建一个 XML IDREF 条目?
I'm wondering if it's possible to annotate my classes so that the first time the marshaller encounters an object, it generates an XML element of the appropriate type, but any subsequent reference to this object by anything else will have an XML IDREF entry created?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以利用 JAXB 的
XmlAdapter
概念来执行如下操作:input.xml
下面是我将用于本示例的 XML 文档。第 3 个
phone-number
条目是对第 1 个phone-number
条目的引用,第 5 个phone-number
条目是对第四:Customer
客户类维护一个
PhoneNumber
对象的集合。 PhoneNumber 的同一实例可能会在集合中出现多次。PhoneNumber
这是一个可以出现在文档本身中或作为引用的类。这将使用
XmlAdapter
来处理。 XmlAdapter 使用@XmlJavaTypeAdapter
注释进行配置。由于我们已在类型/类级别指定了此适配器,因此它将应用于引用PhoneNumber
类的所有属性:WorkPhoneNumber
根据您的评论,我添加了
的子类>电话号码
。PhoneNumberAdapter
下面是
XmlAdapter
的实现。请注意,我们必须维护 PhoneNumber 对象以前是否已出现过。如果有,我们只填充AdaptedPhoneNumber
对象的id
部分。演示
为了确保
XmlAdapter
的同一实例用于整个marshal
和unmarshal
操作,我们必须专门设置Marshaller
和Unmarshaller
上的 XmlAdapter 实例:输出
了解更多信息
You can leverage the concept of JAXB's
XmlAdapter
to do something like the following:input.xml
The following is the XML document I will use for this example. The 3rd
phone-number
entry is a reference to the 1stphone-number
entry, and the 5thphone-number
entry is a reference to the 4th.:Customer
The customer class maintains a collection of
PhoneNumber
objects. The same instance of PhoneNumber may appear multiple times in the collection.PhoneNumber
This is a class that can either appear in the document itself or as a reference. This will be handled using an
XmlAdapter
. An XmlAdapter is configured using the@XmlJavaTypeAdapter
annotation. Since we have specified this adapter at the type/class level it will apply to all properties referencing thePhoneNumber
class:WorkPhoneNumber
Based on your comment I have added a subclass of
PhoneNumber
.PhoneNumberAdapter
Below is the implementation of the
XmlAdapter
. Note that we must maintain if the PhoneNumber object has been seen before. If it has we only populate theid
portion of theAdaptedPhoneNumber
object.Demo
To ensure the same instance of the
XmlAdapter
is used for the entiremarshal
andunmarshal
operations we must specifically set an instance of the XmlAdapter on both theMarshaller
andUnmarshaller
:Output
For More Information