我正在根据模式验证 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 7 64 位上使用 Java 1.6)
失败时的异常消息:
Could not validate against schema SampleResponse.xsd. Nested exception: src-resolve: Cannot resolve the name 'oa:Attachments' to a(n) 'element declaration' component.