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 );
}
}
闽公网安备 35060202000074号