I have two xsd files to validate a xml. But the problem is my code takes only one xsd. How to use other xsd in the following code? I dont have idea about where should i place/call 2nd 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();
}
}
Schemas can be composed of one or more XML documents. These schema documents can be explicitly joined together using the include and import elements.
XML documents are validated by the Create method of the XmlReader class. To validate an XML document, construct an XmlReaderSettings object that contains an XML schema definition language (XSD) schema with which to validate the XML document. The System. Xml.
You can validate your XML documents against XML schemas only; validation against DTDs is not supported. However, although you cannot validate against DTDs, you can insert documents that contain a DOCTYPE or that refer to DTDs.
Plenty of hits when searching on SO or Google. One of them is this question, where the author found his own solution and reports the following code to add multiple xsd's 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 InputStream
on StreamSource
, the resolver is not able to load any referenced XSD files. If, for instance, the file xsd1
imports or includes a third file (which is not xsd2
), schema creation will fail. You should either set the system identifier (setSystemId
) or (even better) use the StreamSource(File f)
constructor.
Adjusted to your 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 working with classpath resources, I'd prefer the StreamSource(String systemId)
constructor (rather than creating a File
):
new StreamSource(getClass().getClassLoader().getResource("a.xsd").toExternalForm());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With