2012-07-25 93 views
2

參考我的previous post。我有以下代碼正在從文件中讀取XML。無法理解JAXB解組行爲

logger.log(Level.INFO, "testSchemaChange"); 
JAXBContext jaxbContext = JAXBContext.newInstance("com.store.web.ws.v1.model"); 
Unmarshaller unmarshaller = jaxbContext.createUnmarshaller(); 
JAXBElement<BookType> jeBookType = (JAXBElement<BookType>) unmarshaller.unmarshal(new File (BOOK_XML)); 

BookType bookType = jeBookType.getValue(); 
logger.log(Level.INFO, "Book recieved: " + bookType.getISBN()); 

我播種與Book的XML作爲我的根元素,而不是BookList。這個例子工作正常,只要我保留在JAXBContext.newInstance中的包的完整路徑。

沒有快,我更換

JAXBContext jaxbContext = JAXBContext.newInstance("com.store.web.ws.v1.model");

JAXBContext jaxbContext = JAXBContext.newInstance(BookType.class);

我開始變得異常SEVERE: unexpected element (uri:"", local:"book"). Expected elements are (none)

有人能解釋爲什麼是這種行爲?

PS: 爲方便起見,我的測試類和JAXB生成的類在同一個包即com.store.web.ws.v1.model

回答

3

你所看到的問題是,因爲JAXBContext不知道你ObjectFactory類包含@XmlElementDecl註釋爲book元素。

當您在包名稱上創建JAXBContext時,它將自動拉入ObjectFactory類。如果在類上創建JAXContext,則需要明確包含@XmlRegistry註釋(本例中爲ObjectFactory)的類。