/**
 * @author Matthias Ferdinand
 */


import java.io.IOException;

import org.apache.xerces.impl.xs.psvi.XSTypeDefinition;
import org.apache.xerces.parsers.DOMParser;
import org.apache.xerces.xni.psvi.ElementPSVI;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
import org.xml.sax.SAXNotRecognizedException;
import org.xml.sax.SAXNotSupportedException;
import org.xml.sax.SAXParseException;


public class PSVIExample {

  Document xml;	
	DOMParser parser;		
	
	// constructor
	PSVIExample(String xml_file) {
		prepareParser();				
		readFile(xml_file);	
		traverse(xml);
	}


	private void prepareParser()
	{
		parser = new DOMParser();

		try {
			parser.setFeature("http://xml.org/sax/features/validation", true);
			parser.setFeature("http://apache.org/xml/features/validation/schema", true);
			parser.setFeature("http://apache.org/xml/features/dom/include-ignorable-whitespace", false);
			parser.setProperty("http://apache.org/xml/properties/dom/document-class-name", 
			                   "org.apache.xerces.dom.PSVIDocumentImpl");			                  
		}
		catch (SAXNotRecognizedException e) {
            System.err.println (e);
    } 
    catch (SAXNotSupportedException e) {
            System.err.println (e);
    }		
	}
	
	
	private void readFile(String xml_file) {
	
		try {	
			parser.parse(xml_file);
			xml = parser.getDocument();			
		}	 
		catch (SAXParseException spe) {
			spe.printStackTrace();
		}
		catch (SAXException se) {
			se.printStackTrace();
		}		
		catch (IOException ioe) {
			ioe.printStackTrace();
		}			
	}	
	
  
	private void traverse(Node node)
	{
		// traverse DOM tree	
		// process element
    if (node.getNodeType() == Node.ELEMENT_NODE)
    {
    	Element elem = (Element) node;
    	System.out.println("\nElement: "+elem.getNodeName());    	    	    
    
      // get type of element from PSVI
      XSTypeDefinition type = ((ElementPSVI) elem).getTypeDefinition();
      
    	// output type information
    	if(type!=null)
    	{
    		System.out.print("  type = ");
    		if(type.getNamespace()!=null)
    		{
    			System.out.println(type.getNamespace()+":");
    		}
    		System.out.println(type.getName()+" ");    		
    	}
    }        
    
    // if any, process children recursively
    NodeList children = node.getChildNodes();    
    if (children != null) 
    {    	
    	for (int i=0; i< children.getLength(); i++)
        traverse(children.item(i));           
    }	
	}	
		
	
	public static void main(String[] args) {
		if(args.length != 1) 
		{
			System.err.println("Usage: java PSVIExample XML_filename");
			System.exit(1);
		}
		new PSVIExample(args[0]);		
	}
	
}