private List<Book> bookList = new ArrayList<Book>();
// 返回集合
public List<Book> getBookList() {
return bookList;
}
// 保存当期的开始标签
private String currentTag;
// 封装当前书对象
Book book;
// 开始标签
public void startElement(String uri, String localName, String qName,
Attributes attributes) throws SAXException {
this.currentTag = qName;
// 每次读取的书的开始标签的时候,创建对象
if ("书".equals(qName)) {
book = new Book();
for(int i=0;attributes!=null&&i<attributes.getLength();i++){
String attrName = attributes.getQName(i);
String attrValue = attributes.getValue(i);
if("编号".equals(attrName)){
book.setNo(attrValue);
}
}
}
//获取属性,把书的编号封装到书对象里
}
// 内容
public void characters(char[] ch, int start, int length)
throws SAXException {
// characters(c,2,2);
// 读取到的内容
String content = new String(ch, start, length);
// 封装book对象
// 判断
if ("书名".equals(currentTag)) {
book.setBookName(content);
} else if ("作者".equals(currentTag)) {
book.setAuthor(content);
} else if ("售价".equals(currentTag)) {
book.setPrice(Double.parseDouble(content));
}
}
// 结束标签
public void endElement(String uri, String localName, String qName)
throws SAXException {
// 把book对象添加到集合
if ("书".equals(qName)) {
bookList.add(book);
book = null;// 建议gc回收资源
}
// 重置开始标签
currentTag = null;
}
// 返回集合
public List<Book> getBookList() {
return bookList;
}
// 保存当期的开始标签
private String currentTag;
// 封装当前书对象
Book book;
// 开始标签
public void startElement(String uri, String localName, String qName,
Attributes attributes) throws SAXException {
this.currentTag = qName;
// 每次读取的书的开始标签的时候,创建对象
if ("书".equals(qName)) {
book = new Book();
for(int i=0;attributes!=null&&i<attributes.getLength();i++){
String attrName = attributes.getQName(i);
String attrValue = attributes.getValue(i);
if("编号".equals(attrName)){
book.setNo(attrValue);
}
}
}
//获取属性,把书的编号封装到书对象里
}
// 内容
public void characters(char[] ch, int start, int length)
throws SAXException {
// characters(c,2,2);
// 读取到的内容
String content = new String(ch, start, length);
// 封装book对象
// 判断
if ("书名".equals(currentTag)) {
book.setBookName(content);
} else if ("作者".equals(currentTag)) {
book.setAuthor(content);
} else if ("售价".equals(currentTag)) {
book.setPrice(Double.parseDouble(content));
}
}
// 结束标签
public void endElement(String uri, String localName, String qName)
throws SAXException {
// 把book对象添加到集合
if ("书".equals(qName)) {
bookList.add(book);
book = null;// 建议gc回收资源
}
// 重置开始标签
currentTag = null;
}