Reputation: 794
I need to bind an XML response using JAXB. however, there are two possible responses, either the success XML or error XML. So, I need a way to receive either one. Below are two sample XML files. I'd appreciate it, if anyone could help me with this. I've been looking everywhere how to do achieve to good solution! Thanks!!
Successful response:
<?xml version="1.0" encoding="UTF-8"?>
<ResponseEnvioComandoSpy>
<comandoSpy>
<id>5</id>
<status>4</status>
<erro>0</erro>
</comandoSpy>
</ResponseEnvioComandoSpy>
Error response
<ErrorRequest>
<codigo>14</codigo>
<erro>Nenhum comando/macro a ser enviada, favor verificar as tags xml.</erro>
<request>EnvioComando</request>
</ErrorRequest>
Upvotes: 1
Views: 2968
Reputation: 794
Well thanks to Blaise's tutorial http://blog.bdoughan.com/2012/07/jaxb-and-root-elements.html ive managed to solve my problem. The solution was to implement an object factory with the classes of both xml's. Heres the code below.
public static void main(String[] args) throws JAXBException, MalformedURLException, IOException {
RequestMensagemCB requestMensagemCB = new RequestMensagemCB();
XMLBinder xmlBinder = new XMLBinder();
InputStreamReader isr = Request.doPost(url, xmlBinder.marshaller(requestMensagemCB));
JAXBContext jc = JAXBContext.newInstance(ObjectFactory.class);
Unmarshaller unmarshaller = jc.createUnmarshaller();
Object object = (Object) unmarshaller.unmarshal(isr);
Marshaller marshaller = jc.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
marshaller.marshal(object, System.out);
}
@XmlRegistry
public class ObjectFactory {
public ObjectFactory() {
}
public ResponseMensagemCB createResponseMensagemCB() {
return new ResponseMensagemCB();
}
public ErrorRequest createErrorRequest() {
return new ErrorRequest();
}
}
Upvotes: 0
Reputation: 149047
You can use the @XmlElementDecl
on a class annotated with @XmlResistry
(usually ObjectFactory
for this use case)
Upvotes: 1