Search code examples
javavalidationdocumentgrammarxerces

How to validate a document using a grammar in Xerces


I have following situation
- I create XML-documents (DocumentImpl) on the fly (using data). So the XML is never written to disc.
- I create XSD-schemas on the fly (using data-definitions), these also are never written to disc. The grammars are complex with assertions, so they need to be used as XMLSchema v1.1
- I store the grammars (SchemaGrammar) from the XSD-schemas in a hashmap, this is because the same grammars are often used more times.

Now my question,

I want to validate the documents against a grammar. I know which grammar to use. They are found by the according data-definition-name.

My problem is that I cannot find example code how to do this, because all the examples seem to work from streams or files, while I have the objects ready.


Solution

  • I think, it works like this:

    `

    XMLGrammarPoolImpl pool = new XMLGrammarPoolImpl();
    pool.putGrammar(grammar);
    
    XMLSchema11Factory factory = new XMLSchema11Factory();
    Schema schema = factory.newSchema(pool);
    
    Validator validator = schema.newValidator();
    
    DOMSource source = new DOMSource(document);
    validator.validate(source);
    

    `