【问题标题】:Validating XML against multiple XSD(stored as resources). Spring Boot针对多个 XSD(存储为资源)验证 XML。弹簧靴
【发布时间】:2020-08-12 11:11:36
【问题描述】:

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

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

【问题讨论】:

    标签: java xml spring kotlin xsd


    【解决方案1】:

    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&lt;SAXParseException&gt; 将包含验证异常列表(如果有的话)

    【讨论】:

      猜你喜欢
      • 2012-09-20
      • 2021-04-11
      • 2011-02-07
      • 2014-07-13
      • 2014-02-05
      • 1970-01-01
      • 2017-12-22
      • 2020-03-12
      • 2011-10-12
      相关资源
      最近更新 更多