Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java XML validation against XSD Schema

private void validateXML(DOMSource source) throws Exception {
    URL schemaFile = new URL("http://www.csc.liv.ac.uk/~valli/modules.xsd");
    SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_INSTANCE_NS_URI);
    Schema schema = schemaFactory.newSchema(schemaFile);

    Validator validator = schema.newValidator();
    DOMResult result = new DOMResult();
    try {
        validator.validate(source, result); 
        System.out.println("is valid");
    } catch (SAXException e) {
        System.out.println("not valid because " + e.getLocalizedMessage());
    }
}

But this returns an error saying: Exception in thread "main" java.lang.IllegalArgumentException: No SchemaFactory that implements the schema language specified by: http://www.w3.org/2001/XMLSchema -instance could be loaded

Is this a problem with my code or with the actual xsd file?

like image 538
Becky Avatar asked Mar 07 '10 16:03

Becky


People also ask

Can we validate XML documents against a schema?

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.

How you will validate XML document using schema?

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.


1 Answers

That error means that your installed Java doesn't have any classes that can parse XMLSchema files, so it's not a problem with the schema or your code.

I'm pretty sure recent JREs have the appropriate classes by default, so can you get us the output of java -version?


Update:

You're using the wrong XMLContants string. You want: XMLConstants.W3C_XML_SCHEMA_NS_URI

like image 132
brabster Avatar answered Oct 02 '22 02:10

brabster