Reputation: 1916
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?
Upvotes: 2
Views: 2077
Reputation: 149047
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.
Upvotes: 2