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;
}
XML解析书籍信息
本文介绍了一个使用SAX解析XML文件中书籍数据的例子。通过监听开始标签、内容和结束标签事件,实现了从XML中读取书籍的编号、名称、作者及价格,并将这些信息存储为Book对象,最终收集所有书籍信息到一个列表中。
7145

被折叠的 条评论
为什么被折叠?



