2012-03-02 66 views
7

我已经使用.xsd文件生成Java类,并且使用XML文件,我需要解组。JAXB Unmarshall异常 - 意外的元素

我使用这个代码:

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) 

我见过很多的解决方案,但没有在我的项目工作。

我可以尝试做什么?

+0

您可以向我们展示test.xml'的'内容开始。 – skaffman 2012-03-02 11:21:29

+0

和xsd文件。 – 2012-03-03 13:17:28

回答

16

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

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

namespace =“”对我至关重要 – dirkoneill 2013-12-11 20:37:10

+0

您的意思是更改自动生成的Java类并将此注释添加到它? – Line 2017-06-01 08:52:49

+0

如果需要更改生成的代码,为什么不..我的意思是它可能是越野车... – 2017-07-26 23:13:23

4

尝试

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

我可以使用它与XML字符串? – Line 2017-06-01 09:00:23

+1

@Line StreamSource只接受InputStream,Reader和File源。但是你可以使用'StringReader'来插入你的XML字符串。 'StreamSource streamSource = new StreamSource(new StringReader(xmlText));' – Stroboskop 2017-06-26 15:08:35