1

我需要使用 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> 
4

2 回答 2

1

您可以@XmlElementDecl在带有注释的类上使用@XmlResistry(通常ObjectFactory用于此用例)

于 2013-09-12T14:48:13.257 回答
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();
}
}
于 2013-09-13T11:23:09.353 回答