这个压缩包里的都是超级经典的java例子
源代码在线查看: seterror.htm
Handling Errors While Parsing an XML File (Java Developers Almanac Example)
The Java Developers Almanac 1.4
Order this book from Amazon.
google_ad_client = "pub-6001183370374757";
google_ad_width = 120;
google_ad_height = 600;
google_ad_format = "120x600_as";
google_ad_channel = "4777242811";
google_ad_type = "text_image";
google_color_border = "FFFFFF";
google_color_bg = "FFFFFF";
google_color_link = "6666CC";
google_color_url = "6666CC";
google_color_text = "000000";
//-->
Home
>
List of Packages
>
javax.xml.parsers
[8 examples]
>
DOM
[4 examples]
e513. 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 e385 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>
Related Examples
e510.
The Quintessential Program to Create a DOM Document from an XML File
e511.
Creating an Empty DOM Document
e512.
Converting an XML Fragment into a DOM Fragment
See also:
DOM Parsing Options
SAX
© 2002 Addison-Wesley.