Tha*_*ham 12 java xsd jaxb xml-validation
所以当我使用XML模式验证XML文件时,我只能知道它是失败还是通过,如果我想知道它为什么失败,我需要查看错误消息,如
[org.xml.sax.SAXParseException: cvc-complex-type.2.4.a: Invalid content was found starting with element 'City'. One of '{Address1}' is expected.]
Run Code Online (Sandbox Code Playgroud)
在上面的示例中,它失败,因为我缺少标记Address1.我的问题是当验证失败时,我能知道导致失败的标签吗?这是因为我需要为每个重要的缺失标记处理不同的故障.现在我的想法是
FileInputStream inputStream = null;
try{
SchemaFactory sf = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
Schema schema = sf.newSchema(new File(config.getXmlSchema()));
JAXBContext context = JAXBContext.newInstance(PackageLabel.class);
Unmarshaller unmarshaller = context.createUnmarshaller();
unmarshaller.setSchema(schema);
inputStream = new FileInputStream(xmlFile);
pl = (PackageLabel) unmarshaller.unmarshal(inputStream);
} catch (JAXBException e) {
if(pl.getAddress1() == null){
System.out.println("Invalid Mailing Address");
}
//EDIT: CANNOT DO THIS, SINCE pl IS NULL AT THIS POINT
//Some more logics on how to handle important missing-tags
...
}finally{
if(inputStream != null) inputStream.close();
}
Run Code Online (Sandbox Code Playgroud)
但是,我不认为内部写入逻辑catch clause是正确的.有什么建议?
编辑
我遵循了Balaise的想法,下面是我在XML缺少Address1时收到的事件
EVENT
SEVERITY: 2
MESSAGE: cvc-complex-type.2.4.a: Invalid content was found starting with element 'City'. One of '{Address1}' is expected.
LINKED EXCEPTION: org.xml.sax.SAXParseException: cvc-complex-type.2.4.a: Invalid content was found starting with element 'City'. One of '{Address1}' is expected.
LOCATOR
LINE NUMBER: 4
COLUMN NUMBER: 11
OFFSET: -1
OBJECT: null
NODE: null
URL: null
Run Code Online (Sandbox Code Playgroud)
然而,无论是NODE和OBJECT是空的,我不能再对什么产生例外,除非我解析异常这是我原来问调查.
你可以利用JAXB ValidationEventHandler.然后可以在Marshaller和的实例上设置实现Unmarshaller:
package blog.jaxb.validation;
import javax.xml.bind.ValidationEvent;
import javax.xml.bind.ValidationEventHandler;
public class MyValidationEventHandler implements ValidationEventHandler {
public boolean handleEvent(ValidationEvent event) {
System.out.println("\nEVENT");
System.out.println("SEVERITY: " + event.getSeverity());
System.out.println("MESSAGE: " + event.getMessage());
System.out.println("LINKED EXCEPTION: " + event.getLinkedException());
System.out.println("LOCATOR");
System.out.println(" LINE NUMBER: " + event.getLocator().getLineNumber());
System.out.println(" COLUMN NUMBER: " + event.getLocator().getColumnNumber());
System.out.println(" OFFSET: " + event.getLocator().getOffset());
System.out.println(" OBJECT: " + event.getLocator().getObject());
System.out.println(" NODE: " + event.getLocator().getNode());
System.out.println(" URL: " + event.getLocator().getURL());
return true;
}
}
Run Code Online (Sandbox Code Playgroud)
欲获得更多信息
| 归档时间: |
|
| 查看次数: |
6818 次 |
| 最近记录: |