4.6 Access to Attributes

public static void main(String[] args) throws Exception {  
   ....  
   xmlReader.setContentHandler( new MyContentHandler( ... ) );  
   ....  
}  
class MyContentHandler extends DefaultHandler {  
  public void startDocument(){ ... }  
  public void endDocument(){ ... }  
  public void startElement(String ns, String sname,  
                     String qName, Attributes atts) { ... }  
  public void endElement(String ns,  
                        String sname, String qName) { ... }  
  public void characters(char[] ch, int start, int length){ ... }  
}

The Attributes interface shows how attributes of elements may be accessed.

<..a handler accessing SAX attributes..>
 class MyContentHandler extends DefaultHandler {
      String curColor, titleColor, background;
      int y;
 
   public void startElement(String ns, String sname,
                           String qName, Attributes atts) {
      if( qName.equals("document") ){
         if( atts.getLength() != 2 ){ System.err.println("ERROR"); }
         if( !atts.getQName(0).equals("title") ){
                                         System.err.println("ERROR"); }
         titleColor = atts.getValue(0);
         background = atts.getValue( "canvas" );
      }
      curColor = qName.equals("title")? titleColor : "black";
   }
 
   public void characters(char[] ch, int start, int length){
     <.insert colored text and background at distance y.>
   }
 
   public void startDocument(){ <.insert svg header.> }
 
   public void endDocument(){ System.out.println( "</svg>" );
   }
 }
-_-_-
<?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>  
  <rect x="0" y="0" width="100%"  
    height="15" fill="yellow"/>  
  <text x="10" y="15"  
    stroke="red">First section</text>  
  <rect x="0" y="15" width="100%"  
    height="15" fill="yellow"/>  
  <text x="10" y="30"  
    stroke="black">Some text.</text>

-->

Note the wasteful approach used for painting the background!