简体   繁体   English

针对多个 XSD(存储为资源)验证 XML。 Spring 开机

[英]Validating XML against multiple XSD(stored as resources). Spring Boot

I've spend a lot of time to validate XML against multiple XSD in Spring.我花了很多时间针对XML中的多个XSD验证 XML。 Even when I give all XSD schemas to SchemaFactory it does not work because main schema can't see import schema declared in main XSD file.即使我将所有XSD模式都提供给 SchemaFactory,它也不起作用,因为主模式无法看到在主 XSD 文件中声明的import schema Even when I give this schemas as files it does not work, because Spring's resource files can't be resolved to absolute path .即使我将此模式作为文件提供它也不起作用,因为Spring's资源文件无法解析为 absolute path

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

1. First we need this dependency which can parse xsd schemas: 1.首先我们需要这个可以解析xsd模式的依赖:

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

2. We create 2 beans. 2. 我们创建 2 个 bean。 One for storing our XSD's (it will automatically find other files if there this schemaLocation="..." ), another for our Validator :一个用于存储我们的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. And we can use it: 3.我们可以使用它:

    @Autowired
    private val myValidator: XmlValidator

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

Array<SAXParseException> will contain list of validation exceptions if any of course Array<SAXParseException>将包含验证异常列表,如果有的话

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM