ddvalidator.java

来自「JAVA Servlet2.3外文书籍源码」· Java 代码 · 共 80 行

JAVA
80
字号
package deployment;
import java.io.*;
// JAXP packages
import javax.xml.parsers.*;
import org.xml.sax.*;
import org.xml.sax.helpers.*;
import org.w3c.dom.*;

public class DDValidator {
  private String xmlfile;

  public DDValidator(String xmlfile) {
    this.xmlfile = xmlfile;
  }

  private boolean isValid() throws SAXException {

    // Step 1: create a DocumentBuilderFactory and configure it
    DocumentBuilderFactory dbf =
    DocumentBuilderFactory.newInstance();
    dbf.setValidating(true);

    // Step 2: create a DocumentBuilder that satisfies the constraints
    // specified by the DocumentBuilderFactory
    DocumentBuilder db = null;
    try {
      db = dbf.newDocumentBuilder();

      //  Inner class to handle errors in parsing the document
      db.setErrorHandler(new DefaultHandler() {
         public void error(SAXParseException e) throws SAXException {
            throw new SAXException ("ERROR : " + e.getMessage());
         }
         public void fatalError(SAXParseException e) throws SAXException {
            throw new SAXException ("FATAL ERROR : " + e.getMessage());
         }

      });
    } catch (ParserConfigurationException pce) {
      System.err.println("Exception with configuration" + pce);
      System.exit(1);
    }

    //  Step 3: create a dom by parsing the document.
    //  any parse errors will cause an exception to be thrown
    Document doc = null;
    try {

      doc = db.parse(new File(this.xmlfile));

    } catch (IOException ioe) {
      // If the file was not valid, throw an exception
      throw new SAXException("Document Invalid " + ioe.getMessage());
    }

    // This point is only ever reached if the XML was validated
    return true;

  }

  public static void main(String args[]) {
    //  Get the name of the XML doc
    if (args.length != 1) {
      System.err.println("Usage: DDValidator xml_file_to_validate");
      System.exit(0);
    }

    String xmlfile = args[0];
    DDValidator validator = new DDValidator(xmlfile);

    try {
      System.out.println(validator.isValid());
    } catch (SAXException se) {
      System.err.println(se.getMessage());
    }
  }


}

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?