package com.animee.day13.sax;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
import java.util.ArrayList;
import java.util.List;
/**
* Created by Administrator on 2018/1/10.
*/
public class StudentHandler extends DefaultHandler {
private List<Student>list;
private Student student;
private String nowTag;
public List<Student> getList() {
return list;
}
@Override
public void startDocument() throws SAXException {
list = new ArrayList<>();
}
@Override
public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
if (qName.equals("student")) {
student = new Student();
}
nowTag = qName;
}
@Override
public void endElement(String uri, String localName, String qName) throws SAXException {
if (qName.equals("student")) {
list.add(student);
}
nowTag = "";
}
@Override
public void characters(char[] ch, int start, int length) throws SAXException {
String s = new String(ch, start, length);
if (nowTag.equals("id")) {
student.setId(s);
}else if (nowTag.equals("name")) {
student.setName(s);
}else if (nowTag.equals("age")) {
int age = Integer.parseInt(s);
student.setAge(age);
}
}
}
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
import java.util.ArrayList;
import java.util.List;
/**
* Created by Administrator on 2018/1/10.
*/
public class StudentHandler extends DefaultHandler {
private List<Student>list;
private Student student;
private String nowTag;
public List<Student> getList() {
return list;
}
@Override
public void startDocument() throws SAXException {
list = new ArrayList<>();
}
@Override
public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
if (qName.equals("student")) {
student = new Student();
}
nowTag = qName;
}
@Override
public void endElement(String uri, String localName, String qName) throws SAXException {
if (qName.equals("student")) {
list.add(student);
}
nowTag = "";
}
@Override
public void characters(char[] ch, int start, int length) throws SAXException {
String s = new String(ch, start, length);
if (nowTag.equals("id")) {
student.setId(s);
}else if (nowTag.equals("name")) {
student.setName(s);
}else if (nowTag.equals("age")) {
int age = Integer.parseInt(s);
student.setAge(age);
}
}
}