package dom;
import java.lang.reflect.Method;

import java.io.*;
import org.w3c.dom.*;

import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;

public class DisplayTree
{	
	/** Writes the specified node, recursively. */
    public void display (Node node) 
	{
		if (node == null) return; // End of recursion
		short type = node.getNodeType();
		displayNode (node, type);
		Node child = node.getFirstChild();
		while (child != null) 
		{
			display (child); // Recursive call.
			child = child.getNextSibling();
		}
		
        if (type == Node.ELEMENT_NODE) // end-tag
            System.out.print("</" + node.getNodeName() + ">");
    } // display (Node)
    
    protected void displayNode (Node node, short type)
    {
		if (type == Node.DOCUMENT_NODE) // xml declaration
		{
			displayDocNode (node);
			Document document = (Document)node;
			node = document.getDocumentElement();
		}
		else
		if (type == Node.ELEMENT_NODE) //start-tag
			displayElementNode (node);
		else
		if (type == Node.TEXT_NODE) //text
			System.out.print(node.getNodeValue());	
    } // displayNode
    
    protected void displayDocNode (Node node)
    {
    	Document document = (Document)node;
    	String version = null;
    	try 
        {
            Method getXMLVersion = document.getClass().getMethod("getXmlVersion", new Class[]{});
            // If Document class implements DOM L3, this method will exist.
            if (getXMLVersion != null) 
                version = (String) getXMLVersion.invoke(document, null);
        } catch (Exception e) {}
        
		if (version.equals("1.1")) {System.out.println("<?xml version=\"1.1\" encoding=\"UTF-8\"?>");}
		else {System.out.println("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");}
    } // displayDocNode
    
    protected void displayElementNode (Node node)
    {
    	System.out.print("<" + node.getNodeName ()); 
		// display attributes       
		NamedNodeMap attrs = node.getAttributes ();                                           
		for (int count = 0; count < attrs.getLength (); count++) 
		{
			Attr attr = (Attr)attrs.item(count);
			System.out.print(" " + attr.getNodeName() + "=\"" + attr.getNodeValue () + "\"");	
		}
		System.out.print('>');           
    } // displayElementNode	
} // TreeDisplayClass
