Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Validate XML with loading schemas at runtime, failure depending on schema order

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?

like image 233
John B Avatar asked Aug 07 '12 18:08

John B


1 Answers

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

like image 135
Michael Kay Avatar answered Sep 28 '22 01:09

Michael Kay