//Example XML document
/* An XML Document
<?xml version="1.0" standalone="yes"?>
<person>
<name>Joe Wang</name>
<phone type="home">306 555-9999</phone>
<email>joe@yoursite.net;</email>
</person>
*/
import java.io.IOException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.xml.sax.ErrorHandler;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;
import org.xml.sax.XMLReader;
public class SAXCheck {
static public void main(String[] arg) {
String filename = null;
boolean validate = false;
if (arg.length == 1) {
filename = arg[0];
} else if (arg.length == 2) {
if (!arg[0].equals("-v"))
usage();
validate = true;
filename = arg[1];
} else {
usage();
}
// Create a new factory to create parsers that will
// validate or not, according to the flag setting.
SAXParserFactory spf = SAXParserFactory.newInstance();
spf.setValidating(validate);
// Create the XMLReader to be used to check for errors.
XMLReader reader = null;
try {
SAXParser parser = spf.newSAXParser();
reader = parser.getXMLReader();
} catch (Exception e) {
System.err.println(e);
System.exit(1);
}
// Install an error handler in the reader.
reader.setErrorHandler(new MyErrorHandler());
// Use the XMLReader to parse the entire file.
try {
InputSource is = new InputSource(filename);
reader.parse(is);
} catch (SAXException e) {
System.exit(1);
} catch (IOException e) {
System.err.println(e);
System.exit(1);
}
}
private static void usage() {
System.err.println("Usage: SAXCheck [-v] <filename>");
System.exit(1);
}
}
class MyErrorHandler implements ErrorHandler {
public void warning(SAXParseException e) throws SAXException {
show("Warning", e);
throw (e);
}
public void error(SAXParseException e) throws SAXException {
show("Error", e);
throw (e);
}
public void fatalError(SAXParseException e) throws SAXException {
show("Fatal Error", e);
throw (e);
}
private void show(String type, SAXParseException e) {
System.out.println(type + ": " + e.getMessage());
System.out.println("Line " + e.getLineNumber() + " Column "
+ e.getColumnNumber());
System.out.println("System ID: " + e.getSystemId());
}
}
|