I am trying out some XML Schema examples and have to validate them with a sample XML File. The schema is a local file (someFile.xsd). I am using eclipse and want to include
Does something like this work?
<?xml version="1.0"?> <note xmlns="http://www.w3schools.com" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.w3schools.com note.xsd"> <to>Tove</to> <from>Jani</from> <heading>Reminder</heading> <body>Don't forget me this weekend!</body> </note>
Copied from http://www.w3schools.com/Schema/schema_howto.asp
Are you using the xsi:schemaLocation attribute?
Ex:
<?xml version="1.0" encoding="UTF-8"?>
<root xmlns="http://foo/target/Namespace"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:someNamespace="someFile"
xsi:schemaLocation="
someFile someFile.xsd" >
...
</root>
I believe someFile.xsd
has to be in your classpath
You can set your own Implementation of ResourceResolver and LSInput to the SchemaFactory so that the call of of LSInput.getCharacterStream() will provide a schema from a local path.
It tried to provide a comprehensive example here.
The approach basically consists of a proper implementation of what is called from
getSchemaAsStream(input.getSystemId(), input.getBaseURI(), localPath)));
at the end of the following code. At this point you have to hook in with your own lookup mechanism to find schema files on your local path.
public void validate(InputStream xmlStream, InputStream schemaStream, String baseUri, String localPath)
throws SAXException, IOException {
Source xmlFile = new StreamSource(xmlStream);
SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
factory.setResourceResolver((type, namespaceURI, publicId, systemId, baseURI) -> {
LSInput input = new DOMInputImpl();
input.setPublicId(publicId);
input.setSystemId(systemId);
input.setBaseURI(baseUri);
input.setCharacterStream(new InputStreamReader(
getSchemaAsStream(input.getSystemId(), input.getBaseURI(), localPath)));
return input;
});