Search code examples
javaxmljaxb2

Unable to understand JAXB Unmarshalling behaviour


Reference to my previous post. I have following code which is reading XML from the file.

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());

I am seeding an XML with Book as my root element instead of BookList. This example is working fine as long as i keep the full path of the package in the JAXBContext.newInstance.

No sooner, did i change

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

to

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

I started getting exception SEVERE: unexpected element (uri:"", local:"book"). Expected elements are (none)

Can someone explain why is this behaviour ?

P.S: For sake of convenience my test class and JAXB generated classes are in same package i.e. com.store.web.ws.v1.model


Solution

  • The problem you are seeing is because the JAXBContext isn't aware of your ObjectFactory class that contains the @XmlElementDecl annotation for the book element.

    When you create a JAXBContext on a package name, the it will automatically pull in the ObjectFactory class. If you create a JAXContext on classes you need to explicitly include the class with the @XmlRegistry annotation (ObjectFactory in this case).