XMLドキュメントをスキーマに対して検証しています。このコードを使用してそれらを検証しようとすると、いくつかのより複雑なドキュメント/スキーマは常に失敗します。
DocumentBuilderFactory dbfac = DocumentBuilderFactory.newInstance();
dbfac.setNamespaceAware(true);
dbfac.setIgnoringElementContentWhitespace(true);
DocumentBuilder docBuilder = dbfac.newDocumentBuilder();
Document doc = docBuilder.parse("sampleResponse.xml");
SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
Source schemaSource = new StreamSource(getClass().getResourceAsStream("/" + "SampleResponse.xsd"));
Schema schema = schemaFactory.newSchema(schemaSource);
Validator validator = schema.newValidator();
Source source = new DOMSource(doc);
// Set a custom error handler that simple re-throws every exception
validator.setErrorHandler(new ValidationErrorHandler());
validator.validate(source);
問題はこの行です:
Source schemaSource = new StreamSource(getClass().getResourceAsStream("/" + "SampleResponse.xsd"));
スキーマをファイルとして読み取ると、次のように機能します。
Source schemaSource = new StreamSource(new File("somepath/SampleResponse.xsd"));
クラスパスからスキーマを直接取得すると、検証が機能しないのはなぜですか?
(Windows 764ビットでJava1.6を使用)
失敗した場合の例外メッセージ:
Could not validate against schema SampleResponse.xsd. Nested exception: src-resolve: Cannot resolve the name 'oa:Attachments' to a(n) 'element declaration' component.