事件处理器,断点跟踪到characters方法为什么程序不朝下跑了?
1.新建一个Student类,成员变量name,location,grade(为了方便,grade可以是String)2.xml文件,exam.xml
<?xml version="1.0" encoding="UTF-8"?>
<exam>
<student>
<name>李四</name>
<location>沈阳</location>
<grade>59</grade>
</student>
<student>
<name>的</name>
<location>队伍</location>
<grade>34343</grade>
</student>
</exam>
3.问题代码
public class Xml封装对象返回List {
@Test
public void Test() throws Exception, SAXException {
SAXParserFactory factory = SAXParserFactory.newInstance();
SAXParser sp = factory.newSAXParser();
XMLReader reader = sp.getXMLReader();
MyHandle h = new MyHandle();
reader.setContentHandler(h);
reader.parse("src/exam.xml");
List<Student> list = h.getList();
System.out.println(list.get(1));
}
class MyHandle extends DefaultHandler {
private List list = new ArrayList();// 解析到一本书就放在list集合里面
private String currentTag;// 记住解析到的是什么标签
private Student student;
public List getList() {
return list;
}
public void startElement(String uri, String localName, String name,
Attributes attributes) throws SAXException {
currentTag = name;
if (currentTag.equals("student")) {
student = new Student();
}
}
public void characters(char[] ch, int start, int length)
throws SAXException {
if (currentTag.equals("name")) {
String names = new String(ch, start, length);
student.setNane(names);
}
if (currentTag.equals("location")) {
String location = new String(ch, start, length);
student.setLocation(location);
}
if (currentTag.equals("grade")) {
String grade = new String(ch, start, length);
student.setGrade(grade);
}
}
public void endElement(String uri, String localName, String named)
throws SAXException {
if (named.equals("student")) {
list.add(student);
}
currentTag = null;
}
}
}