首页>代码>Java XML解析的四种方法总结>/xmlparse/src/net/nyist/xmlparse/parse/sax/PersonHandle.java
package net.nyist.xmlparse.parse.sax;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import net.nyist.xmlparse.domain.Student;

import org.xml.sax.Attributes;
import org.xml.sax.InputSource;
import org.xml.sax.Locator;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

/**
 * @author yuchao
 * 
 * @school 南阳理工软件学院移动设备应用与开发移动四班
 * 
 * @email yu0312chao@163.com
 * 
 * @time 2014年10月1日 下午6:38:52
 * 
 */

public class PersonHandle extends DefaultHandler {

	private Student student;
	private List<Student> students;
	/**对于这个属性的使用主要作用是为了用来存放标签的名称,由此而获得这个标签下的文本内容的值*/
	private String tagName;

	public List<Student> getStudents() {
		return students;
	}

	public InputSource resolveEntity(String publicId, String systemId)
			throws IOException, SAXException {
		return null;
	}

	public void setDocumentLocator(Locator locator) {
		System.out.println("加载器开始处理xml文档........");
	}

	public void startDocument() throws SAXException {
		System.out.println("文档开始加载.........");
		students = new ArrayList<Student>();
	}

	public void endDocument() throws SAXException {
		System.out.println("xml文档处理结束.........");
	}

	public void startElement(String uri, String localName, String qName,
			Attributes attributes) throws SAXException {

		tagName = qName;
		if ("student".equals(qName)) {
			student = new Student();
			int id = Integer.parseInt(attributes.getValue("id"));
			student.setId(id);
		}
	}
	public void endElement(String uri, String localName, String qName)
			throws SAXException {
        
		if ("student".equals(qName)) {
			students.add(student);
		}
		/**将其值变为null的主要目的是为了防止再次遍历的时候保存了结尾标签,这样会有空值的存在*/
		tagName = null;
	}

	public void characters(char ch[], int start, int length)
			throws SAXException {

		if (!"".equals(tagName) && tagName != null) {

			if ("name".equals(tagName)) {

				student.setName(new String(ch, start, length));

			} else if ("sex".equals(tagName)) {

				student.setSex(new String(ch, start, length));

			} else if ("desc".equals(tagName)) {

				student.setDesc(new String(ch, start, length));
			}
		}
	}
	public static void main(String[] args) {
		PersonHandle personHandle =new PersonHandle();
		System.out.println(personHandle.getStudents());
	}
}
最近下载更多
我是helloworld  LV23 2022年6月2日
ycb159856  LV12 2017年4月11日
scpcyzxb  LV16 2017年3月5日
v512345  LV10 2016年2月14日
日久生情  LV19 2015年6月12日
jing427  LV18 2015年3月9日
zyb507  LV13 2015年1月22日
1037704496  LV1 2014年11月14日
softcore  LV10 2014年10月14日
lwptest  LV1 2014年10月12日
最近浏览更多
我是helloworld  LV23 2022年6月2日
chokkint  LV12 2021年10月27日
zhoujunyu  LV14 2021年4月13日
773977962  LV9 2021年3月30日
1234567891011  LV5 2020年7月3日
王二麻子滴滴 2020年6月14日
暂无贡献等级
和诗夜 2020年6月13日
暂无贡献等级
下载狂魔 2020年1月16日
暂无贡献等级
AKALilgirl 2019年12月8日
暂无贡献等级
0312wangchen  LV26 2019年10月31日
顶部 客服 微信二维码 底部
>扫描二维码关注最代码为好友扫描二维码关注最代码为好友