gpt4 book ai didi

java - 针对多个 XSD(存储为资源)验证 XML。 Spring 启动

转载 作者:行者123 更新时间:2023-12-01 17:03:27 24 4
gpt4 key购买 nike

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

<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>当然将包含验证异常(exception)列表(如果有的话)

关于java - 针对多个 XSD(存储为资源)验证 XML。 Spring 启动,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61483586/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com