// Analyse3.java
//
// Parse avec l'Api SAX un document XML 
// fait echo des constituants du document XML

import java.io.*;
import org.xml.sax.*;
import org.xml.sax.helpers.DefaultHandler;
import javax.xml.parsers.SAXParserFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;

public class Analyse3 extends DefaultHandler {
  static private FileWriter dest;
  public static void main (String argv[])
  throws IOException {
    if (argv.length != 2) {
      System.err.println
         ("Usage: Analyse3 fichierSource fichierCible");
      System.exit (1);
    }
    File fichierDest = new File(argv[1]);
    dest = new FileWriter(fichierDest);
    DefaultHandler handler = new Analyse3();
    SAXParserFactory factory = SAXParserFactory.newInstance();
    try {
      SAXParser saxParser = factory.newSAXParser();
      saxParser.parse( new File(argv[0]), handler );
    } catch (Throwable t) {
      t.printStackTrace ();
      System.exit (2);
    }
    System.exit (0);
  }

  public void error(SAXParseException e)
  throws SAXParseException
  {
    throw e;
  }

  public void startDocument ()
  throws SAXException {
    ecrit("startDocument");
    nl();
  }

  public void endDocument ()
  throws SAXException {
    ecrit("endDocument");
    nl();
  }

  public void startElement (String namespaceURI,
                             String simpleName,
                             String qualifiedName,
                             Attributes attrs)
    throws SAXException {
    String  elementName = simpleName;
    if (elementName.equals(""))
      elementName = qualifiedName;
    ecrit("startElement : "+ elementName);
    nl();
  }

  public void endElement (String namespaceURI,
                           String simpleName,
                           String qualifiedName)
  throws SAXException {
    String  elementName = simpleName;
    if (elementName.equals(""))
      elementName = qualifiedName;
    ecrit("endElement : "+ elementName);
    nl();
  }

  public void characters (char buf [], int offset, int len)
  throws SAXException {
    String s = new String(buf, offset, len);
    ecrit (s);
    nl();
  }

  private void nl()
  throws SAXException {
    String lineEnd =  System.getProperty("line.separator");
    try {
      dest.write (lineEnd);
    } catch (IOException e) {
      throw new SAXException ("I/O error", e);
    }
  }

  private void ecrit(String s)
  throws SAXException {
    try {
      dest.write (s);
      dest.flush ();
    } catch (IOException e) {
      throw new SAXException ("I/O error", e);
    }
  }

}

