Java核心代码例程之:(JAXP) SAX

发表于:2007-06-22来源:作者:点击数: 标签:
importjavax.xml.parsers.*; importorg.xml.sax.*; /** *SAXDemousesJA XP toa cq uireaSAXparsertoparseanXMLfile. *TheexampleXMLfilerepresentsashoppingcart. * *ThefollowingJARsmustbeinyourCLASSPATH: *-jaxp.jar *-xerces.jar(forSAXparserimplement

   
import javax.xml.parsers.*;
import org.xml.sax.*;


/**
 * SAXDemo uses JAXP to acquire a SAX parser to parse an XML file.

 * The example XML file represents a shopping cart.
 *
 * The following JARs must be in your CLASSPATH:
 * - jaxp.jar
 * - xerces.jar (for SAX parser implementation)
 *
 * Download JAXP (which includes these JARs) here: http://java.sun.com/xml/
 * Find additional Xerces info here: http://xml.apache.org/
 *
 * Note: Unlike DOM, SAX parsing does not load the XML file into memory.
 * SAX parsers traverse the XML file and report parse "events" to an event handler.
 **/

 public class SAXDemo
  extends org.xml.sax.HandlerBase
{

  /**
   * main creates and runs a SaxTest instance.
   **/
  public static void main( String[] args )
  {
    SAXDemo me = new SAXDemo();
    me.run();
  }


  public void run()
  {
    try
    {
      SAXParserFactory factory = SAXParserFactory.newInstance();
      log( "SAXParserFactory classname: " + factory.getClass().getName() );

      SAXParser saxParser = factory.newSAXParser();
      log( "SAXParser classname: " + saxParser.getClass().getName() );

      /*
      The SAXParser.parse method initiates parsing of the XML file.
      The second parameter specifies which class will handle parse events.
      This class must extend org.xml.sax.HandlerBase
      **/
      saxParser.parse( "cart.xml", this );
    }
    catch( Exception e )
    {
      e.printStackTrace();
    }
  }

  /**
   * log simply prints the specified message to System.out
   **/
  public void log( String message )
  {
    System.out.println( message );
  }


  /**
   * SAXParser calls startDocument() when it starts parsing a document
   **/
  public void startDocument ()
    throws SAXException
  {
    log( "Start SAX parse" );
  }

  /**
   * SAXParser calls endDocument() when it finishes parsing a document
   **/
  public void endDocument ()
    throws SAXException
  {
    log( "End SAX parse" );
  }

  /**
   * SAXParser calls startElement() when it encounters an opening element tag (eg <item>)
   **/
  public void startElement (String name, AttributeList attrs)
    throws SAXException
  {
    log( "<" + name + ">" );
  }

  /**
   * SAXParser calls endElement() when it encounters a closing element tag (eg </item>)
   **/
  public void endElement (String name)
    throws SAXException
  {
    log( "</" + name + ">" );
  }

  /**
   * SAXParser calls characters() when it encounters text outside of any tags
   **/
  public void characters(char[] p0, int p1, int p2)
    throws SAXException
  {
    String str = new String( p0, p1, p2 ).trim();
    if( str.length() > 0 )
      log( str );
  }


}

原文转自:http://www.ltesting.net