xml 格式:
<students>
<student id="1" group="1">
<name>张三</name>
<sex>男</sex>
<age>18</age>
<email>zhangsan@163.com</email>
<birthday>1987-06-08</birthday>
<memo>好学生</memo>
</student>
<student id="2" group="2">
<name>李四</name>
<sex>女</sex>
<age>18</age>
<email>lisi@163.com</email>
<birthday>1987-06-08</birthday>
<memo>好学生</memo>
</student>
</students>
xml解析过程:
1. 新建java类 继承 DefaultHandler ,实现里面的方法:startDocument();startElement();characters();endElement();endDocument();
startDocument()和endDocument()整个生命周期只执行一次。开始节点 值 结束节点
public class MySaxParse extends DefaultHandler{
private static ArrayList<Student> list;
private Student student;
private StringBuffer sb;
@Override
public void startDocument() throws SAXException {
super.startDocument();
list = new ArrayList<Student>();
}
@Override
public void startElement(String uri, String localName, String qName,
Attributes attributes) throws SAXException {
super.startElement(uri, localName, qName, attributes);
if(qName.equals("student")){
student = new Student();
int id = Integer.parseInt(attributes.getValue(0));
int group = Integer.parseInt(attributes.getValue(1));
student.setId(id);
student.setGroup(group);
}
}
@Override
public void characters(char[] ch, int start, int length)
throws SAXException {
super.characters(ch, start, length);
sb.append(new String(ch, start, lenth));
}
@Override
public void endElement(String uri, String localName, String qName)
throws SAXException {
super.endElement(uri, localName, qName);
String value = sb.toString();
if(qName.equals("name")){
student.setName(value);
}else if(qName.equals("sex")){
student.setSex(value);
}else if(qName.equals("age")){
student.setAge(Integer.parseInt(value));
}else if(qName.equals("email")){
student.setEmail(value);
}else if(qName.equals("birthday")){
student.setBirthday(value);
}else if(qName.equals("memo")){
student.setMemo(value);
}else if(qName.equals("student")){
list.add(student);
}
sb.setLength(0);
}
@Override
public void endDocument() throws SAXException {
super.endDocument();
}
public static List<Student> getStudent(){
return list;
}
}
2.写SAXParse方法
SAXParserFactory parserFactory = SAXParserFactory.newInstance();
try {
SAXParser saxParser = parserFactory.newSAXParser();
byte[] b = xml.getBytes();
InputStream inputStream = new ByteArrayInputStream(b);
saxParser.parse(inputStream, new MySaxParse());
} catch (Exception e) {
e.printStackTrace();
}