João
João

Reputation: 2333

How to ignore Unexpected element situation in JAXB?

How can one ignore Unexpected element situation in JAXB ans still get all other kind of javax.xml.bind.UnmarshalException?

obj = unmler.unmarshal(new StringReader(xml))

Notice i still want to get the obj result of the xml parsing.

Upvotes: 12

Views: 22963

Answers (3)

Franziskus Karsunke
Franziskus Karsunke

Reputation: 5208

Use JAXB.unmarshal() which ignores unexpected elements by default. Be careful, since it will also skip schema validation.

JavaDoc: https://docs.oracle.com/javase/8/docs/api/javax/xml/bind/JAXB.html

Upvotes: 0

Jason
Jason

Reputation: 12333

Also, JAXB 2.0 automatically ignores unrecognized elements and continues the unmarshalling process. See https://jaxb.java.net/nonav/jaxb20-fcs/docs/api/javax/xml/bind/Unmarshaller.html and jump to "Validation and Well-Formedness".

Upvotes: 4

João
João

Reputation: 2333

The solution.

In JAXB implementing ValidationEventHandler like so:

class CustomValidationEventHandler implements ValidationEventHandler{

    public boolean handleEvent(ValidationEvent evt) {
        System.out.println("Event Info: "+evt);
        if(evt.getMessage().contains("Unexpected element"))
            return true;
        return false;
    }

}

Then

Unmarshaller u = ...;

u.setEventHandler(new CustomValidationEventHandler());

u.unmarshal(new StringReader(xml));

Upvotes: 14

Related Questions