2012-08-22 55 views
1

在我的項目中,我通過JaxB對象生成了xml文件。現在我再次想要解除對象現在的JAXB對象。當我嘗試解組時拋出classcastException。無法解組xml文件

請找我寫的類:

public class ReservationTest1 { 

    public static void main(String []args) throws IOException, JAXBException 
    { 

     JAXBContext jaxbContext = JAXBContext.newInstance(com.hyatt.Jaxb.makeReservation.request.OTAHotelResRQ.class); 
     Unmarshaller unmarshaller = jaxbContext.createUnmarshaller(); 
     @SuppressWarnings("unchecked") 
     JAXBElement bookingElement = (JAXBElement) unmarshaller.unmarshal(
       new FileInputStream("D://myproject//Reservation.xml")); 


     System.out.println(bookingElement.getValue()); 

    } 
} 

能否請您提供有用的信息來解決它。

回答

1

爲什麼你得到一個ClassCastException

如果被解組的對象與@XmlRootElement註解,那麼你會得到繼承,而不是的JAXBElement實例的實例。

FileInputStream xml = new FileInputStream("D://myproject//Reservation.xml"); 
OTAHotelResRQ booking = (OTAHotelResRQ) unmarshaller.unmarshaller.unmarshal(xml); 

總是域對象

如果你總是希望得到您的域對象的實例,而不管域對象或JAXBElement是否是從您可以使用JAXBIntrospector解組操作返回。

FileInputStream xml = new FileInputStream("D://myproject//Reservation.xml"); 
Object result = unmarshaller.unmarshaller.unmarshal(xml); 
OTAHotelResRQ booking = (OTAHotelResRQ) JAXBIntrospector.getValue(result); 

總是得到的JAXBElement

如果你寧可永遠得到的JAXBElement一個實例可以使用的unmarshal方法,需要一個類參數之一。

StreamSource xml = new StreamSource("D://myproject//Reservation.xml"); 
JAXBElement<OTAHotelResRQ> bookingElement = 
    unmarshaller.unmarshal(xml, OTAHotelResRQ.class); 

更多信息