Digg StumbleUpon LinkedIn YouTube Flickr Facebook Twitter RSS Reset

Java: Gestionnaire de l’événement SAX*

Java: Gestionnaire de l'événement SAX*
{filelink=8347}

/***** Code de MesExemples.com *******/
/**
 * @(#)EvenementSAX.java
 *
 *
 * @author 
 *sakoba(java.mesexemples.com) @version 1.00 2013/7/4
 */
 
import java.io.File;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.xml.sax.Attributes;
import org.xml.sax.helpers.DefaultHandler;
 
public class EvenementSAX {
  public static void main(String args[]) throws Exception {
    File file = new File("test.xml");
    SAXParserFactory spf = SAXParserFactory.newInstance();
    SAXParser parser = null;
    spf.setNamespaceAware(true);
    spf.setValidating(true);
    System.out.println("Parser will " + (spf.isNamespaceAware() ? "" : "not ")
        + "be namespace aware");
    System.out.println("Parser will " + (spf.isValidating() ? "" : "not ")
        + "validate XML");
 
    parser = spf.newSAXParser();
    System.out.println("Parser object is: " + parser);
 
    MySAXHandler handler = new MySAXHandler();
    parser.parse(file, handler);
  }
}
 
class MySAXHandler extends DefaultHandler {
  public void startDocument() {
    System.out.println("Start document: ");
  }
 
  public void endDocument() {
    System.out.println("End document: ");
  }
 
  public void startElement(String uri, String localName, String qname,
      Attributes attr) {
    System.out.println("Start element: local name: " + localName + " qname: "
        + qname + " uri: " + uri);
  }
 
  public void endElement(String uri, String localName, String qname) {
    System.out.println("End element: local name: " + localName + " qname: "
        + qname + " uri: " + uri);
  }
 
  public void characters(char[] ch, int start, int length) {
    System.out.println("Characters: " + new String(ch, start, length));
  }
 
  public void ignorableWhitespace(char[] ch, int start, int length) {
    System.out
        .println("Ignorable whitespace: " + new String(ch, start, length));
  }
}

Code testé avec le fichier XML Suivant

<?xml version="1.0" encoding="windows-1252"?>
<!-- Edited by MesEXemple.com -->
<note>
	<to>Sakoba</to>
	<from>Adams</from>
	<heading>Rappel</heading>
	<body>Ne m'oubliez pas ce week-end!</body>
</note>