xml文档-book.xml
<?xml version="1.0" encoding="UTF-8"?>
<书架>
<书>
<书名>Java就业基础教程</书名>
<作者>张孝祥</作者>
<售价>59</售价>
</书>
<书>
<书名>JavaScript网页开发</书名>
<作者>黎活明</作者>
<售价>46</售价>
</书>s
</书架>
程序实现:获得两本书的数据(书名、作者、售价)保存到List集合中
封装数据的Book类
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;
}
}
主运行的Sax类
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;
public class Sax {
public static void main(String[] args) throws ParserConfigurationException, Exception {
//1.得到工厂
SAXParserFactory factory = SAXParserFactory.newInstance();
//2.创建解析器
SAXParser sp = factory.newSAXParser();
//3.获得读取器
XMLReader reader = sp.getXMLReader();
//4.设置内容处理器
BookListHandler handler = new BookListHandler();
reader.setContentHandler(handler);
//5.读取xml文档
reader.parse("src/book.xml");
//6.得到xml文档内容
List books = handler.getBooks();
System.out.println(books);
}
}
class BookListHandler extends DefaultHandler{
List books = new ArrayList();
String currentNode = null;
Book book = null;
@Override
public void startElement(String uri, String localName, String name,
Attributes attributes) throws SAXException {
currentNode = name;
if("书".equals(name)){
book = new Book();
}
}
@Override
public void characters(char[] ch, int start, int length)
throws SAXException {
String value = new String(ch,start,length);
if("书名".equals(currentNode)){
book.setName(value);
}
if("作者".equals(currentNode)){
book.setAuthor(value);
}
if("售价".equals(currentNode)){
book.setPrice(value);
}
}
@Override
public void endElement(String uri, String localName, String name)
throws SAXException {
if("书".equals(name)){
books.add(book);
book = null;
}
currentNode = null;
}
public List getBooks(){
return books;
}
}