1 package itcast.sax;
2
3 import java.util.ArrayList;
4 import java.util.List;
5
6 import org.xml.sax.Attributes;
7 import org.xml.sax.SAXException;
8 import org.xml.sax.helpers.DefaultHandler;
9
10 //把xml文档中的每一本封装到一个book对象,并把多个book对象放在一个list集合中
11 public class BeanListHandler extends DefaultHandler {
12
13 private List list = new ArrayList();
14 private String currentTag;
15 private Book book;
16
17 @Override
18 public void characters(char[] ch, int start, int length)
19 throws SAXException {
20 if("bookname".equals(currentTag)){
21 String bookname = new String(ch,start,length);
22 book.setName(bookname);
23 }
24 if("editor".equals(currentTag)){
25 String author = new String(ch,start,length);
26 book.setAuthor(author);
27 }
28 if("price".equals(currentTag)){
29 String price = new String(ch,start,length);
30 book.setPrice(price);
31 }
32 }
33
34 @Override
35 public void endElement(String uri, String localName, String name)
36 throws SAXException {
37 if(name.equals("书")){
38 list.add(book);
39 book=null;
40 }
41 currentTag = null;
42 }
43
44 @Override
45 public void startElement(String uri, String localName, String name,
46 Attributes attributes) throws SAXException {
47
48 currentTag=name;
49 if("书".equals(currentTag)){
50 book = new Book();
51 }
52
53 }
54
55 public List getList() {
56 return list;
57 }
58
59 }