import java.io.IOException;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.w3c.dom.Document;
import org.xml.sax.ErrorHandler;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;
public class DOMCheck {
static public void main(String[] arg) {
boolean validate = true;
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
dbf.setValidating(validate);
dbf.setNamespaceAware(true);
try {
DocumentBuilder builder = dbf.newDocumentBuilder();
builder.setErrorHandler(new MyErrorHandler());
InputSource is = new InputSource("person.xml");
Document doc = builder.parse(is);
} catch (SAXException e) {
System.out.println(e);
} catch (ParserConfigurationException e) {
System.err.println(e);
} catch (IOException e) {
System.err.println(e);
}
}
}
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());
}
}
//File: person.xml
999 555-8888
e@yoursite.net
R, L
333 555-9910
V, R
rv@yoursite.com
B, D.
b@xyz.net
c@n.net
C, X
502 555-2192
B, M
Error: Document is invalid: no grammar found.
Line 3 Column 7
System ID: file:///C:/Java_Dev/eclipse31/Eclipse/person.xml
org.xml.sax.SAXParseException: Document is invalid: no grammar found.