import javax.xml.parsers.SAXParser; import javax.xml.parsers.SAXParserFactory; import org.xml.sax.helpers.DefaultHandler; import org.xml.sax.SAXParseException; /** * Lecture 8's demonstration of validation. * * @author Computer Science E-259 **/ public class SAXValidator extends DefaultHandler { /** * Main driver. Expects one command-line argument: the name of the * XML file to validate * * @param argv [0] - filename */ public static void main(String [] argv) { // grab filename String input = argv[0]; try { // instantiate a SAX parser factory SAXParserFactory factory = SAXParserFactory.newInstance(); // enable validation factory.setValidating(true); // instantiate a SAX parser SAXParser parser = factory.newSAXParser(); // instantiate our little handler SAXValidator handler = new SAXValidator(); // parse the file parser.parse(input, handler); } catch (Exception e) { e.printStackTrace(); } } /** * Receive notification of a recoverable parser error. * * @param e the exception thrown */ public void error(SAXParseException e) { System.out.println("Parsing error at " + e.getLineNumber() + ":" + e.getColumnNumber() + ": " + e.getMessage()); } /** * Receive notification of a parser warning. * * @param e the exception thrown */ public void warning(SAXParseException e) { System.out.println("Parsing warning at " + e.getLineNumber() + ":" + e.getColumnNumber() + ": " + e.getMessage()); } /** * Report a fatal XML parsing error. * * @param e the exception thrown */ public void fatalError(SAXParseException e) { System.out.println("Fatal parsing warning at " + e.getLineNumber() + ":" + e.getColumnNumber() + ": " + e.getMessage()); } }