问题描述
我正在尝试针对许多不同的模式验证 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.
为了通过包含正确加载子架构,我必须编写一个自定义资源解析器.代码可以在这里找到:
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/resources).欢迎对此提出任何意见...
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 文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!