2

Possible Duplicate:
Validating XML against XSD

I am using this code to validate my XML with an XSD

        DocumentBuilder parser = factory.newDocumentBuilder();

        // Parse the file. If errors found, they will be printed.
        parser.parse(args[1]);

But i want to know how does it work , will it check tag or all data ? How reliable it is ?

Community
  • 1
  • 1
abhinav
  • 57
  • 1
  • 8

1 Answers1

1

You could do something like the following where after the document is parser the resulting DOM is validated against the XML schema. You can set an instance of ErrorHandler so that you can choose what to do with an validation errors.

public class Demo {

    public static void main(String[] args) throws Exception {
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        factory.setNamespaceAware(true);
        DocumentBuilder parser = factory.newDocumentBuilder();
        Document document = parser.parse(args[1]);
        DOMSouce source = new DOMSource(document);

        SchemaFactory sf = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
        Schema schema = sf.newSchema(new File("customer.xsd"));

        Validator validator = schema.newValidator();
        validator.setErrorHandler(new MyErrorHandler());
        validator.validate(source);
    }

}

Alternatively you could call setSchema on the DocumentBuilderFactory so that validation will happen during the parse, but this isn't supported by all DOM parsers:

For More Information

Below is a link to an example from my blog where this schema validation approach is used. In that example a JAXBSource instead of a DOMSource is used, but everything else is the same.

bdoughan
  • 147,609
  • 23
  • 300
  • 400