This example shows how to use SAX interface to parse XML documents
Here is the document I want to analyze Emp.xml
XML Version = "1.0"?>
The development environment I use is JBuilder5, the following is the Java program.
Import java.io.ioException; import org.xml.sax. *; import org.xml.sax.helpers. *; import org.apache.xerces.parsers.saxparser; import java.util.stack;
Public class xmltohtml extends defaulthandler {
String strname; string strsex; string strimage;
private Stack stackName = new Stack (); private Stack stackAge = new Stack (); private Stack stackSex = new Stack (); private Stack stackTel = new Stack (); private Stack stackImage = new Stack (); private int flag;
Public static void main (string [] argv) {
IF (argv.Length! = 1) {system.out.println ("USAGE: Java XmlToHtml [URI]); system.exit (0);} string uri = argv [0];
try {XMLReader parser = XMLReaderFactory.createXMLReader ( "org.apache.xerces.parsers.SAXParser"); XmlToHtml XmlToHtmlInstance = new XmlToHtml (); parser.setContentHandler (XmlToHtmlInstance); parser.parse (uri);} catch (IOException ioe) {IOE.PrintStackTrace ();} catch (saxException SAXE) {SAXE.PRINTSTACKTRACE ();
} Public void character, int = new string (CH, start, length); if (CH [0] == '/ n') return; if (Flag == 1) {stackname.push (s);} else if (flag == 2) {stackage.push (s);} else if (flag == 3) {stacksex.push (s);} else IF FLAG == 4) {stacktel.push (s);} else if (flag == 5) {stackimage.push (s);}} public void enddocument () throws saxception {for (int count = stackname.size) -1; count> = 0; count -) {
String strName = stackName.elementAt (count) .toString (); String strAge = stackAge.elementAt (count) .toString (); String strSex = stackSex.elementAt (count) .toString (); String strTel = stackTel.elementAt (count ) .tostring (); string strimage = stackimage.elease.ementat (count) .tostring (); system.out.println (strname " strage " strsEx " strttel " strimage ""); // Output Western data}}}
public void startElement (String uri, String localName, String qName, Attributes attributes) throws SAXException {if (localName.equals ( "name")) {flag = 1;} else if (localName.equals ( "age")) {flag = 2;} else if ("sex")) {flag = 3;} else if (localname.equals ("tel")) {Flag = 4;} else if (localname.equals ("IMG" )) {FLAG = 5;}
}