問題描述
我正在嘗試針對許多不同的模式驗證 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 文件的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!