如何解决如何确定不良模式?
我正在编写一个小应用程序,以根据存储在文件夹中的已知良好架构文件的“库”来验证“候选”xml 文件...
事实证明,已知的良好模式文件本身会引发问题!
我将架构文件(21 个文件,我很确定这些架构中的大多数不仅引用自身,而且其中一些还使用文件夹中的其他架构)加载到我的“架构空间”中的方式:>
// Load schemas into schema space:
Schema mySchema;
try {
SchemaFactory mySchemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
mySchemaFactory.setResourceResolver(new ResourceResolver(pathToSchemasFolder));
mySchema = mySchemaFactory.newSchema(primeAllSchemaDocsFromFolder(pathToSchemasFolder));
System.out.println("Schemas loaded");
} catch (SAXException e) {
throw new RuntimeException("Schema loading Failed: " + e);
}
我得到:
Exception in thread "main" java.lang.RuntimeException: Schema loading Failed: org.xml.sax.SAXParseException; lineNumber: 232; columnNumber: 5; s4s-elt-chara...
- 注意它给了我行号和列号但没有文件名...
我在验证时已经在使用自定义 XsdErrorHandler()
:
// Validate xml file within schema space:
try {
Validator validator = mySchema.newValidator();
validator.setErrorHandler(new XsdErrorHandler());
validator.validate(getSingleXmlFileStreamSource(pathToXmlCandidateFile));
System.out.println("Validation is successful");
但是,在调试时,我发现它没有被调用......这是有道理的,因为失败的部分是加载模式,在我将 ErrorHandler 设置为验证器之前完成的一些事情......
我想知道是否有办法为架构加载过程设置错误处理程序?
或者您可以与我分享任何其他技术来查找违规模式的名称? (例如:将架构文件增量添加到架构空间中,每次测试架构空间是否有效 - 没有任何无效的架构定义)
解决方法
有一个方法 SchemaFactory.setErrorHandler() 允许您在架构编译期间拦截错误。
,当您生成 StreamSource
时,您应该提供一个 publicId
属性。此属性不会影响解析,但会在异常中提供有用的信息:
* <p>The public identifier is always optional: if the application
* writer includes one,it will be provided as part of the
* location information.</p>
如果您将架构文件名用作 publicId
,您将能够从 SAXParseException 中检索它。
来自原始提问者的编辑: 由于我在 newSchema() 中使用 Source[],我可以为每个 Source 准备输入以包含提到的方法,如下所示:
Source[] sourceArray = new Source[numberOfSchemaFiles];
for (int i=0; i<numberOfSchemaFiles ; i++) {
String currentFileName = schemaFiles[i].getName();
try {
StreamSource currentStreamSource = new StreamSource(
new FileInputStream(directoryPath + currentFileName)
);
currentStreamSource.setPublicId(currentFileName);
sourceArray[i] = currentStreamSource;
} catch (FileNotFoundException e) {
throw new RuntimeException("Cannot find file: " + directoryPath + currentFileName);
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。