您的位置:首页 > 编程语言 > Java开发

Java解析XML文件的四种方式之SAX解析

2014-06-30 13:51 309 查看
xml文件:

<?xml version="1.0" encoding="utf-8"?>
<!--   Copyright w3school.com.cn  -->
<!--  W3School.com.cn bookstore example  -->
<bookstore>
	<book category="children">
		<title lang="en">Harry Potter</title>
		<author>J K. Rowling</author>
		<year>2005</year>
		<price>29.99</price>
	</book>
	<book category="cooking">
		<title lang="en">Everyday Italian</title>
		<author>Giada De Laurentiis</author>
		<year>2005</year>
		<price>30.00</price>
	</book>
	<book category="web" cover="paperback">
		<title lang="en">Learning XML</title>
		<author>Erik T. Ray</author>
		<year>2003</year>
		<price>39.95</price>
	</book>
	<book category="web">
		<title lang="en">XQuery Kick Start</title>
		<author>James McGovern</author>
		<year>2003</year>
		<price>49.99</price>
	</book>
</bookstore>


Java处理:

封装xml数据的一个类:

package com.xyls.xml.sax;
import java.util.Date;
public class Book {
	private String category;
	private String title;
	private String lang;
	private String author;
	private Date year;
	private double price;
	public String getCategory() {
		return category;
	}
	public void setCategory(String category) {
		this.category = category;
	}
	public String getTitle() {
		return title;
	}
	public void setTitle(String title) {
		this.title = title;
	}
	public String getLang() {
		return lang;
	}
	public void setLang(String lang) {
		this.lang = lang;
	}
	public String getAuthor() {
		return author;
	}
	public void setAuthor(String author) {
		this.author = author;
	}
	public Date getYear() {
		return year;
	}
	public void setYear(Date year) {
		this.year = year;
	}
	public double getPrice() {
		return price;
	}
	public void setPrice(double price) {
		this.price = price;
	}
	@Override
	public String toString() {
		return "图书信息 	[\n"+ 
				"    分类:" + category + 
				",\n    名称:" + title + 
				",\n    语言:"+lang+
				", \n    作者:"+ author + 
				", \n    出版日期:" + year + 
				", \n    价格:" + price + "]";
	}
	

}


编写解析器继承自DefaultHandler:

package com.xyls.xml.sax;

import java.io.File;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
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.helpers.DefaultHandler;
/**
 * 如果使用Sax解析xml,需要编写一个解析器,继承DefaultHandler类
 * SAX采用顺序模式 部分读取 进行访问,触发事件
 * 不受文件大小限制
 * SAX只能读取信息
 * */
public class MySax extends DefaultHandler {
	private List<Book> books = null;
	private Book book = null;
	private String flag = null;//定义一个标记,存放正在解析的节点名称
	
	public List<Book> getBooks() {
		return books;
	}

	@Override
	public void startDocument() throws SAXException {
		books = new ArrayList<Book>();
	}

	@Override
	public void startElement(String uri, String localName, String qName,
			Attributes attributes) throws SAXException {
		if("book".equals(qName)){
			book = new Book();
			book.setCategory(attributes.getValue(0));
		}else if("title".equals(qName)){
			book.setLang(attributes.getValue(0));
		}
		flag = qName;//存放正在解析的节点的名称
	}

	@Override
	public void endElement(String uri, String localName, String qName)
			throws SAXException {
		if("book".equals(qName)){
			books.add(book);
			book = null;
		}
		flag = null;//结束标签解析完毕时,定义为null
	}

	@Override
	public void characters(char[] ch, int start, int length)
			throws SAXException {
		if(flag!=null){
			String content = new String(ch,start,length);
			if("title".equals(flag)){
				book.setTitle(content);
			}
			if("author".equals(flag)){
				book.setAuthor(content);
			}
			if("year".equals(flag)){
				try {
					book.setYear(new SimpleDateFormat("yyyy").parse(content));
				} catch (ParseException e) {
					e.printStackTrace();
				}
			}
			if("price".equals(flag)){
				book.setPrice(Float.parseFloat(content));
			}
		}
	}
	public static void main(String[] args) {
		MySax handle = new MySax();
		SAXParserFactory sf = SAXParserFactory.newInstance();
		try {
			SAXParser sp = sf.newSAXParser();
			URI uri = MySax.class.getClassLoader().getResource("books.xml").toURI();
			File f = new File(uri);
			sp.parse(f, handle);
			List<Book> books = handle.getBooks();
			for(Book book:books){
				System.out.println(book);
			}
		} catch (ParserConfigurationException e) {
			e.printStackTrace();
		} catch (SAXException e) {
			e.printStackTrace();
		} catch (URISyntaxException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: