<?xml version="1.0" encoding="utf-8"?>
<书架>
<书>
<书名>JAVA就业培训教材</书名>
<作者>张孝祥</作者>
<价格>39.00</价格>
</书>
<书>
<书名>SaxJDK7.0全解</书名>
<作者>哈哈</作者>
<价格>90.00</价格>
</书>
</书架>
package XML及其操作;
public class Book {
private String name;
private String author;
private String price;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
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 XML及其操作;
import java.util.ArrayList;
import java.util.List;
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;
public class Xml的Sax解析方式并封装到Bean {
public static void main(String[] args) throws Exception{
//1.创建解析工厂
SAXParserFactory sf = SAXParserFactory.newInstance();
//2.创建解析器
SAXParser sp = sf.newSAXParser();
//3.得到读写器
XMLReader xr = sp.getXMLReader();
//4.设置内容处理器
BeanListHandler bh = new BeanListHandler();
xr.setContentHandler(bh);
//5.读取xml文档
xr.parse("src/XML及其操作/Sax解析.xml");
List <Book> list = bh.getList();
System.out.println(list);
}
}
/**
* 把xml文档中的每一本书封装到一个book对象中,并把多个 book对象放到一个list集合对象中返回
*
* @author Administrator
*
*/
class BeanListHandler extends DefaultHandler {
private Book book;
private List <Book> list = new ArrayList <Book> ();
private String currentTag;
@Override
public void startElement(String uri, String localName, String qName,
Attributes attributes) throws SAXException {
currentTag = qName;
if("书".equals(currentTag)){
book = new Book();
}
}
@Override
public void endElement(String uri, String localName, String qName)
throws SAXException {
currentTag = null;
if("书".equals(qName)){
list.add(book);
book = null;
}
}
@Override
public void characters(char[] ch, int start, int length)
throws SAXException {
if("书名".equals(currentTag)){
String name = new String(ch , start , length);
book.setName(name);
}
if("作者".equals(currentTag)){
String author = new String(ch , start , length);
book.setAuthor(author);
}
if("价格".equals(currentTag)){
String price = new String(ch , start , length);
book.setPrice(price);
}
}
public List <Book> getList(){
return list;
}
}