1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113
| import java.util.ArrayList; import java.util.List;
import org.xml.sax.Attributes; import org.xml.sax.SAXException; import org.xml.sax.helpers.DefaultHandler;
import com.lune.bean.Book;
public class SAXParseHandler extends DefaultHandler { private List<Book> list; private Book book;
private String content = null;
@Override public void startDocument() throws SAXException {
super.startDocument(); System.out.println("开始解析xml文件"); list = new ArrayList<Book>(); }
@Override public void endDocument() throws SAXException {
super.endDocument(); System.out.println("xml文件解析完毕"); }
@Override public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
super.startElement(uri, localName, qName, attributes);
if(qName.equals("book")){ book = new Book(); String id = attributes.getValue("id"); book.setId(Integer.parseInt(id)); }
}
@Override public void endElement(String uri, String localName, String qName) throws SAXException {
super.endElement(uri, localName, qName); if(qName.equals("name")){ book.setName(content); }else if(qName.equals("author")){ book.setAuthor(content); }else if(qName.equals("year")){ book.setYear(Integer.parseInt(content)); }else if(qName.equals("price")){ book.setPrice(Double.parseDouble(content)); }else if(qName.equals("book")){ list.add(book); book = null; }
}
@Override public void characters(char[] ch, int start, int length) throws SAXException {
super.characters(ch, start, length);
content = new String(ch, start, length);
}
public List<Book> getBooks(){ return list; }
}
|