Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to ignore Unexpected element situation in JAXB?

Tags:

xml

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.

like image 390
João Avatar asked Dec 12 '08 11:12

João


People also ask

Is JAXB context thread safe?

JAXBContext is thread safe and should only be created once and reused to avoid the cost of initializing the metadata multiple times. Marshaller and Unmarshaller are not thread safe, but are lightweight to create and could be created per operation.

What is the use of @XmlElement?

A JavaBean property, when annotated with @XmlElement annotation is mapped to a local element in the XML Schema complex type to which the containing class is mapped. Example 2: Map a field to a nillable element. Example 3: Map a field to a nillable, required element.

What is @XmlRootElement?

Annotation Type XmlRootElementMaps a class or an enum type to an XML element. Usage. The @XmlRootElement annotation can be used with the following program elements: a top level class. an enum type.

What is JAXB marshal?

JAXB stands for Java Architecture for XML Binding. It provides mechanism to marshal (write) java objects into XML and unmarshal (read) XML into object. Simply, you can say it is used to convert java object into xml and vice-versa.


2 Answers

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));
like image 123
João Avatar answered Oct 02 '22 15:10

João


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".

like image 31
Jason Avatar answered Oct 02 '22 16:10

Jason