问题
I am trying to do xml validation. I am being given a list of schemas at run-time (possibly wrapped in a jar). Validation passes or failes based on the order in which I provide the schemas to the SchemaFactory.
Here is what I am doing:
private void validateXml(String xml, List<URI> schemas){
Source[] source = new StreamSource[schemas.size()];
int i=0;
for (URI f : schemas){
source[i++] = new StreamSource(f.openStream());
}
SchemaFactory sf = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NA_URI);
sf.setResourceResolver(new MyClassPathResourceResolver());
Schema schema = schemaFactory.newSchema(source);
Validator validator = schema.newValidator();
validator.validate(new StreamSource(new ByteArrayInputStream(xml.getBytes()));
again, this fails if the passed set of schema do not start with the schema to which the root element of the xml referrs. Is there a fix to this or am I doing something wrong?
回答1:
By default Xerces will ignore a schema document if it already has a schema document for the same namespace. This behaviour can be changed using the factory option
http://apache.org/xml/features/validation/schema/handle-multiple-imports
回答2:
Firstly, you must set an instance of org.xml.sax.ErrorHandler object on XML reader by calling registerErrorHandler() method. You might receive warnings which would give you clue about issue.
Secondly, you must know which xml library you are using. Call schemaFactory.getClass().getName() in your code and print it. Once you know library, you can refer its documentation if it supports feature to turn on/off multiple schema imports.
来源:https://stackoverflow.com/questions/11852311/validate-xml-with-loading-schemas-at-runtime-failure-depending-on-schema-order