Parsing a Document with XMLReader

import org.xml.sax.*;
import org.xml.sax.helpers.*;
import java.io.*;

public class SAX2Checker {

  public static void main(String[] args) {

    XMLReader parser;
    try {
      parser = XMLReaderFactory.createXMLReader();
    }
    catch (SAXException ex) {
      try {
        parser = XMLReaderFactory.createXMLReader(
         "org.apache.xerces.parsers.SAXParser");
      }
      catch (SAXException ex2) {
        System.out.println("Could not locate a parser."
         + "Please set the the org.xml.sax.driver property.");
        return;
      }
    }

    if (args.length == 0) {
      System.out.println("Usage: java SAX2Checker URL1 URL2...");
    }

    // start parsing...
    for (int i = 0; i < args.length; i++) {

      // command line should offer URIs or file names
      try {
        parser.parse(args[i]);
        // If there are no well-formedness errors
        // then no exception is thrown
        System.out.println(args[i] + " is well formed.");
      }
      catch (SAXParseException ex) { // well-formedness error
        System.out.println(args[i] + " is not well formed.");
        System.out.println(ex.getMessage()
         + " at line " + ex.getLineNumber()
         + ", column " + ex.getColumnNumber());
      }
      catch (SAXException ex) { // some other kind of error
        System.out.println(ex.getMessage());
      }
      catch (IOException ex) {
        System.out.println("Could not check " + args[i]
         + " because of the IOException " + ex);
      }
    }
  }
}

Previous | Next | Top | Cafe con Leche

Copyright 2002-2006 Elliotte Rusty Harold
elharo@metalab.unc.edu
Last Modified January 2, 2006