如何使用JAXB从服务返回的’anyType’创建java对象?

Web服务返回由WSDL定义的对象:

 

当我打印出这个对象的类信息时,它出现为:

 class com.sun.org.apache.xerces.internal.dom.ElementNSImpl 

但我需要将此对象解组为以下类的对象:

 @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "", propOrder = { "info", "availability", "rateDetails", "reservation", "cancellation", "error" }) @XmlRootElement(name = "ArnResponse") public class ArnResponse { } 

我知道响应是正确的,因为我知道如何编组这个对象的XML:

 Marshaller m = jc.createMarshaller(); m.setProperty( Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE ); m.marshal(rootResponse, System.out); 

打印出来:

             

如何将我看到的ElementNSImpl对象转换为我知道它代表的ArnResponse对象?

此外,我正在AppEngine上运行,其中文件访问受到限制。

谢谢你的帮助

更新

我添加了@XmlAnyElement(lax=true)注释,如下所示:

  @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "", propOrder = { "content" }) @XmlSeeAlso(ArnResponse.class) public static class SubmitRequestDocResult { @XmlMixed @XmlAnyElement(lax = true) protected List content; 

但它没有任何区别。

这与内容是List的事实有关吗?

这是我从服务器获取内容后尝试访问内容的代码:

 List list = rootResponse.getSubmitRequestDocResult().getContent(); for (Object o : list) { ArnResponse response = (ArnResponse) o; System.out.println(response); } 

哪个有输出:

2012年1月31日上午10:04:14 com.districthp.core.server.ws.alliance.AllianceApi getRates SEVERE:com.sun.org.apache.xerces.internal.dom.ElementNSImpl无法强制转换为com.districthp.core .server.ws.alliance.response.ArnResponse

回答:

axtavt的回答就是诀窍。 这工作:

 Object content = ((List)result.getContent()).get(0); JAXBContext context = JAXBContext.newInstance(ArnResponse.class); Unmarshaller um = context.createUnmarshaller(); ArnResponse response = (ArnResponse)um.unmarshal((Node)content); System.out.println("response: " + response); 

您可以将该对象传递给Unmarshaller.unmarshal(Node) ,它应该能够解组它。

您可以使用@XmlAnyElement(lax=true) 。 这会将具有已知根元素( @XmlRootElement@XmlElementDecl )的XML转换为域对象。 有关示例,请参阅:

根据我在使用XML时发现的, anyType可以表示任何对象,因此最接近它的是java.lang.Object 。 (除了这个事实, anyType在技​​术上可能是一个安全漏洞,允许有人注入任何东西,包括恶意二进制文件到那个位置,并且没有任何东西会阻止它,因为你的架构允许它。)

最好更改架构以允许映射到自定义对象。 从编程角度,消费角度和安全角度来看,这都是更清洁的。

等待你不能这样做,我建议将类型存储为元素的属性。 您可能需要编写自定义代码然后帮助您将anyType转换回该对象,但至少您知道它的类型。

我的两美分来自我的经验(主要是在整合领域)。