2017-08-29 36 views
0

解组XML时遇到以下是XML我收到在Java中

<?xml version="1.0" encoding="UTF-8" standalone="no"?> 
<soap-env:Envelope xmlns:soap-env="http://schemas.xmlsoap.org/soap/envelope/"> 
    <soap-env:Header/> 
    <soap-env:Body RequestId="1503948112779" Transaction="HotelResNotifRS"> 
     <OTA_HotelResNotifRS xmlns="http://www.opentravel.org/OTA/2003/05" TimeStamp="2017-08-28T19:21:54+00:00" Version="1.003"> 
      <Errors> 
       <Error Code="450" Language="en-us" ShortText="Unable to process " Status="NotProcessed" Type="3">Discrepancy between ResGuests and GuestCounts</Error> 
      </Errors> 
     </OTA_HotelResNotifRS> 
    </soap-env:Body> 
</soap-env:Envelope> 

这得到伪解组到OTAHotelResNotifRS对象,你可以得到.getErrors()上。问题是没有与此位关联的类型,所以它作为ElementNSImpl形式的对象返回。我不控制OTAHotelResNotifRS对象,所以我最好的选择是将.getErrors()对象解组为我自己的pojo。这是我的尝试。

@XmlRootElement(name = "Errors") 
@XmlAccessorType(XmlAccessType.FIELD) 
public class CustomErrorsType { 
    @XmlAnyElement(lax = true) 
    private String[] errors; 

    public String[] getErrors() { 
     return errors; 
    } 
} 

这是所使用的代码,试图将它解组到我CustomErrorsType对象

Object errorsType = otaHotelResNotifRS.getErrors(); 
JAXBContext context = JAXBContext.newInstance(CustomErrorsType.class); 
Unmarshaller unmarshaller = context.createUnmarshaller(); 
CustomErrorsType customErrorsType = (CustomErrorsType)unmarshaller.unmarshal((Node)errorsType); 

调用解组

javax.xml.bind.UnmarshalException: unexpected element (uri:"http://www.opentravel.org/OTA/2003/05", local:"Errors"). Expected elements are <{}Errors> 

有什么想法时,它抛出以下异常?对于xml解组来说,我非常虚弱。

回答

1

您正在忽略响应中的XML名称空间,如xmlns属性中所定义。请参阅https://www.w3.org/TR/xml-names/了解命名空间和定义它们的属性的完整说明。

标准符号,描述了使用它的命名空间的XML名称是{命名空间URI}本地名。所以这个例外就是告诉你,你的CustomErrorsType需要一个名称为Errors的元素和一个空的名称空间({}),但是它却遇到了一个名称为Errors和名称空间为http://www.opentravel.org/OTA/2003/05的元素。

尝试修改此:

@XmlRootElement(name = "Errors") 

这样:

@XmlRootElement(name = "Errors", namespace = "http://www.opentravel.org/OTA/2003/05") 

作为一个侧面说明,如果你有机会到它定义了SOAP服务的WSDL,你可以让你的任务相当容易通过调用标准的JDK工具wsimport并将WSDL的位置作为参数。所有编组将隐式地由生成的Service和Port类关注。

+0

这样做。谢谢! – Aubanis