0

I am trying to validate an xml file which is generated w.r.t a schema in xsd format. The doubt is if I need to pass the url of the schema or the location of schema on my system ? Similarly, do we need to pass the content of xml file or its location ?

Below is the code snippet I am using -

public void validateDTFAgainstXSD()
{
    String inputxml = "C:/Users/file.xml";
    String schemaLocation = "https://github.abcd/schema.xsd";
    try
    {
        SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
        File schemaFile = new File(schemaLocation);
        Schema schema = factory.newSchema(schemaFile);
        javax.xml.validation.Validator validator = schema.newValidator();

        Source source = new StreamSource(new StringReader(inputxml));
        validator.validate(source);
        System.out.println("File validated");
    }
    catch(Exception ex)
    {
        System.out.println("File not validated");
    }       
}
R11G
  • 1,941
  • 8
  • 26
  • 37
  • I did a lot of research for my above question. And among the many questions related to it on the site, this one answers it the BEST - http://stackoverflow.com/a/16054/1472493 – R11G Apr 04 '13 at 16:37

1 Answers1

1

There are newSchema() overloads that take either a File object or a Source object. You're passing a File, which is fine.

The Validator.validate() method requires a Source. If you have a filename, you can construct a Source using new StreamSource(new File(filename)). The way you are doing it is wrong: it assumes that the string your are wrapping in the StringReader contains the XML to be validated, not the name of a file containing the XML.

Michael Kay
  • 156,231
  • 11
  • 92
  • 164
  • Getting this error - org.apache.xerces.jaxp.validation.ValidatorImpl cannot be cast to javax.xml.bind.Validator For this line : Validator validator = (Validator) schema.newValidator(); – R11G Apr 03 '13 at 18:42
  • That's just a simple case of importing the Validator class from the wrong package. Basic Java error. – Michael Kay Apr 04 '13 at 09:46