XML validation - using multiple xsd

I have two xsd files for xml validation. But the problem is that my code only accepts one xsd. How to use another xsd in the following code? I have no idea where I should place / call the second xsd file.

private void validate(File xmlF,File xsd1,File xsd2) { try { url = new URL(xsd.toURI().toString());// xsd1 } catch (MalformedURLException e) { e.printStackTrace(); } source = new StreamSource(xml); // xml try { System.out.println(url); schema = schemaFactory.newSchema(url); } catch (SAXException e) { e.printStackTrace(); } validator = schema.newValidator(); System.out.println(xml); try { validator.validate(source); } catch (SAXException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } 
+7
source share
1 answer

Many hits when searching in SO or Google. One of them is this question, where the author found his own solution and reports the following code to add several xsd to the validator:

 Schema schema = factory().newSchema(new Source[] { new StreamSource(stream("foo.xsd")), new StreamSource(stream("Alpha.xsd")), new StreamSource(stream("Mercury.xsd")), }); 

However, when working directly with an InputStream on a StreamSource , the recognizer cannot load any XSD files with a link. If, for example, the xsd1 file imports or includes a third file (which is not xsd2 ), the creation of the schema will fail. You must either set the system identifier ( setSystemId ) or (even better) use the StreamSource(File f) constructor StreamSource(File f) .

Corrected example code:

 try { schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); schema = schemaFactory.newSchema(new Source[] { new StreamSource(xsd1), new StreamSource(xsd2) }); } catch (SAXException e) { // TODO Auto-generated catch block e.printStackTrace(); } 

Note:

If you work with class resources, I would prefer the StreamSource(String systemId) constructor (instead of creating a File ):

 new StreamSource(getClass().getClassLoader().getResource("a.xsd").toExternalForm()); 
+20
source

All Articles