package org.mcraig.cs445.refentry;
import java.io.FileReader;
import org.xml.sax.InputSource;
import org.xml.sax.XMLReader;
import org.xml.sax.helpers.DefaultHandler;
import org.xml.sax.helpers.XMLReaderFactory;
/**
* Wrapper for a SAX parser that checks XML document validity.
* @author <a href=mailto:mark@mcraig.org>Mark Craig</a>
*/
public class RefEntryValidator {
/**
* Command-line interface for the validator.<p>
* Usage: java RefEntryValidator <filename>
*/
public static void main(String[] args) {
if (args.length != 1) {
System.err.println("Usage: java RefEntryValidator <filename>");
System.exit(1);
}
try {
InputSource src = new InputSource(new FileReader(args[0]));
if (isValid(src)) System.out.println("Valid.");
else System.out.println("Not valid.");
} catch (Exception e) {
System.err.println(e.toString());
}
}
/**
* Returns true if the input is a valid XML document.
* @param src The XML document to validate.
*/
public static boolean isValid(InputSource src) {
boolean srcIsValid = false;
try {
String saxp = new String("org.apache.xerces.parsers.SAXParser");
XMLReader reader = XMLReaderFactory.createXMLReader(saxp);
reader.setFeature("http://xml.org/sax/features/validation", true);
reader.setContentHandler(new DefaultHandler());
reader.setErrorHandler(new RefEntryErrorHandler());
reader.parse(src);
srcIsValid = true;
} catch (Exception e) {
System.out.println(e.toString());
} finally {
return srcIsValid;
}
}
} |