import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
import com.newer.xml.dom.Book;
public class Test {
static class BookHandler extends DefaultHandler {
List<Book> list = new ArrayList<Book>();//创建一个列表
private Book book;
private String tagName;
public List<Book> getList() {
return list;
}
@Override
public void startElement(String uri, String localName, String qName,
Attributes attributes) throws SAXException {
super.startElement(uri, localName, qName, attributes);
System.out.println("开始:" + qName);
if (qName.equals("book")) {
book = new Book();
// 获取book节点上的isbn属性值
book.setIsbn(attributes.getValue(0));
}
this.tagName = qName;
}
@Override
public void endElement(String uri, String localName, String qName)
throws SAXException {
// TODO Auto-generated method stub
super.endElement(uri, localName, qName);
System.out.println("结束:" + qName);
if (qName.equals("book")) {
list.add(book);
}
this.tagName = null;
}
@Override
public void characters(char[] ch, int start, int length)
throws SAXException {
// TODO Auto-generated method stub
super.characters(ch, start, length);
System.out.println("文本:" + new String(ch, start, length));
if (tagName != null) {
String data = new String(ch, start, length);
if (tagName.equals("title")) {
book.setTitle(data);
}
if (tagName.equals("author")) {
book.setAuthor(data);
}
}
}
}
public static void main(String[] args) {
// SAXParser parser = SAXParserFactory.newInstance().newSAXParser();
try {
SAXParserFactory factory = SAXParserFactory.newInstance();
SAXParser parser = factory.newSAXParser();
File f = new File("c:/books.xml");
BookHandler bookHandler = new BookHandler();
// 开始解析
parser.parse(f, bookHandler);
System.out.println(bookHandler.getList());
} catch (ParserConfigurationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SAXException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Book类
public class Book {
private String title;
private String isbn;
private String author;
public Book() {
super();
// TODO Auto-generated constructor stub
}
public Book(String title, String isbn, String author) {
super();
this.title = title;
this.isbn = isbn;
this.author = author;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getIsbn() {
return isbn;
}
public void setIsbn(String isbn) {
this.isbn = isbn;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
@Override
public String toString() {
return "Book [title=" + title + ", isbn=" + isbn + ", author=" + author
+ "]";
}
}