根据多个模式定义验证XML文件 [英] Validate an XML File Against Multiple Schema Definitions

查看:100
本文介绍了根据多个模式定义验证XML文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试针对许多不同的模式验证XML文件(为人为的例子道歉):

I'm trying to validate an XML file against a number of different schemas (apologies for the contrived example):


  • a。 xsd

  • b.xsd

  • c.xsd

c.xsd特别是导入b.xsd和b.xsd导入a.xsd,使用:

c.xsd in particular imports b.xsd and b.xsd imports a.xsd, using:

< xs:include schemaLocation = b.xsd/>

我试图通过Xerces以下列方式执行此操作:

I'm trying to do this via Xerces in the following manner:

XMLSchemaFactory xmlSchemaFactory = new XMLSchemaFactory();
Schema schema = xmlSchemaFactory.newSchema(new StreamSource[] { new StreamSource(this.getClass().getResourceAsStream("a.xsd"), "a.xsd"),
                                                         new StreamSource(this.getClass().getResourceAsStream("b.xsd"), "b.xsd"),
                                                         new StreamSource(this.getClass().getResourceAsStream("c.xsd"), "c.xsd")});     
Validator validator = schema.newValidator();
validator.validate(new StreamSource(new StringReader(xmlContent)));

但这无法正确导入所有三个模式导致无法解析名称'blah'到(n)'组'组件。

but this is failing to import all three of the schemas correctly resulting in cannot resolve the name 'blah' to a(n) 'group' component.

我已经使用 Python 成功验证了这一点,但是 Java 6.0 Xerces存在实际问题2.8.1 即可。任何人都可以在这里建议出现问题,或者更简单的方法来验证我的XML文档吗?

I've validated this successfully using Python, but having real problems with Java 6.0 and Xerces 2.8.1. Can anybody suggest what's going wrong here, or an easier approach to validate my XML documents?

推荐答案

以防其他任何人运行在这里,我需要从单元测试中加载父模式(和隐式子模式) - 作为资源 - 来验证XML字符串。我使用Xerces XMLSchemFactory与Java 6验证器一起执行此操作。

So just in case anybody else runs into the same issue here, I needed to load a parent schema (and implicit child schemas) from a unit test - as a resource - to validate an XML String. I used the Xerces XMLSchemFactory to do this along with the Java 6 validator.

为了通过include正确加载子模式,我必须编写自定义资源解析器。代码可以在这里找到:

In order to load the child schema's correctly via an include I had to write a custom resource resolver. Code can be found here:

https://code.google.com/p/xmlsanity/source/browse/src/com/arc90/xmlsanity/validation/ResourceResolver.java

要使用解析器在架构工厂中指定它:

To use the resolver specify it on the schema factory:

xmlSchemaFactory.setResourceResolver(new ResourceResolver());

它将使用它来通过类路径解析你的资源(在我的例子中来自src / main /资源)。欢迎任何评论......

and it will use it to resolve your resources via the classpath (in my case from src/main/resources). Any comments are welcome on this...

这篇关于根据多个模式定义验证XML文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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