Package com.test;
Import Java.io.File;
Import Java.io.FileInputStream;
Import java.util.ArrayList;
Import java.util.List;
Import Javax.xml.parsers.SAXParser;
Import Javax.xml.parsers.SAXParserFactory;
Import org.xml.sax.Attributes;
Import org.xml.sax.SAXException;
Import Org.xml.sax.helpers.DefaultHandler;
public class Saxxml {
public static void Main (string[] args) {
File File = new file ("E:/people.xml");
try {
SAXParserFactory SPF = saxparserfactory.newinstance ();
SAXParser parser = Spf.newsaxparser ();
Saxhandler handler = new Saxhandler ("people");
Parser.parse (new FileInputStream (file), handler);
list<people> peoplelist = Handler.getpeoples ();
For (people people:peoplelist) {
System.out.println (People.getid () + "\ T" +people.getname () + "T" +people.getenglishname () + "T" +people.getage ());
}
catch (Exception e) {
TODO auto-generated Catch block
E.printstacktrace ();
}
}
}
Class Saxhandler extends DefaultHandler {
Private list<people> peoples = null;
Private people people;
Private String Currenttag = null;
Private String currentvalue = null;
Private String nodename = null;
Public list<people> Getpeoples () {
return peoples;
}
Public Saxhandler (String nodename) {
This.nodename = nodename;
}
@Override
public void Startdocument () throws Saxexception {
TODO triggers this method when you read a start tag
Super.startdocument ();
Peoples = new arraylist<people> ();
}
@Override
public void Enddocument () throws Saxexception {
TODO auto-generated method stubs
Super.enddocument ();
}
@Override
public void Startelement (string uri, String localname, string name,
Attributes Attributes) throws Saxexception {
TODO call this method when it comes to the beginning of the document
Super.startelement (URI, LocalName, name, attributes);
if (Name.equals (nodename)) {
People = new people ();
}
if (attributes!= null && people!= null) {
for (int i = 0; i < attributes.getlength (); i++) {
if (Attributes.getqname (i). Equals ("id")) {
People.setid (Attributes.getvalue (i));
}
else if (attributes.getqname (i). Equals ("en")) {
People.setenglishname (Attributes.getvalue (i));
}
}
}
Currenttag = name;
}
@Override
public void characters (char[] ch, int start, int length)
Throws Saxexception {
TODO This method is used to process the content read in the XML file
Super.characters (CH, start, length);
if (Currenttag!= null && people!= null) {
CurrentValue = new String (CH, start, length);
if (currentvalue!= null &&!currentvalue.trim (). Equals ("") &&!currentvalue.trim (). Equals ("\ n")) {
if (Currenttag.equals ("Name")) {
People.setname (CurrentValue);
}
else if (currenttag.equals ("Age")) {
People.setage (CurrentValue);
}
}
}
Currenttag = null;
CurrentValue = null;
}
@Override
public void EndElement (string uri, String localname, string name)
Throws Saxexception {
TODO calls this method when it encounters an end tag
Super.endelement (URI, LocalName, name);
if (Name.equals (nodename)) {
Peoples.add (people);
}
}
}