我使用.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)
我见过很多解决方案,但在我的项目中没有任何效果。
我可以尝试做什么?
答案 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);