在 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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
有几种可能的方法:
1。使用 XmlAdapter
您可以利用 JAXB 的 XmlAdapter。在这里,您将创建带有额外字段的类的版本(改编后的类可以扩展原始类)。然后在适配器中进行它们之间的转换。由于该类的替代版本将包含额外的字段,因此它将被整理出来。
2.使用 Binder
如果您编组目标是 DOM,那么您可以利用 JAXB 的 Binder。它旨在保存信息集,但在编组之后,它确实维护对象和 DOM 节点之间的链接。一旦编组完成,您就可以使用绑定器来查找对象的关联节点并更新它。
3.包装输出目标
如果您的输出目标类似于 ContentHandler 或 XMLStreamWriter,那么当达到适当的状态时,您可以触发在嵌套编组目标上调用的其他事件。
There are a few possible approaches:
1. Use an 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.
2. Use Binder
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.
3. Wrap the Output Target
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 编组到 DOM,然后以编程方式将额外信息插入到该 DOM 中,然后将 DOM 重新编组为 XML。
丑陋且效率低下,但这是我能想到的最好的。
The easiest way I can think of would be to use JAXB to marshal to a DOM, and then programmatically insert your extra information into that DOM, then re-marshal the DOM to XML.
Ugly and inefficient, but that's the best I can think of.