首页 文章

无法使用 JAXB 类解组 XML 响应

提问于
浏览
1

例外:

javax.xml.bind.UnmarshalException:意外元素(uri:“http://www.cleartrip.com/hotel/hotel-search-response”,local:“hotel-search-response”)。预期要素是(无)


MyTestFile.txt(XML):

<hotel-search-response xmlns="http://www.cleartrip.com/hotel/hotel-search-response" xmlns:hotel-info="http://www.cleartrip.com/places/hotel-info" xmlns:common="http://www.cleartrip.com/hotel/common">
<search-criteria>
    <booking-date>2018-12-12+05:30</booking-date>
    <check-in-date>2018-12-14+05:30</check-in-date>
    <check-out-date>2018-12-16+05:30</check-out-date>
    <number-of-rooms>1</number-of-rooms>
    <number-of-nights>2</number-of-nights>
    <number-of-room-nights>2</number-of-room-nights>
    <city>Bangalore</city>
    <country>IN</country>
</search-criteria>
<currency>INR</currency>

JAXB 类:

@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "hotel-search-response", propOrder = {
"searchCriteria",
"additionalCurrency",
"currency",
"baseUrl",
"hotels",
"pgfeeJson",
"pgchargeJson"
})
public class HotelSearchResponse {

@XmlElement(name = "search-criteria", required = false)
protected SearchCriteria searchCriteria;
@XmlElement(name = "additional-currency",required= false)
protected AdditionalCurrency additionalCurrency;
@XmlElement(required = false)
protected String currency;
@XmlElement(name = "base-url", required = false)
protected String baseUrl;
@XmlElement(required = false)
protected Hotels hotels;
@XmlElement(name = "pgfee-json", required = false)
protected String pgfeeJson;
@XmlElement(name = "pgcharge-json", required = false)
protected String pgchargeJson;
}

Java 主类:

JAXBContext jc= JAXBContext.newInstance(HotelSearchResponse.class);
        javax.xml.bind.Unmarshaller ums = jc.createUnmarshaller();
        HotelSearchResponse emp=(HotelSearchResponse) ums.unmarshal(new    File("E:/MyTestFile.txt"));

1 回答

  • 0

    首先,你需要一个@XmlRootElement。其次,您需要指定命名空间(因为您使用命名空间)。

    @XmlRootElement(name = "hotel-search-response", namespace = "http://www.cleartrip.com/hotel/hotel-search-response")
    @XmlAccessorType(XmlAccessType.FIELD)
    @XmlType(name = "hotel-search-response", propOrder = { "currency", "baseUrl",
    "pgfeeJson", "pgchargeJson" }, namespace = "http://www.cleartrip.com/hotel/hotel-search-response")
    public class HotelSearchResponse
    

    上面,propOrder被简化了。

相关问题