being a newbie to Java XML binding i am facing a challenge.
Let say i have a scenario where my domain model is constructed and i want to marshall this domain to an xml structure.
Now i want to provide different unmarshall path’s:
- Marshall the whole object graph [no problem here]
- Marshall an objectgraph until a specific depth!!! [challenge]
I cannot figure out a good way on how to tackle this without introducing to much complexity. One can make a copy of the domain and manually later that, but that does not feel right. Any other solutions available?
You could leverage XmlAdapter and Marshal.Listener to get this behaviour:
Demo
A Marshal.Listener will be set to keep track of the depth of the tree we are marshalling. Also we will set runtime level XmlAdapters that are aware of the depth listener. These adapters will start returning null when the desired depth has been reached.
DepthListener
The purpose of this class is to to keep track of the current depth.
RootAdapter
The purpose of the XmlAdapter is to start returning null when the desired depth has been reached to stop the marshalling process.
Root
The following demonstrates how to specify the XmlAdapter on the domain object via the @XmlJavaTypeAdapter annotation:
Output
The following is the output from the demo code: