Handling Errors While Parsing an XML File

This example installs an error handler to a parser. The error handler logs error messages to a logger (see The Quintessential Logging Program).
// Create a builder DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder(); // Set an error listener builder.setErrorHandler(new MyErrorHandler()); // Use the builder to parse the file Document doc = builder.parse(new File("infilename.xml")); } catch (SAXException e) { // A parsing error occurred; the xml input is not valid. // This exception can still be thrown, even if an error handler is installed. } catch (ParserConfigurationException e) { } catch (IOException e) { } // This error handler uses a Logger to log error messages class MyErrorHandler implements ErrorHandler { // This method is called in the event of a recoverable error public void error(SAXParseException e) { log(Level.SEVERE, "Error", e); } // This method is called in the event of a non-recoverable error public void fatalError(SAXParseException e) { log(Level.SEVERE, "Fatal Error", e); } // This method is called in the event of a warning public void warning(SAXParseException e) { log(Level.WARNING, "Warning", e); } // Get logger to log errors private Logger logger = Logger.getLogger("com.mycompany"); // Dump a log record to a logger private void log(Level level, String message, SAXParseException e) { // Get details int line = e.getLineNumber(); int col = e.getColumnNumber(); String publicId = e.getPublicId(); String systemId = e.getSystemId(); // Append details to message message = message + ": " + e.getMessage() + ": line=" + line + ", col=" + col + ", PUBLIC=" + publicId + ", SYSTEM=" + systemId; // Log the message logger.log(level, message); } }
Given the following input file, MyErrorHandler.fatalError() is called and parse() throws a SAXParseException as well.
<!-- invalid XML --> <root> <element> </root>

Post a comment

More information about formatting options

CAPTCHA
This question is for testing whether you are a human visitor and to prevent automated spam submissions.
Image CAPTCHA
Enter the characters shown in the image. Ignore spaces and be careful about upper and lower case.