
package dom;

import java.io.*;
import org.w3c.dom.*;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;

/**
 * Adapted from code written by Andy Clark, IBM
 */
public class DomParser
{
     /** Validation feature id (http://xml.org/sax/features/validation). */
    protected static final String 
    	VALIDATION_FEATURE_ID = "http://xml.org/sax/features/validation";

    /** Schema validation feature id (http://apache.org/xml/features/validation/schema). */
    protected static final String 
    	SCHEMA_VALIDATION_FEATURE_ID = "http://apache.org/xml/features/validation/schema";

    /** Default parser name. */
    protected static final String DEFAULT_PARSER_NAME = "dom.wrappers.Xerces";

    /** Main program entry point. */
    public static void main(String args[]) 
    {
		System.out.println ("DTD and Schema Parser and Validator");
        BufferedReader stdin = new BufferedReader (new InputStreamReader (System.in));
        String xmlfile = "", option = "";
        try
        {	
        	System.out.print ("Option: v for DTD or s for schema. ");
        	option = stdin.readLine ();
        	System.out.print ("XML File Name: ");
        	xmlfile = stdin.readLine ();
    	} catch (IOException e) {System.err.println ("No xml file name or option");}
        
        ParserWrapper parser = null;
        boolean validation = false;
        boolean schemaValidation = false;
        
		if (option.equalsIgnoreCase("v")) validation = option.equals("v");
		if (option.equalsIgnoreCase("s")) schemaValidation = option.equals("s");
		
		// create parser
		try 
		{
			parser = (ParserWrapper)Class.forName(DEFAULT_PARSER_NAME).newInstance();	
		}
		catch (Exception e) {System.err.println("Unable to instantiate parser");}

		// set parser features
		try 
		{
			parser.setFeature(VALIDATION_FEATURE_ID, validation);
			parser.setFeature(SCHEMA_VALIDATION_FEATURE_ID, schemaValidation);
		} catch (SAXException e) {System.err.println("Parser does not support this validation feature.");}
		
		// parse file
		try 
		{
			Document document = parser.parse (xmlfile);
			DisplayTree treeDisplay = new DisplayTree ();
			treeDisplay.display (document);
			System.out.println ();
		} catch (SAXParseException e) {System.err.println ("SAXParse error.");}
		catch (Exception e) 
		{
			System.err.println("Parse error occurred - "+e.getMessage());
			e.printStackTrace(System.err);
		}
    } // main
  
}  // class DomParser

