JAXB marshaling: how to include exceptions info into xml output file?
I have a very basic application that uses JAXB marshaller to validate input information against an xsd schema. I register a validation event handler to obtain information about the exceptions. What I would like to achieve is the ability to include this information into xml output structure I receive as a result of marshaling. I’ve included excepti开发者_运维百科on collection section into my xsd and now I can instantiate the corresponding exception object once an exception is encountered. The question is how do I attach this object to the rest of my JAXB generated Java objects structure considering the fact that marshaling process had already started? Is it even possible? Or should I try and modify the xml result after the marshaling is done? Any advice would be highly appreciated. Thanks!
There a couple of ways to do this:
Option #1 - Add an "exceptions" Property to You Root Object
- Ensure that the exceptions property is marshalled last, this can be configured using propOrder on the @XmlType annotation.
- Create a validation handler that holds onto the root object.
- When the validation handler encounters an exception, add that exception to the exceptions property on the root object.
Option #2 - Use an XMLStreamWriter
- Create an XMLStreamWriter
- Write out a root element
- Set the validation handler on the marshaller, ensure that it will store the exceptions encountered.
- Marshal the root object to the XMLStreamWriter.
- Marshal the individual exceptions encountered to the XMLStreamWriter.
- Write out the close for the root element.
Short answer: no. JAXB is intended to take an object graph and produce XML. it's not intended to do this.
Longer answer: You could inject the exception representation into the graph after JAXB is done the first time.
Even longer answer: There are a number of plugin and customization technologies for JAX-B, and it's possible that you could use one of them. However, it's very hard to conceptualize this at the abstract level of your question.
精彩评论