我有一個unmarshaller以及一個MySchema.xsd文件。如何在進行反編組時對XML進行驗證?
StreamSource sources = new StreamSource(getClass().getClassLoader().getResourceAsStream("/xmlValidation.xsd"));
SchemaFactory sf = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
unmarshaller.setSchema(sf.newSchema(sources));
做出unmarshaller.setEventHandler()函數,調用指定自定義驗證事件處理程序,基本上是格式化錯誤提示字符串,通過:
final String errorString = new String();
unmarshaller.setEventHandler(new ValidationEventHandler() {
@Override
public boolean handleEvent(ValidationEvent validationevent) {
if(validationevent.getSeverity()!= ValidationEvent.WARNING){
errorString.format("Line:Col[" + validationevent.getLocator().getLineNumber()
+ ":" + validationevent.getLocator().getColumnNumber()
+ "]:" + validationevent.getMessage());
return false;
}
return true;
}
});
上面的代碼似乎工作確定(我可以得到java對象,當輸入字符串被驗證,並且錯誤提示字符串被格式化爲例外)
問題是,當輸入xml格式不正確時,它也會拋出一個SaxParseException。
在此先感謝。 安德魯
我搜索更多的,我必須使用javax.xml.validation.Validator中google.Seems,這可以從javax.xml創建.validation.Schema來驗證它。 (我不確定,但Iwill會在測試結束後返回)ValidationEventHandler是否也可以捕獲SaxParseException? – yzandrew 2011-03-23 03:57:50