| 12
 3
 4
 5
 6
 7
 8
 9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 
 |  
 
import org.xml.sax.*;
import org.xml.sax.helpers.DefaultHandler;
import javax.xml.parsers.SAXParserFactory;
import javax.xml.parsers.SAXParser;
import java.io.*;
 
public class AnalyseSAX extends DefaultHandler {
  public static void main (String args[]) throws IOException {
      //Si l'utilisateur a oublié de passer
      //le nom du fichier XML en parametre => erreur
      if (args.length != 1) {
          System.err.println("Usage: AnalyseSAX fichierSourceXML");
          System.exit (1);
      }
      //on lance l'analyseur avec le fichier XML en parametre
      DefaultHandler handler = new AnalyseSAX();
      SAXParserFactory factory = SAXParserFactory.newInstance();
      try {
          SAXParser saxParser = factory.newSAXParser();
          saxParser.parse( new File(args[0]), handler );
      } catch (Throwable t) {
          //Si on a une erreur pendant l'analyse
          t.printStackTrace ();
          System.exit (1);
      }
      System.exit (0);
  }
 
 
  public void error(SAXParseException e) throws SAXParseException{
      throw e;
  }
 
  public void startDocument () throws SAXException {
      System.out.println("début du document");
  }
 
  public void endDocument () throws SAXException {
      System.out.println("fin du document");
  }
 
  public void startElement (String namespaceURI,String simpleName,String qualifiedName,Attributes attrs) throws SAXException {
      String nomElement = simpleName;
      if (nomElement.equals("")) nomElement = qualifiedName;
 
      System.out.println("startElement : "+ nomElement);
  }
 
  public void endElement (String namespaceURI,String simpleName,String qualifiedName) throws SAXException {
      String nomElement = simpleName;
      if (nomElement.equals("")){
          nomElement = qualifiedName;
      }
      System.out.println("endElement : "+ nomElement);
  }
 
  public void characters (char buf [], int offset, int len)
      throws SAXException {
      String s = new String(buf, offset,len);
      System.out.println (s);
  }
 
 
} | 
Partager