复制代码代码如下:
Paket com.test;
java.io.File importieren;
import java.io.FileInputStream;
import java.util.ArrayList;
java.util.List importieren;
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;
öffentliche Klasse SaxXML {
public static void main(String[] args) {
Datei file = new File("e:/People.xml");
versuchen {
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(Leute Leute: peopleList){
System.out.println(people.getId()+"/t"+people.getName()+"/t"+people.getEnglishName()+"/t"+people.getAge());
}
} Catch (Ausnahme e) {
// TODO Automatisch generierter Catch-Block
e.printStackTrace();
}
}
}
Klasse SaxHandler erweitert DefaultHandler {
private List<People> peoples = null;
Privatleute; Menschen;
privater String currentTag = null;
privater String currentValue = null;
private String nodeName = null;
public List<People> getPeoples() {
zurückkehrende Völker;
}
public SaxHandler(String nodeName) {
this.nodeName = nodeName;
}
@Override
public void startDocument() löst SAXException {
// TODO 当读到一个开始标签的时候,会触发这个方法
super.startDocument();
peoples = new ArrayList<People>();
}
@Override
public void endDocument() löst SAXException {
// TODO 自动生成的方法存根
super.endDocument();
}
@Override
public void startElement(String uri, String localName, String name,
Attribute (Attribute) löst SAXException {
// TODO 当遇到文档的开头的时候,调用这个方法
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));
}
sonst if(attributes.getQName(i).equals("en")){
people.setEnglishName(attributes.getValue(i));
}
}
}
currentTag = Name;
}
@Override
öffentliche Leerzeichen (char[] ch, int start, int length)
wirft SAXException {
// TODO 这个方法用来处理在XML文件中读到的内容
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(aktuellerWert);
}
sonst if(currentTag.equals("Alter")){
people.setAge(currentValue);
}
}
}
currentTag = null;
aktueller Wert = null;
}
@Override
public void endElement(String uri, String localName, String name)
wirft SAXException {
// TODO 在遇到结束标签的时候,调用这个方法
super.endElement(uri, localName, name);
if (name.equals(nodeName)) {
peoples.add(people);
}
}
}