Insert additional fields in JAXB marshalling

北城以北 提交于 2019-12-23 02:39:00

问题


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:


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.

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

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.

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

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.




回答2:


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.



来源:https://stackoverflow.com/questions/4307430/insert-additional-fields-in-jaxb-marshalling

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!