针对多个XSD(存储为资源)验证XML.春季靴 [英] Validating XML against multiple XSD(stored as resources). Spring Boot

查看:120
本文介绍了针对多个XSD(存储为资源)验证XML.春季靴的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.首先,我们需要这种可以解析xsd模式的依赖项:

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

2.我们创建2个bean.一个用于存储我们的XSD's(如果存在schemaLocation="...",它将自动查找其他文件),另一个用于存储我们的Validator:

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.我们可以使用它:

    @Autowired
    private val myValidator: XmlValidator

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

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

Array<SAXParseException> will contain list of validation exceptions if any of course

这篇关于针对多个XSD(存储为资源)验证XML.春季靴的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆