【问题标题】:JAXB Unmarshall exception - unexpected elementJAXB Unmarshal 异常 - 意外元素
【发布时间】:2012-03-20 21:43:16
【问题描述】:

我使用 .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的内容。

标签: exception jaxb unmarshalling


【解决方案1】:

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

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

【讨论】:

  • namespace="" 对我来说很重要
  • 你的意思是改变自动生成的Java类并添加这个注解?
  • 如果需要更改生成的代码,为什么不...我的意思是它可能是错误的...
【解决方案2】:

试试

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

【讨论】:

  • 我可以将它与 XML 字符串一起使用吗?
  • @Line StreamSource 只接受 InputStream、Reader 和 File 源。但是您可以使用StringReader 插入您的XML 字符串。 StreamSource streamSource = new StreamSource(new StringReader(xmlText));
猜你喜欢
  • 1970-01-01
  • 2017-08-14
  • 1970-01-01
  • 1970-01-01
  • 2023-04-02
  • 1970-01-01
  • 2019-05-15
  • 1970-01-01
  • 2018-08-27
相关资源
最近更新 更多