使用 JAXB 映射到对象时如何忽略 XML 中的 elements/attributes?
How to ignore elements/attributes in XML when mapping to objects using JAXB?
我正在使用 JAXB 2.0 将 XML 字符串映射到 POJO 中,反之亦然,我希望能够确定 XML 中应该映射到我带注释的 POJO 中的元素classes.
假设我有以下 XML:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<customer id="1">
<firstName>Peter</firstName>
<lastName>Parker</lastName>
<socialSecurityNumber>112233445566</socialSecurityNumber>
</customer>
我想将它映射到一个省略了 socialSecurityNumber 元素的 class:
@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;
}
}
如果我尝试解组它,我会收到错误消息:
unexpected element (uri:"", local:"socialSecurityNumber"). Expected elements are <{}lastName>
是否可以从我的 POJO classes 中不存在的 XML 中忽略 elements/attributes?
默认情况下,JAXB 不应抱怨额外的元素。但是,您可以在解组上指定 ValidationEventHandler
的实例以获得您正在寻找的行为。
我正在使用 JAXB 2.0 将 XML 字符串映射到 POJO 中,反之亦然,我希望能够确定 XML 中应该映射到我带注释的 POJO 中的元素classes.
假设我有以下 XML:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<customer id="1">
<firstName>Peter</firstName>
<lastName>Parker</lastName>
<socialSecurityNumber>112233445566</socialSecurityNumber>
</customer>
我想将它映射到一个省略了 socialSecurityNumber 元素的 class:
@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;
}
}
如果我尝试解组它,我会收到错误消息:
unexpected element (uri:"", local:"socialSecurityNumber"). Expected elements are <{}lastName>
是否可以从我的 POJO classes 中不存在的 XML 中忽略 elements/attributes?
默认情况下,JAXB 不应抱怨额外的元素。但是,您可以在解组上指定 ValidationEventHandler
的实例以获得您正在寻找的行为。