在 JAXB 编组中插入附加字段

发布于 2024-10-05 19:14:20 字数 107 浏览 0 评论 0原文

将某些对象编组到 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

红衣飘飘貌似仙 2024-10-12 19:14:20

有几种可能的方法:

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.

江南月 2024-10-12 19:14:20

我能想到的最简单的方法是使用 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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文