Handling Errors While Parsing an XML File
import java.io.File;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.xml.sax.ErrorHandler;
import org.xml.sax.SAXParseException;
public class Main {
public static void main(String[] argv) throws Exception {
DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
builder.setErrorHandler(new MyErrorHandler());
Document doc = builder.parse(new File("infilename.xml"));
}
}
class MyErrorHandler implements ErrorHandler {
public void error(SAXParseException e) {
log(Level.SEVERE, "Error", e);
}
public void fatalError(SAXParseException e) {
log(Level.SEVERE, "Fatal Error", e);
}
public void warning(SAXParseException e) {
log(Level.WARNING, "Warning", e);
}
private Logger logger = Logger.getLogger("com.mycompany");
private void log(Level level, String message, SAXParseException e) {
int line = e.getLineNumber();
int col = e.getColumnNumber();
String publicId = e.getPublicId();
String systemId = e.getSystemId();
message = message + ": " + e.getMessage() + ": line=" + line + ", col=" + col + ", PUBLIC="
+ publicId + ", SYSTEM=" + systemId;
logger.log(level, message);
}
}
Related examples in the same category