JAXB Unmarshal异常 - 意外元素

时间:2012-03-02 11:19:57

标签: exception jaxb unmarshalling

我使用.xsd文件生成Java类,并且使用XML文件,我需要解组。

我正在使用此代码:

JAXBContext objJAXBContext = JAXBContext.newInstance("my.test");

// create an Unmarshaller
Unmarshaller objUnmarshaller = objJAXBContext.createUnmarshaller();

FileInputStream fis = new FileInputStream("test.xml");

JAXBElement<Root> objMyRoot = (JAXBElement<Root>) objUnmarshaller.unmarshal(fis);

Root mRoot = objMyRoot.getValue();

我收到此错误:

javax.xml.bind.UnmarshalException: unexpected element (uri:"", local:"Root"). Expected elements are (none)

我见过很多解决方案,但在我的项目中没有任何效果。

我可以尝试做什么?

2 个答案:

答案 0 :(得分:16)

您的xml根目录缺少名称空间(uri)属性。 你最好在XMLRootElement ...

上试一试
@XmlRootElement(name = "root", namespace="")

答案 1 :(得分:4)

尝试

StreamSource streamSource = new StreamSource("test.xml")
JAXBElement<Root> objMyRoot = (JAXBElement<Root>) objUnmarshaller.unmarshal(streamsource, Root.class);