XML file
03. xml
<?xml version="1.0" encoding="gb2312"?><!DOCTYPE persons[ <!ELEMENT persons (person*)> <!ELEMENT person (name,sex,age)> <!ELEMENT name (#PCDATA)> <!ELEMENT sex (#PCDATA)> <!ELEMENT age (#PCDATA)>]><persons> <person> <name>xiaowang</name> <sex>male</sex> <age>27</age> </person></persons>
Java file 1: MyHandler. java
Import org. xml. sax. helpers. defaultHandler; import org. xml. sax. SAXParseException; import org. xml. sax. SAXException; public class MyHandler extends DefaultHandler {String em = null; // general error. Generally, the validity error is public void error (SAXParseException e) throws SAXException {em = e. getMessage (); System. out. println ("general error" + em);} // critical error public void fataError (SAXParseException e) throws SAXException {em = e. getMessage (); System. out. println ("Fatal error" + em );}}
Java file 2: XMLValidate. java
Import org. w3c. dom. document; import javax. xml. parsers. *; import java. util. imports; import java. io. file; public class XMLValidate {public static void main (String [] args) {// Save the name of the XML file String File = null; try {reader = new partition (System. in); System. out. println ("input file to be checked:"); file = reader. nextLine (); // obtain the resolution factory DocumentBuilderFactory factory = DocumentBuilderFactory. newInstance (); // set the parser to support the validity check factory. setValidating (true); // create the DOM parser DocumentBuilder builder = factory. newDocumentBuilder (); // instantiate the event processor MyHandler handler = new MyHandler (); // bind the event processor builder. setErrorHandler (handler); // starts parsing the file Document document = builder. parse (new File (file); // if the returned error message is null, XML is a valid if (handler. em = null) {System. out. println ("file" + file + "is a valid XML file. ");} else {System. out. println ("file" + file + "is invalid XML file") ;}} catch (Exception e) {e. printStackTrace ();}}}
This article is from the "Aegean Sea" blog, please be sure to keep this source http://piano.blog.51cto.com/3954765/1298244