FileDocCategorySizeDatePackage
XMLValidator.javaAPI DocExample1972Sun Jul 07 09:39:26 BST 2002javajaxb.util

XMLValidator.java

package javajaxb.util;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintStream;
import java.io.Reader;

// JAXP classes
import javax.xml.parsers.SAXParserFactory;
import javax.xml.parsers.SAXParser;

// SAX classes
import org.xml.sax.InputSource;
import org.xml.sax.helpers.DefaultHandler;

public class XMLValidator {

    public XMLValidator() {
        // Currently, does nothing
    }

    public void validate(Reader reader, OutputStream errorStream) {
        PrintStream printStream = new PrintStream(errorStream);
        try {
            SAXParserFactory factory = SAXParserFactory.newInstance();
            factory.setValidating(true);

            SAXParser parser = factory.newSAXParser();
            parser.parse(new InputSource(reader), new DefaultHandler());

            // If we got here, no errors occurred
            printStream.print("XML document is valid.\n");
        } catch (Exception e) {
            e.printStackTrace(printStream);
        }
    }

    public static void main(String[] args) {
        if (args.length != 1) {
            System.out.println("Usage: java javajaxb.util.XMLValidator " +
                "[XML filename]");
            return;
        }

        try {
            File xmlFile = new File(args[0]);
            FileReader reader = new FileReader(xmlFile);

            XMLValidator validator = new XMLValidator();

            // Validate, and write errors to system output stream
            validator.validate(reader, System.out);
        } catch (FileNotFoundException e) {
            System.out.println("Could not locate XML document '" +
                args[0] + "'");
        } catch (IOException e) {
            System.out.println("Error processing XML: " + e.getMessage());
            e.printStackTrace();
        }
    }
}