Insert additional fields in JAXB marshalling

2019-05-31 01:33发布

问题:

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.