使用SAXParser(SAXParserFactory.newInstance())验证XML文件格式---XSD
SAXValidator.java---------------------------------------------------------- package com.xsd; import java.io.File; import java.io.IOException; import javax.xml.parsers.ParserConfigurationException; import javax.xml.parsers.SAXParser; import javax.xml.parsers.SAXParserFactory; import org.xml.sax.SAXException; import org.xml.sax.SAXParseException; import org.xml.sax.helpers.DefaultHandler; class SAXValidator { public static void main(String[] args) { String schemaFeature = "http://apache.org/xml/features/validation/schema"; String fileName = "conf/xsd/dictionary_invalid_xsd.xml"; try { File x = new File(fileName); SAXParserFactory f = SAXParserFactory.newInstance(); System.out.println(f.toString()); f.setValidating(true); f.setFeature(schemaFeature, true); SAXParser p = f.newSAXParser(); System.out.println(p.toString()); DefaultHandler h = new MyErrorHandler(); p.parse(x, h); } catch (ParserConfigurationException e) { System.out.println(e.toString()); } catch (SAXException e) { System.out.println(e.toString()); } catch (IOException e) { System.out.println(e.toString()); } } private static class MyErrorHandler extends DefaultHandler { public void warning(SAXParseException e) throws SAXException { System.out.println("Warning: "); printInfo(e); } public void error(SAXParseException e) throws SAXException { System.out.println("Error: "); printInfo(e); } public void fatalError(SAXParseException e) throws SAXException { System.out.println("Fattal error: "); printInfo(e); } private void printInfo(SAXParseException e) { System.out.println(" Public ID: " + e.getPublicId()); System.out.println(" System ID: " + e.getSystemId()); System.out.println(" Line number: " + e.getLineNumber()); System.out.println(" Column number: " + e.getColumnNumber()); System.out.println(" Message: " + e.getMessage()); } } } dictionary_invalid_xsd.xml---------------------------------------------- XML eXtensible Markup Language. < Mathematical symbol representing the "less than" logical operation, like: 1<2. Reserved symbol in XML representing the beginning of tags, like: Hello world!
]]> extensible Capable of being extended. dictionary.xsd-------------------------------------------------------