2017-08-29 40 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