当前位置 : 主页 > 编程语言 > c++ >

xml解析之sax解析

来源:互联网 收集:自由互联 发布时间:2021-07-03
gistfile1.txt package cn.jxau.sax;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
gistfile1.txt
package cn.jxau.sax;

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;

import cn.jxau.domain.Book;

public class Demo {
	public static void main(String[] args) throws Exception, SAXException {

		// 创建产生解析器的工厂
		SAXParserFactory factory = SAXParserFactory.newInstance();
		// 得到解析器
		SAXParser parser = factory.newSAXParser();
		// 得到读取器
		XMLReader reader = parser.getXMLReader();
		// 设置读取器的处理器(由程序员设置)
		// 创建处理器对象
		BookHandler handler = new BookHandler();
		reader.setContentHandler(handler);
		// 读取文档
		reader.parse("book.xml");
		List
 
   list = handler.getlist();
		for (Book book : list) {
			System.out.println(book.getName() + " " + book.getAuthor() + " " + book.getPrice());
		}
	}
}

class BookHandler extends DefaultHandler {
	private Book book = null;
	private List list = new ArrayList();

	public List getlist() {
		return list;
	}

	// 定义记住标签名的变量
	private String current_tag = null;
	// 定义记住第几本书的变量
	private int count = 0;

	@Override
	public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
		// TODO Auto-generated method stub
		super.startElement(uri, localName, qName, attributes);
		current_tag = qName;
		if ("书".equals(current_tag)) {
			// 创建一本书
			book = new Book();
			count++;
		}
		
	}

	@Override
	public void characters(char[] ch, int start, int length) throws SAXException {
		// TODO Auto-generated method stub
		super.characters(ch, start, length);
		if ("书名".equals(current_tag)) {
			book.setName(new String(ch,start,length));
		}
		if ("作者".equals(current_tag)) {
			book.setAuthor(new String(ch,start,length));
		}
		if ("售价".equals(current_tag)) {
			book.setPrice(new String(ch,start,length));
		}
	}

	@Override
	public void endElement(String uri, String localName, String qName) throws SAXException {
		// TODO Auto-generated method stub
		super.endElement(uri, localName, qName);
		if ("书".equals(qName) && count == 1) {
			list.add(book);
		}
		current_tag = null;//每个标签结束后都会有一段空白字段,空白纸短也是一个对象,
							//由于空白字段没有标签,所以程序不会执行startelement和endelement,而去执行characters
							//此时的current_tag的值还是上一个标签名,所以要将current_tag的值置为null
	}
}
 
网友评论