JAXB解组异常-意外的元素

7

我使用了一个.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)

我看过很多解决方案,但在我的项目中都没有起作用。

我可以尝试做什么?


您可以先展示一下 test.xml 文件的内容。 - skaffman
2个回答

16

您的 XML 根元素缺少命名空间(URI)属性。 最好在 XMLRootElement 上尝试此操作...

@XmlRootElement(name = "root", namespace="")

命名空间 namespace="" 对我来说非常关键。 - YoungDinosaur
你的意思是修改自动生成的Java类并添加这个注解吗? - Line
如果需要更改生成的代码,为什么不这样做呢?我的意思是它可能存在漏洞... - Waqas Memon

4

尝试

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

我可以将它与XML字符串一起使用吗? - Line
1
@Line StreamSource 只接受 InputStream、Reader 和 File 源。但是你可以使用 StringReader 将你的 XML 字符串插入其中。 StreamSource streamSource = new StreamSource(new StringReader(xmlText)); - Stroboskop

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接