2

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?

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

6 Comments

I have a ValidationEventHandler but how can I set it so JAXB doesn't crash when parsing this xml?
@UrielArvizu - JAXB will only error out for events that you return false for i the event handler.
so I should return true if the error is related to this issue? That way I can get the mapping done right?
I'm checking and the ValidationEventHandler's handleEvent method returning true solves my problem, but if I want to handle other errors, do I have to add an if statement to check if the error thrown was due to unexpected element?
also you mention by default JAXB shouldn't complain, but me getting this error means I'm not using it's default configuration?
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.