int getAge() { return age; } public void setAge(int age) { this.age = age; } public String getSn() { return sn; } public void setSn(String sn) { this.sn = sn; } }
下面再来完成处理器的代码:
public class MyHandler extends DefaultHandler { private List<Student> studentList; private boolean inStudent = false; private boolean studentName = false; private boolean studentAge = false; private boolean studentSN = false; private Student curStudent ; public MyHandler() { studentList = new ArrayList<Student>(); } @Override public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException { String tagName = localName.length() != 0 ? localName : qName; tagName = tagName.toLowerCase().trim(); if(tagName.equals("student")) { inStudent = true; curStudent = new Student(); } if(inStudent) { if(tagName.equals("name")) { studentName = true; }else if(tagName.equals("age")) { studentAge = true; }else if(tagName.equals("sn")) { studentSN = true; } } } @Override public void endElement(String uri, String localName, String qName) throws SAXException { String tagName = localName.length() != 0 ? localName : qName; tagName = tagName.toLowerCase().trim(); if(tagName.equals("student")) { inStudent = true; studentList.add(curStudent); } if(inStudent) { if(tagName.equals("name")) { studentName = false; }else if(tagName.equals("age")) { studentAge = false; }else if(tagName.equals("sn")) { studentSN = false; } } } @Override public void characters(char[] ch, int start, int length) throws SAXException { if(studentName) { curStudent.setName(curStudent.getName() + new String(ch,start,length)); }else if (studentAge) { curStudent.setAge(Integer.parseInt(new String(ch,start,length))); }else if(studentSN) { curStudent.setSn(curStudent.getSn() + new String(ch, start, length)); } }}
如上面的代码,我们使用了一系列的布尔标志变量来保存文档的遍历状态,先从startElement说起,当我们进入到student节点的时候,我们将inStudent状态设置为true,表示我们已经处于student节点之中,同时创建了一个student对象,相应地,在endElement方法中,我们遇到student结束的时候,会把这个对象添加到我们的studentList中,并将inStudent状态设置为false。同样的,在startElement方法中判断instudent状态,如果当前已经处于student节点中,并且遍历到name,age或