我正在使用JAXB 2.0将XML字符串映射到POJO,反之亦然,我希望能够确定XML中应该映射到带注释的POJO类的元素。
我们说我有以下XML:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<customer id="1">
<firstName>Peter</firstName>
<lastName>Parker</lastName>
<socialSecurityNumber>112233445566</socialSecurityNumber>
</customer>
我想将它映射到省略socialSecurityNumber元素的类:
@XmlRootElement
public class Customer {
private Integer id;
private String firstName;
private String lastName;
public Customer() {
}
public Customer(Integer id, String firstName, String lastName) {
this.id = id;
this.firstName = firstName;
this.lastName = lastName;
}
@XmlAttribute
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
@XmlElement(nillable = true)
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
@XmlElement(nillable = true)
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
}
如果我试图解组,我会收到错误:
意外元素(uri:&#34;&#34;,local:&#34; socialSecurityNumber&#34;)。预期元素是&lt; {} lastName&gt;
是否可以忽略我的POJO类中不存在的XML中的元素/属性?
答案 0 :(得分:2)
默认情况下,JAXB不应该抱怨额外的元素。但是,您可以在unmarshall上指定ValidationEventHandler
的实例以获取您要查找的行为。