I want to validate an XSD file (not XML). The approach i am using is to treat the XSD as any other XML file and use this www.w3.org/2001/XMLSchema.xsd as the schema.
I am using the following code:
String schemaLang = "http://www.w3.org/2001/XMLSchema";
SchemaFactory factory = SchemaFactory.newInstance(schemaLang);
Schema schema = factory.newSchema(new StreamSource("C:\\Users\\aprasad\\Desktop\\XMLSchema.xsd"));
Validator validator = schema.newValidator();
validator.validate(new StreamSource("shiporder.xsd"));
But i am getting the following error:
Failed to read schema document 'XMLSchema.xsd', because 1) could not find the document; 2) the document could not be read; 3) the root element of the document is not <xsd:schema>
.
Not sure what the error is as the file path is correct.
Please tell me the correct approach to validate an XSD file.
You need to have two additional files right beside XMLSchema.xsd
. These are:
XMLSchema.dtd
datatypes.dtd
XMLSchema.xsd
references these two files.
Right beside, so if XMLSchema.xsd
is located at C:/XMLSchema.xsd
then you have to have C:/XMLSchema.dtd
and C:/datatypes.dtd
.
SchemaFactory
instances use (see SchemaFactory.setResourceResolver(LSResourceResolver)
) by default an internal class called XMLCatalogResolver
which implements LSResourceResolver
. The former (I assume) looks for referenced files beside the referer.
If you look really hard then the cause of your SAXParseException
is a FileNotFoundException
that says the the system couldn't find the XMLSchema.dtd
file.
Other than this, your code is OK (and your schema too).
According to the javadoc for the StreamSource class, if you use the constructor method that takes a String
, that string needs to be a valid URI. For example, if you are trying to reference a local file, you may need to prefix the path with file:/
. Alternatively, you can pass a File
object to the constructor:
Schema schema = factory.newSchema(new File(new StreamSource("C:\\Users\\aprasad\\Desktop\\XMLSchema.xsd")));
In summary, it would be beneficial in this case to do some simple testing to rule out problems caused by your program not finding the necessary files, for example
File schemaFile1 = new File("C:\\Users\\aprasad\\Desktop\\XMLSchema.xsd");
File schemaFile2 = new File("shiporder.xsd");
assert schemaFile1.exists();
assert schemaFile2.exists();
I wonder what you are trying to achieve? If factory.newSchema(X) throws no exception, then X must be a valid schema(*). That seems a much more straightforward thing to do than validating against the schema for schema documents.
(*) the reverse isn't necessarily true of course: X might be valid against the schema for schema documents, but be invalid for other reasons, such as violating a UPA constraint.