// Dom1.java
//
// Parse un document XML produit un arbre DOM
// Parsing validant
// et TreeWalker

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.FactoryConfigurationError;
import javax.xml.parsers.ParserConfigurationException;

import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;

import java.io.File;
import java.io.IOException;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.DOMException;

public class Dom1
{
  public static void main (String argv [])
            throws IOException
    {
     if (argv.length != 1) {
        System.err.println ("Usage: cmd filename");
        System.exit (1);
    }
    DocumentBuilderFactory factory =
                          DocumentBuilderFactory.newInstance();
    try {
      DocumentBuilder builder = factory.newDocumentBuilder();
      Document document = builder.parse( new File(argv[0]) );
      Element  rootElement =  document.getDocumentElement () ;
      printDomTree (rootElement, "");
    } catch (Throwable t) {
      t.printStackTrace ();
      System.exit (1);
    }
    System.exit (0);
  }

  public static void printDomTree (Node node, String indent)
    { String type;
      switch (node.getNodeType()) {
        case Node.ATTRIBUTE_NODE :
                        type = "attribut"; break;
        case Node.CDATA_SECTION_NODE :
                        type = "CDATA"; break;
        case Node.COMMENT_NODE :
                        type = "comment"; break;
        case Node.DOCUMENT_FRAGMENT_NODE :
                        type = "document fragment"; break;
        case Node.DOCUMENT_NODE :
                        type = "document"; break;
        case Node.DOCUMENT_TYPE_NODE :
                        type = "document type"; break;
        case Node.ELEMENT_NODE :
                        type = "node"; break;
        case Node.ENTITY_NODE :
                        type = "entity"; break;
        case Node.ENTITY_REFERENCE_NODE :
                        type = "entity reference"; break;
        case Node.NOTATION_NODE :
                        type = "notation"; break;
        case Node.PROCESSING_INSTRUCTION_NODE :
                        type = "processing instruction"; break;
        case Node.TEXT_NODE :
                        type = "text"; break;
        default : type = "none";
      }
      System.out.println(indent+"type : " + type);
      System.out.println(indent+"noeud name  : "+node.getNodeName());
      System.out.println(indent+"value : "+node.getNodeValue());
      if (node.hasChildNodes())  {
        Node nextFils = node.getFirstChild();
       while (nextFils != null) {
           printDomTree (nextFils,  indent+" ");
           nextFils = nextFils.getNextSibling();
      }
      }
    }
  }
