<s1 title="SAX Parsing">

<p>SAX parsers use a callback mechanism to parse XML.  Applications
register a <var/ContentHandler/> to receive the parsing events.  Although
this is a little more complicated, it's more efficient because there's
no need to build any data structures.</p>

<p>Because Sun's JAXP API only supports SAX 1.0, the following example
instantiates the Resin parser directly.  Of course, if you want to parse
HTML with a SAX API, you'll need to instantiate <var/Html/> instead.</p>

<p>The following example just prints the element names, properly indented,
as they're parsed.</p>

<example title="Input File">
&lt;top>
  &lt;a/>
  &lt;b>
    &lt;b1/>
    &lt;b2/>
  &lt;/b>
  &lt;c/>
&lt;/top>
</example>

<p><var/DefaultHandler/> is a convenient abstract implementation of the
SAX handler APIs.  By extending <var/DefaultHandler/>, you can just
implement the methods your application needs.</p>

<p>The SAX parser will call <var/startElement()/> when it finishes
parsing the open tag.  In this case, I'm ignoring the namespace junk
and just using the tag name, <var/qName/>.</p>

<p>The <var/endElement()/> callback just decrements the depth to get
the correct value.</p>

<example title="SAX Handler Class">
import java.io.*;
import org.xml.sax.*;
import org.xml.sax.helpers.DefaultHandler;
import com.caucho.xml.*;

public class MyHandler extends DefaultHandler {
  int depth;

  public void startElement(String namespaceURI, String localName,
                           String qName, Attributes atts)
  {
    for (int i = 0; i < depth; i++)
      System.out.print(" ");

    System.out.println(qName);

    depth += 2;
  }

  public void endElement(String namespaceURI, String localName,
                         String qName)
  {
    depth -= 2;
  }
}
</example>

<p>To parse with SAX, you must register your handler
using <var/setContentHandler/>.</p>

<example title="Parsing using SAX">
// Create a new parser
Xml xml = new Xml();

xml.setContentHandler(new MyHandler());

xml.parse("test.xml");
</example>

<p>And the result looks like:</p>
<results>
top
  a
  b
    b1
    b2
  c
</results>
</s1>