I’m wondering if it’s possible to annotate my classes so that the first time the marshaller encounters an object, it generates an XML element of the appropriate type, but any subsequent reference to this object by anything else will have an XML IDREF entry created?
Share
You can leverage the concept of JAXB’s
XmlAdapterto do something like the following:input.xml
The following is the XML document I will use for this example. The 3rd
phone-numberentry is a reference to the 1stphone-numberentry, and the 5thphone-numberentry is a reference to the 4th.:Customer
The customer class maintains a collection of
PhoneNumberobjects. The same instance of PhoneNumber may appear multiple times in the collection.PhoneNumber
This is a class that can either appear in the document itself or as a reference. This will be handled using an
XmlAdapter. An XmlAdapter is configured using the@XmlJavaTypeAdapterannotation. Since we have specified this adapter at the type/class level it will apply to all properties referencing thePhoneNumberclass:WorkPhoneNumber
Based on your comment I have added a subclass of
PhoneNumber.PhoneNumberAdapter
Below is the implementation of the
XmlAdapter. Note that we must maintain if the PhoneNumber object has been seen before. If it has we only populate theidportion of theAdaptedPhoneNumberobject.Demo
To ensure the same instance of the
XmlAdapteris used for the entiremarshalandunmarshaloperations we must specifically set an instance of the XmlAdapter on both theMarshallerandUnmarshaller:Output
For More Information