在JAXB编组中插入其他字段 [英] Insert additional fields in JAXB marshalling

查看:62
本文介绍了在JAXB编组中插入其他字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当将一些对象编组为XML时,我需要在每个生成的XML对象中插入一个额外的字段 - 一种标记。目的不是修改源对象,而是在输出XML中插入该信息。

When marshaling some objects into XML, I need to insert an additional field in each of the resulting XML objects - sort of flag. The purpose is not modifying the source objects but inserting that information in the output XML.

如果可能的话,是否有任何想法?

Any ideas if this is possible?

推荐答案

有几种可能的方法:

1。使用XmlAdapter

您可以利用JAXB的XmlAdapter。在这里,您将使用额外字段创建类的版本(适应的类可以扩展原始类)。然后在适配器中转换它们。由于该类的替代版本将包含额外字段,因此它将编组。

You could leverage JAXB's XmlAdapter. Here you would create a version of the classes with the extra field (the adapted classes could extend the original). Then convert between them in the adapter. Since the alternate version of the class would contain the extra field it would marshal out.

  • http://bdoughan.blogspot.com/2010/07/xmladapter-jaxbs-secret-weapon.html

2。使用Binder

如果你编组的目标是DOM,那么你可以利用JAXB的Binder。它用于信息集保存,但在编组之后它确实保持了对象和DOM节点之间的链接。编组完成后,您可以使用活页夹查找对象的关联节点并进行更新。

If you marshal target is DOM, then you could leverage JAXB's Binder. It is intended for infoset preservation, but after a marshal it does maintain a link between the objects and the DOM nodes. Once the marshal is complete you could use the binder to find an object's associated node and update it.

  • http://bdoughan.blogspot.com/2010/09/jaxb-xml-infoset-preservation.html

3。包装输出目标

如果您的输出目标类似于ContentHandler或XMLStreamWriter,那么当达到适当的状态时,您可以触发要调用的其他事件嵌套的元帅目标。

If your output target is something like a ContentHandler or XMLStreamWriter then when the appropriate state is reached you could trigger additional events to be called on the nested marshal target.

这篇关于在JAXB编组中插入其他字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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