Validating against a Schema with JAXB

前端 未结 2 620
南方客
南方客 2021-01-04 09:37

I\'ve been looking for solutions to this problem for far too long considering how easy it sounds so I\'ve come for some help.

I have an XML Schema which I have used

相关标签:
2条回答
  • 2021-01-04 10:29

    As far as I know, you just have to set the schema with Marshaller.setSchema() to a schema created by the SchemaFactory from your DDSSettings.xsd. This will turn validation on.

    0 讨论(0)
  • 2021-01-04 10:30

    OK, I've found the solution. Using the schema factory to create a schema, but without specifying a schema file makes it work with the noNamespaceSchemaLocation specified in the XML file.

    So the code from above has had this added:

    SchemaFactory factory = SchemaFactory.newInstance("http://www.w3.org/2001/XMLSchema");
    Schema schema = factory.newSchema();
    Unmarshaller unmarshaller = jc.createUnmarshaller();
    unmarshaller.setSchema(schema);
    m_ddsSettings = (com.ultra.DDSSettings)unmarshaller.unmarshal(new File(xmlfileName));
    

    Shame that took the best part of 24 hours to find the answer to!

    The javadoc for SchemaFactory.newSchema() says:

    For XML Schema, this method creates a Schema object that performs validation by using location hints specified in documents.

    The returned Schema object assumes that if documents refer to the same URL in the schema location hints, they will always resolve to the same schema document. This asusmption allows implementations to reuse parsed results of schema documents so that multiple validations against the same schema will run faster.

    0 讨论(0)
提交回复
热议问题