How do I redirect a JAXB object to a different schema?
I have parsed the XML that comes in a specific format, eg.
<root>
<a/>
<b/>
<c>
<x/>
</c>
<d/>
</root>
After playing with the Java object, I want to send it to another service using a different schema like
<anotherRoot>
<a/>
<x/>
<something>
<d/>
</something>
</anotherRoot>
Can this be done "easily" with JAXB?
source to share
Using any JAXB implementation (JSR-222) , you can use XSLT on JAXBSource
and javax.xml.transform
API to create a secondary XML structure:
JAXBContext jc = JAXBContext.newInstance(Foo.class);
// Output XML conforming to first XML Schema
Marshaller marshaller = jc.createMarshaller();
marshaller.marshal(foo, System.out);
// Create Transformer on Style Sheet that converts XML to
// conform the second XML Schema
TransformerFactory tf = TransformerFactory.newInstance();
StreamSource xslt = new StreamSource(
"src/example/stylesheet.xsl");
Transformer transformer = tf.newTransformer(xslt);
// Source
JAXBSource source = new JAXBSource(jc, foo);
// Result
StreamResult result = new StreamResult(System.out);
// Transform
transformer.transform(source, result);
Complete example
source to share
You can create a proxy for another service and treat its beans as simple data transfer objects.
So when you want to invoke a service, you manually populate the beans based on the values of your appropriate model objects (the one you are playing with, the ones that contain the business logic) and invoke the service using the beans.
If there is a change to the service interface, you can recreate the proxy and the compiler will help you fix that conversion.
source to share