4.4 Structural Events

The ContentHandler interface requests the following structural-oriented methods.

<..a handler for SAX structural events..>
 class MyContentHandler extends DefaultHandler {
     int level=0;
     String docName;
 
   MyContentHandler( String arg0 ){ docName = arg0; }
 
   public void startDocument(){
     System.out.println( docName );
   }
 
   public void startElement(String ns, String sname,
                           String qName, Attributes atts) {
         int i;
      level += 1;
      for(i=0; i<level; i++ ){ System.out.print( "  |"); }
      System.out.println();
      for(i=1; i<level; i++ ){ System.out.print( "  |"); }
      System.out.println( "  +-" + qName );
   }
 
   public void endElement(String ns, String sname, String qName){
      level -= 1;
   }
 }
-_-_-
<?xml version="1.0" encoding="UTF-8"?>  
<document title="red" canvas="yellow">  
  <section>  
    <title>First section</title>  
    <sentence>Some text.</sentence>  
    <sentence>More text.</sentence>  
  </section>  
  <section>  
    <title>Second section</title>  
    <sentence>Another text.</sentence>  
    <sentence>Yet more text.</sentence>  
  </section>  
</document>  
doc.xml  
  |  
  +-document  
  |  |  
  |  +-section  
  |  |  |  
  |  |  +-title  
  |  |  |  
  |  |  +-sentence  
  |  |  |  
  |  |  +-sentence  
  |  |  
  |  +-section  
  |  |  |  
  |  |  +-title  
  |  |  |  
  |  |  +-sentence  
  |  |  |  
  |  |  +-sentence 

<..SAXStruct.java..>
 import java.io.File;
 import javax.xml.parsers.*;
 import org.xml.sax.Attributes;
 import org.xml.sax.XMLReader;
 import org.xml.sax.helpers.DefaultHandler;
 
 class SAXStruct {
   public static void main(String[] args) throws Exception {
     SAXParserFactory factory = SAXParserFactory.newInstance();
     SAXParser saxParser = factory.newSAXParser();
     XMLReader xmlReader = saxParser.getXMLReader();
     xmlReader.setContentHandler( new MyContentHandler( args[0] ) );
     xmlReader.parse( new File(args[0]).toURL().toString() );
 } }
 <.a handler for SAX structural events.>
javac SAXStruct.java; java SAXStruct doc.xml -_-_-