[英]JAXB Unmarshalling not working. Expected elements are (none)
我正在尝试解组XML。
这就是我的XML的样子
<DeviceInventory2Response xmlns="http://tempuri.org/">
<DeviceInventory2Result xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
<Obj123 xmlns="">
<Id>1</Id>
<Name>abc</Name>
</Obj123>
<Obj456 xmlns="">
.
.
.
我想在Obj123下获得Id和Name。 但是,当我运行我的unmarshal命令时,我收到以下错误。
An Error: javax.xml.bind.UnmarshalException: unexpected element (uri:"http://tempuri.org/", local:"DeviceInventory2Response"). Expected elements are (none)
我的代码在主类中看起来像这样:
Obj123 myObj123 = (Obj123) unmarshaller.unmarshal(inputSource);
而我的Obj123课程看起来像这样:
package com.myProj.pkg;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlElementWrapper;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;
@XmlRootElement(name="Obj123")
public class Obj123 {
private String Id;
private String Name;
public String getId() {
return Id;
}
public String getName() {
return Name;
}
}
我想通过设置我的XMLRootElement我应该能够跳过我的XML的前两行,但这似乎并没有发生。 有任何想法吗?
编辑:
这就是我的JAXB上下文的制作方式:
JAXBContext jaxbContext = JAXBContext.newInstance();
Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
Obj123 obj123 = (Obj123) unmarshaller.unmarshal(xmlStreamReader);
我通过添加解决了这个问题
@XmlRootElement(name="abc_xxx")
到Root类。
eclipse生成的JAXB类没有将此注释添加到我的根类。
JAXB实现将尝试匹配文档的根元素(而不是子元素)。 如果要解组到XML文档的中间,那么可以使用StAX解析文档,将XMLStreamReader
推进到所需的元素,然后解组。
欲获得更多信息
现在我收到以下错误。 错误:javax.xml.bind.UnmarshalException - 包含链接异常:[javax.xml.bind.UnmarshalException:unexpected element(uri:“”,local:“Obj123”)。 预期的元素是(无)]。
JAXBContext
只知道你告诉它的类。 代替:
JAXBContext jaxbContext = JAXBContext.newInstance();
你需要这样做:
JAXBContext jaxbContext = JAXBContext.newInstance(Obj123.class);
请改用ObjectFactory类
JAXBContext jaxbContext = null;
try {
jaxbContext = JAXBContext.newInstance(ObjectFactory.class);
} catch (JAXBException e) {
e.printStackTrace();
}
JAXBElement<ObjectFactory> applicationElement = null;
try {
applicationElement = (JAXBElement<ObjectFactory>)
unmarshaller.unmarshal(Thread.currentThread().getClass()
.getResourceAsStream(fileName));
} catch (JAXBException e) {
e.printStackTrace();
}
试试这个并解决上述问题。 我的问题已经解决了。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.