JAXB有多个可能的根元素

时间:2013-09-12 14:35:49

标签: xml jaxb

我需要使用JAXB绑定XML响应。但是,有两种可能的响应,无论是成功XML还是错误XML。所以,我需要一种方法来接收任何一种。以下是两个示例XML文件。我很感激,如果有人能帮我这个。我一直在寻找如何实现良好的解决方案!谢谢!

成功回应:

<?xml version="1.0" encoding="UTF-8"?>
<ResponseEnvioComandoSpy>
<comandoSpy>
<id>5</id>
<status>4</status>
<erro>0</erro>
</comandoSpy>
</ResponseEnvioComandoSpy>

错误回复

<ErrorRequest>
<codigo>14</codigo>
<erro>Nenhum comando/macro a ser enviada, favor verificar as tags xml.</erro>
<request>EnvioComando</request>
</ErrorRequest> 

2 个答案:

答案 0 :(得分:1)

您可以在使用@XmlElementDecl注释的类上使用@XmlResistry(对于此用例,通常为ObjectFactory

答案 1 :(得分:0)

非常感谢Blaise的教程http://blog.bdoughan.com/2012/07/jaxb-and-root-elements.html我设法解决了我的问题。解决方案是使用两个xml的类来实现对象工厂。下面是代码。

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();
}
}