我花了很多时间在Spring中针对多个XML验证XSD。即使将所有XSD模式都提供给SchemaFactory,它也不起作用,因为主模式看不到在主XSD文件中声明的import schema。即使将这种模式作为文件提供,它也不起作用,因为Spring's资源文件无法解析为绝对的path

<xs:import namespace="http://test.com/types" schemaLocation="types.xsd"/>

最佳答案

1.首先,我们需要这个可以解析xsd模式的依赖项:

implementation("org.apache.ws.xmlschema:xmlschema-core:2.2.4")

2.我们创建2个bean。一个用于存储我们的XSD's(如果存在此schemaLocation="...",它将自动查找其他文件),另一个用于我们的Validator
    @Bean
    fun schema(): XsdSchemaCollection {
        return CommonsXsdSchemaCollection(
            ClassPathResource("xsd/main.xsd")
        ).also { it.setInline(true) }
    }

    @Bean
    fun myValidator(schema: XsdSchemaCollection): XmlValidator {
        return schema.createValidator()
    }

3.我们可以使用它:
    @Autowired
    private val myValidator: XmlValidator

    fun validate(data: String): Array<SAXParseException> {
        return myValidator.validate(StreamSource(data.byteInputStream()))
    }

Array<SAXParseException>将包含验证异常列表,如果有的话

09-16 06:58