无法解组xml文件
问题描述:
在我的项目中,我通过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());
}
}
能否请您提供有用的信息来解决它。
答
为什么你得到一个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);
更多信息