【发布时间】:2014-12-22 09:45:43
【问题描述】:
我将使用以下类来解组适当的 XML 文档:
@XmlRootElement(name = "address")
public class AddressObject {
@XmlElement(name = "domain")
public String domain = new String();
@XmlElement(name = "ip-address")
public String ipAddress = new String();
@XmlElement(name = "user-agent")
public String userAgent = new String();
}
为了解组文件,我使用javax.xml.bind.Unmarshaller。使用以下代码:
JAXBContext context = JAXBContext.newInstance(AddressObject.class);
Unmarshaller unmarshaller = context.createUnmarshaller();
StreamSource streamSource = new StreamSource(new StringReader(SOME_CORRECT_XML_DOC));
JAXBElement<AddressObject> obj = unmarshaller.unmarshal(streamSource, AddressObject.class);
只要使用不正确的xml,它就可以正常工作,如下所示:
<?xml version="1.0" encoding="UTF-8" standalone="no"?><hello-world></hello-world>
在最后一种情况下,xml 解组没有任何错误。
有人可以解释为什么会这样吗?我预计会收到有关无效标签或类似内容的任何错误。
【问题讨论】:
-
我认为这是因为默认情况下 JAXB 将公共字段和属性视为已映射。如果您注释一个字段,则它会将该字段和属性视为已映射,从而导致冲突。如果没有
@XmlAccessorType(XmlAccessType.FIELD),您应该注释get 或set 方法。 更多信息 - blog.bdoughan.com/2011/06/using-jaxbs-xmlaccessortype-to.html
标签: java jaxb unmarshalling