无法使用JAXB类解组XML响应

时间:2018-12-12 08:52:00

标签: java jaxb unmarshalling

例外:

javax.xml.bind.UnmarshalException:意外元素(uri:“ http://www.cleartrip.com/hotel/hotel-search-response”,本地:“ 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 :(得分: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被简化。