SAX Java implementation learning notes (1)
This article assumes that the reader has a little understanding of XML
First, give a program that compares the basic processing XML file. You don't have to look at it, skip directly. You can return it when you need it.
Echo01.java
Import java.io. *;
Import org.xml.sax. *;
Import org.xml.sax.helpers.defaulthandler;
Import javax.xml.parsers.saxparserfactory;
Import javax.xml.parsers.ParserConfigurationException;
Import javax.xml.parsers.saxparser;
Public class echo01 extends defaulthandler
{
Stringbuffer textbuffer;
Public static void main (String Argv [])
{
IF (argv.length! = 1) {
System.err.Println ("USAGE: CMD FileName);
System.exit (1);
}
// Use an instance of otselves as the sax event handler
DEFAULTHANDLER HANDLER = New Echo01 ();
// use the default (non-validating) PARSER
SAXPARSERFAACTORY FACTORY = SAXPARSERFACTORY.NEWINSTANCE ();
Try {
// set up Output Stream
OUT = New OutputStreamWriter (System.out, "UTF-8");
// Parse the Input
SAXPARSER SAXPARSER = factory.newsaxparser ();
SAXPARSER.PARSE (New file (Argv [0]), HANDLER);
} catch (throwable t) {
T.PrintStackTrace ();
}
System.exit (0);
}
Static Private Writer Out;
/ / =========================================================================================================================================================================================== ===========
// SAX DocumentHandler Methods
/ / =========================================================================================================================================================================================== ===========
Public void startdocument ()
Throws saxception {
Emit (" XML Version = '1.0' Encoding = 'UTF-8'?>");
NL ();
}
Public void enddocument ()
Throws SAXEXCEPTION
{
Try {
NL ();
Out.flush ();
} catch (ioexception e) {
Throw New SaxException ("I / O Error", E);
}
}
Public void startElement (String Namespaceuri,
String sname, // simple name
String Qname, // Qualified Name
Attributes attrs
Throws SAXEXCEPTION
{
ECHOTEXT ();
String ename = sname; // Element Name
IF (".Equals (ename)) ename = qname; // NOT NAMESPACEAWARE
EMIT ("<" ENAME);
IF (attrs! = null) {
For (int i = 0; i String Aname = attrs.getlocalname (i); // attr name IF ("" .Equals (aname)) aname = attrs.getqname (i); Emit (""); Emit (Aname "= /" " Attrs.getValue (i) " / "); } } Emit (">"); } Public void endelement (String Namespaceuri, String sname, // simple name String Qname // Qualified Name ) Throws SAXEXCEPTION { ECHOTEXT (); String ename = sname; // Element Name IF (".Equals (ename)) ename = qname; // NOT NAMESPACEAWARE Emit ("" ""); } Public void characters (char buf [], int offset, int LEN Throws SAXEXCEPTION { String s = new string (buf, offset, len); IF (TextBuffer == Null) { TextBuffer = New StringBuffer (s); } else { TextBuffer.Append (s); } } / / =========================================================================================================================================================================================== =========== // Utility Methods ... / / =========================================================================================================================================================================================== =========== // Display text Accumulated in the Character Buffer Private vid eceotext () Throws SAXEXCEPTION { IF (TextBuffer == Null) Return; String s = "" TextBuffer; Emit (s); TextBuffer = NULL; } // Wrap I / O Exceptions in Sax Exceptions, To // Suit Handler Signature Requirements Private Void Emit (String S) Throws SAXEXCEPTION { Try { Out.write (s); Out.flush (); } catch (ioexception e) { Throw New SaxException ("I / O Error", E); } } // start a new line Private void nl () Throws SAXEXCEPTION { String LinEnd = System.getProperty ("line.separator"); Try { Out.write (LinEnd); } catch (ioexception e) { Throw New SaxException ("I / O Error", E); } } } As can be seen from the program, the core statement parsing an XML file is part of the following: // Use an instance of otselves as the sax event handler DEFAULTHANDLER HANDLER = New Echo01 (); // use the default (non-validating) PARSER SAXPARSERFAACTORY FACTORY = SAXPARSERFACTORY.NEWINSTANCE (); Try { // set up Output Stream OUT = New OutputStreamWriter (System.out, "UTF-8"); // Parse the Input SAXPARSER SAXPARSER = Factory.newsaxParser (); SAXPARSER.PARS (New File), Handler; } catch (throwable t) { T.PrintStackTrace (); } First create an instance of a SaxParserFactory factory class, then create a SAXPARSER by saxparser saxparser = factory.newsaxparser (); this factory class method created a SAXPARSER. Will an XML file (New file (Argv [0])) and a SAX Event Handler (in this program, this handler is actually this class, this class inherits org.xml.sax.helpers.defaulthandler And in front to initialize it: defaulthandler handler = new echo01 ();) passed to it, let it analyze. Processing in the parsing process of the XML file is all implemented in Handler. General Parser accepts two classes of defaulthandler or handlerbase. The class in this example is virtual class inherited the defaulthandler. Look at the picture below: DefaultHandler is a virtual class that implements EntityResolver, DTDHandler, ContentHandler, Errorhandler's four interfaces. The following method is defined: Different methods are called by Parser at different times, (this is Event-break) Detailed introduction: (temporarily) The UML map of Defualthandler is as follows: After reading Handler, go to the head to see Parser, in the code is saxparser (SAXPARSER SAXPARSER) Look carefully the code inside You will find that it doesn't have the work of parsing, but the other two types of XMLReader and Parser to complete the parsing. It turns out that SAXPARSER has only played an Adapter work. UML: