Validating against a Schema with JAXB

痴心易碎 提交于 2019-11-30 17:47:37
fwgx

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.

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!