book.xml
<?xml version="1.0" encoding="UTF-8" standalone="no"?><书架>
<书>
<书名>水浒传</书名>
<作者>吴承恩</作者>
<价格>109</价格>
</书>
<书>
<书名>三国演义</书名>
<作者>罗贯中</作者>
<价格>33</价格>
</书>
</书架>
package po;
public class Book {
private String bookname;
private String author;
private String price;
public String getBookname() {
return bookname;
}
public void setBookname(String bookname) {
this.bookname = bookname;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
public String getPrice() {
return price;
}
public void setPrice(String price) {
this.price = price;
}
}
package sax;
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.XMLReader;
import org.xml.sax.helpers.DefaultHandler;
import po.Book;
public class XMLToObjectBySAX {
/**
* 开发中经常使用的SAX将XML文档中的片段封装成对象
* @throws SAXException
* @throws ParserConfigurationException
* @throws IOException
*/
public static void main(String[] args) throws ParserConfigurationException, SAXException, IOException {
//create SAXParserFactory
SAXParserFactory factory=SAXParserFactory.newInstance();
SAXParser parser=factory.newSAXParser();
XMLReader reader=parser.getXMLReader();
ListObjectHandler handler=new ListObjectHandler();
reader.setContentHandler(handler);
reader.parse("src/book.xml");
List<Book> list=handler.getList();
for(Book b:list){
System.out.println(b.getBookname()+" "+b.getAuthor()+" "+b.getPrice());
}
}
}
//该处理器的功能就是将xml文档中的标签封装成Book对象
class ListObjectHandler extends DefaultHandler{
private List<Book> list=new ArrayList<Book>();
private String currentTag;
private Book book;
public List<Book> getList() {
return list;
}
public void setList(List<Book> list) {
this.list = list;
}
@Override
public void startElement(String arg0, String arg1, String arg2,
Attributes arg3) throws SAXException {
currentTag=arg2;
if("书".equalsIgnoreCase(currentTag)){
book=new Book();
}
}
@Override
public void characters(char[] arg0, int arg1, int arg2) throws SAXException {
if("书名".equalsIgnoreCase(currentTag)){
book.setBookname(new String(arg0,arg1,arg2));
}else if("作者".equalsIgnoreCase(currentTag)){
book.setAuthor(new String(arg0,arg1,arg2));
}else if("价格".equalsIgnoreCase(currentTag)){
book.setPrice(new String(arg0,arg1,arg2));
}
}
@Override
public void endElement(String arg0, String arg1, String arg2)
throws SAXException {
if(arg2.equalsIgnoreCase("书")){
list.add(book);
book=null;
}
currentTag=null;
}
}