Example usage for org.dom4j.io SAXValidator SAXValidator

List of usage examples for org.dom4j.io SAXValidator SAXValidator

Introduction

In this page you can find the example usage for org.dom4j.io SAXValidator SAXValidator.

Prototype

public SAXValidator() 

Source Link

Usage

From source file:org.dom4j.samples.validate.SAXValidatorDemo.java

License:Open Source License

protected void validate(String url, boolean validateOnParse) throws Exception {
    println("Parsing: " + url + " with validation mode: " + validateOnParse);

    XMLErrorHandler errorHandler = new XMLErrorHandler();

    if (validateOnParse) {
        // validate as we parse
        SAXReader reader = new SAXReader(true);
        reader.setErrorHandler(errorHandler);

        try {//from  w  w  w .  ja  v  a  2s.  com
            Document document = reader.read(url);
            println("Document: " + url + " is valid!");
        } catch (DocumentException e) {
            println("Document: " + url + " is not valid");
            println("Exception: " + e);
        }
    } else {
        // parse without validating, then do that later
        SAXReader reader = new SAXReader();
        Document document = reader.read(url);

        println("Document URI: " + document.getName());

        // now lets set a doc type if one isn't set
        DocumentType docType = document.getDocType();
        if (docType == null) {
            println("Adding an NITF doc type");
            document.addDocType("nitf", null, "nitf.dtd");
        }

        // now lets validate
        try {
            SAXValidator validator = new SAXValidator();
            validator.setErrorHandler(errorHandler);
            validator.validate(document);

            println("Document: " + url + " is valid!");
        } catch (SAXException e) {
            println("Document: " + url + " is not valid");
            println("Exception: " + e);
        }
    }

    // now lets output any errors as XML
    Element errors = errorHandler.getErrors();
    if (errors.hasContent()) {
        XMLWriter writer = new XMLWriter(OutputFormat.createPrettyPrint());
        writer.write(errors);
    }
}