无法理解JAXB Unmarshalling行为
参考我以前的post 。 我有以下代码从文件中读取XML。
logger.log(Level.INFO, "testSchemaChange"); JAXBContext jaxbContext = JAXBContext.newInstance("com.store.web.ws.v1.model"); Unmarshaller unmarshaller = jaxbContext.createUnmarshaller(); JAXBElement jeBookType = (JAXBElement) unmarshaller.unmarshal(new File (BOOK_XML)); BookType bookType = jeBookType.getValue(); logger.log(Level.INFO, "Book recieved: " + bookType.getISBN());
我正在使用Book
作为我的根元素而不是BookList
来播种XML。 只要我在JAXBContext.newInstance
保留包的完整路径,此示例就可以正常工作。
不久,我改变了吗?
JAXBContext jaxbContext = JAXBContext.newInstance("com.store.web.ws.v1.model");
至
JAXBContext jaxbContext = JAXBContext.newInstance(BookType.class);
我开始得到exceptionSEVERE: unexpected element (uri:"", local:"book"). Expected elements are (none)
SEVERE: unexpected element (uri:"", local:"book"). Expected elements are (none)
有人可以解释为什么这种行为?
PS:为方便起见,我的测试类和JAXB生成的类在同一个包中,即com.store.web.ws.v1.model
您遇到的问题是因为JAXBContext
不知道您的ObjectFactory
类包含book
元素的@XmlElementDecl
注释。
当您在包名称上创建JAXBContext
时,它将自动拉入ObjectFactory
类。 如果在类上创建JAXContext
,则需要使用@XmlRegistry
注释显式包含该类(在本例中为ObjectFactory
)。