开发者

Insert additional fields in JAXB marshalling

When mars开发者_如何学Pythonhaling 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?


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜