无法理解JAXB Unmarshalling行为 [英] Unable to understand JAXB Unmarshalling behaviour

查看:155
本文介绍了无法理解JAXB Unmarshalling行为的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

参考我的上一篇文章 。我有以下代码从文件中读取XML。

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

我正在使用预订播种XML我的根元素而不是 BookList 。只要我在 JAXBContext.newInstance 中保留包的完整路径,此示例就可以正常工作。

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.

我刚刚更改

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

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

我开始获得异常 SEVERE:意外元素(uri:,local:book)。预期的元素是(无)

有人可以解释为什么会出现这种情况?

Can someone explain why is this behaviour ?

PS:
为方便起见,我的测试类和JAXB生成的类在同一个包中,即 com.store.web.ws .v1.model

推荐答案

您看到的问题是因为 JAXBContext 不知道您的 ObjectFactory 类,其中包含 @XmlElementDecl 注释 book 元素。

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.

当您创建 JAXBContext 时一个包名,它会自动拉入 ObjectFactory 类。如果在类上创建 JAXContext ,则需要使用 @XmlRegistry 注释显式包含该类( ObjectFactory 在这种情况下)。

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).

这篇关于无法理解JAXB Unmarshalling行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆