How to ignore elements/attributes in XML when mapping to objects using JAXB?

I'm working with mapping XML strings into POJOs and viceversa using JAXB 2.0, and I want to be able to determine the elements in a XML that should be mapped into my annotated POJO classes.

Let's say I have the following XML:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<customer id="1">
    <firstName>Peter</firstName>
    <lastName>Parker</lastName>
    <socialSecurityNumber>112233445566</socialSecurityNumber>
</customer>

And I want to map it to a class that ommits the socialSecurityNumber element:

@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;
    }
}

If I try to unmarshall this I get the error:

unexpected element (uri:"", local:"socialSecurityNumber"). Expected elements are <{}lastName>

Is it possible to ignore elements/attributes from a XML that aren't present in my POJO classes?


By default JAXB shouldn't be complaining about the extra element. However you can specify an instance of ValidationEventHandler on the unmarshall to get the behaviour you are looking for.

链接地址: http://www.djcxy.com/p/62968.html

上一篇: 当Jaxb解组时,希望未知属性出错

下一篇: 如何在使用JAXB映射到对象时忽略XML中的元素/属性?