SAX解析xml文件,将解析出来的结果放到一个bean中,再将所有的baen放到list列表中
例子程序的xml文件为:
- <?xml version="1.0" encoding="UTF-8"?>
- <书架>
- <书>
- <书名>海的女儿</书名>
- <作者>安徒生</作者>
- <售价>50.0元</售价>
- </书>
- <书>
- <书名>卖火柴的小女孩</书名>
- <作者>安徒生</作者>
- <售价>28.0元</售价>
- </书>
- </书架>
需要一个book类,存放书的具体信息(书名,作者,售价)为:
- package com.flower.parsexml;
- 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 com.flower.parsexml;
- import java.io.IOException;
- import java.util.ArrayList;
- 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 SAXparse {
- @SuppressWarnings("unchecked")
- public static void main(String[] args) throws ParserConfigurationException,
- SAXException, IOException {
- // 创建解析工厂
- SAXParserFactory factory = SAXParserFactory.newInstance();
- // 创建解析器
- SAXParser parser = factory.newSAXParser();
- // 得到读取器
- XMLReader reader = parser.getXMLReader();
- // 设置内容处理器
- BeanListHandler handler = new BeanListHandler();
- reader.setContentHandler(handler);
- // 读取xml文档
- reader.parse("src/books.xml");
- ArrayList list = handler.getBooks();
- Book book;
- for(int i = 0; i < list.size(); i++) {
- book = new Book();
- book = (Book) list.get(i);
- System.out.println(book.getName() + book.getAuthor() + book.getPrice());
- }
- }
- }
- class BeanListHandler extends DefaultHandler {
- //将读取的内容存放到一个book对象中,存放到list集合中
- ArrayList<Book> list = new ArrayList<Book>();
- private String currentTag;
- private Book book;
- @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 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);
- }
- }
- @Override
- public void endElement(String uri, String localName, String qName)
- throws SAXException {
- if("书".equals(qName)) {
- list.add(book);
- book = null;
- }
- currentTag = null;
- }
- public ArrayList<Book> getBooks() {
- return list;
- }
- }
运行结果为:
- 海的女儿安徒生50.0元
- 卖火柴的小女孩安徒生28.0元