Validation xsd en gérant la résolution des xsd
Il faut implementer l'interface LSResourceResolver
1public class ResourceResolver implements LSResourceResolver {
2
3public LSInput resolveResource(String type, String namespaceURI,
4 String publicId, String systemId, String baseURI) {
5
6 // note: in this sample, the XSD's are expected to be in the root of the classpath
7 InputStream resourceAsStream = this.getClass().getClassLoader()
8 .getResourceAsStream(systemId);
9 return new Input(publicId, systemId, resourceAsStream);
10}
11
12 }
Ensuite, l'appel se fait comme cela :
1// note that if your XML already declares the XSD to which it has to conform, then there's no need to declare the schemaName here
2void validate(String xml, String schemaName) throws Exception {
3
4 DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();
5 builderFactory.setNamespaceAware(true);
6
7 DocumentBuilder parser = builderFactory
8 .newDocumentBuilder();
9
10 // parse the XML into a document object
11 Document document = parser.parse(new StringInputStream(xml));
12
13 SchemaFactory factory = SchemaFactory
14 .newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
15
16 // associate the schema factory with the resource resolver, which is responsible for resolving the imported XSD's
17 factory.setResourceResolver(new ResourceResolver());
18
19 // note that if your XML already declares the XSD to which it has to conform, then there's no need to create a validator from a Schema object
20 Source schemaFile = new StreamSource(getClass().getClassLoader()
21 .getResourceAsStream(schemaName));
22 Schema schema = factory.newSchema(schemaFile);
23
24 Validator validator = schema.newValidator();
25 validator.validate(new DOMSource(document));
26}
Pour la source (new StreamSource(...)), il faut utiliser un InputStream. Si on met à la place un File, la résolution est faites sans passer par le ressourceResolver