如何忽略JAXB中的意外元素情况仍然得到所有其他类型的javax.xml.bind.UnmarshalException?
obj = unmler.unmarshal(new StringReader(xml))
注意我仍然想获得xml解析的obj结果.
解决方案.
在JAXB中实现ValidationEventHandler,如下所示:
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; } }
然后
Unmarshaller u = ...; u.setEventHandler(new CustomValidationEventHandler()); u.unmarshal(new StringReader(xml));