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

我的未来我决定 提交于 2020-05-09 10:22:08

问题


I've spend a lot of time to validate XML against multiple XSD in Spring. 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. Even when I give this schemas as files it does not work, because Spring's resource files can't be resolved to absolute path.

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

回答1:


1. First we need this dependency which can parse xsd schemas:

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

2. We create 2 beans. One for storing our XSD's (it will automatically find other files if there this schemaLocation="..."), another for our 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:

    @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



来源:https://stackoverflow.com/questions/61483586/validating-xml-against-multiple-xsdstored-as-resources-spring-boot

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!