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.
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.
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.
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.
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.
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));
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".
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With