/*****************************************************************************
 * This is a generic XML reader
 * It can read any XML file and will display all elements and attributes
 * You can pass different XML files via args[0]
 ****************************************************************************/
import javax.xml.parsers.*;
import org.xml.sax.*;
import org.w3c.dom.*;

public class XMLReader 
{
    public static void main(String args[])
    {
        String arg     = (args.length > 0) ? args[0] : "products.xml";
 
	String XMLfile = "/home/sultans/web/java/demo/xml/" + arg;

        Document doc = readXMLFile(XMLfile);		//Read XML file into DOM object

        displayDOM(doc);				//Traverse DOM and display data 		
    }

    static Document readXMLFile(String XMLFile)
    {
	Document doc = null;		
	try
	{
	    InputSource input           = new InputSource(XMLFile);

	    DocumentBuilderFactory fact = DocumentBuilderFactory.newInstance();			
	    DocumentBuilder DOM         = fact.newDocumentBuilder();
	    doc                         = DOM.parse(input);
	}		
	catch(Exception e)	//catch ParserConfigurationException, SAXException, IOException
	{
	    System.err.println(e);
	    doc = null;
	}
	finally				//in either case (success or failure)
	{
	    return (doc);
	}
    }

    static void displayDOM(Document doc)
    {
	Element  root;

	root  = doc.getDocumentElement();
	System.out.println("The Root Element is: " + root.getNodeName());

        traverseDOM(root);
    }
    
    static void traverseDOM(Node node)
    {
        Node         child, attr;
        NodeList     childList;
        NamedNodeMap attrList;

        int type = node.getNodeType();

        String desc = "Other... ";
        if (type == Node.ELEMENT_NODE)   desc = "Element. ";  
        if (type == Node.ATTRIBUTE_NODE) desc = "Attr.... ";  
        if (type == Node.TEXT_NODE)      desc = "Text.... ";  

        System.out.println(desc + node.getNodeName() + "=" + node.getNodeValue());

        attrList = node.getAttributes();			//get all the attributes
        if (attrList != null)
            for (int i = 0; i < attrList.getLength(); i++)
            {
                attr = attrList.item(i);                        
                System.out.println("Attr.... " + attr.getNodeName() + "=" + attr.getNodeValue());
            }


        childList = node.getChildNodes();			//get all the child elements
        if (childList != null)
            for (int i = 0; i < childList.getLength(); i++)
            {
                child = childList.item(i);                        
                traverseDOM(child);				//call recursively
            }
    }
}