如何确定不良模式?

问题描述

我正在编写一个小应用程序,以根据存储在文件夹中的已知良好架构文件的“库”来验证“候选”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);
        }

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...