0

Consider this XML:

<?xml version="1.0" encoding="UTF-8"?>
<config version="1" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:noNamespaceSchemaLocation="http://acme.com/schemas/version1.xsd">

    <params>
        <param>

...

I want to parse the XML in Java and validate the input against the schema.

All the examples that I have seen load the schema beforehand (hard-coded) then parse and validate the XML. But this implies that the particular schema is already known.

It is possible to get the parser to look up the schema defined in the XML? I want to be able to support evolving versions and be able to refer to the relevant schema in the XML itself.

Currently, I load the XML and test the version attribute. I then load version{n}.xsd and validate. I would be nicer to handle it automatically via something like an EntityResolver.

private void validate(Document doc, int version) throws SAXException, IOException {
    if(version < 1) return;
        
    SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
    InputStream inp = this.getClass().getResourceAsStream(String.format("version%d.xsd", version));
    Schema schema = factory.newSchema(new StreamSource(inp));
    Validator validator = schema.newValidator();
    StringReader rdr = new StringReader(getStringFromDocument(doc));
    validator.validate(new StreamSource(rdr));
}
paul
  • 13,312
  • 23
  • 81
  • 144

0 Answers0