欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

使用SAX解析XML

程序员文章站 2022-04-11 09:51:29
...

XML文件:

<?xml version="1.0" encoding="utf-8"?>
<persons>
	<person>
		<name>java小强</name>
		<sex>man</sex>
		<age>30</age>
	</person>
	<person>
		<name>崔素强</name>
		<sex>man</sex>
		<age>26</age>
	</person>
</persons>

 

为此建立响应的对象:

package com.test;
public class Xml {
	private String name;
	private String sex;
	private int age;
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public String getSex() {
		return sex;
	}
	public void setSex(String sex) {
		this.sex = sex;
	}
	public int getAge() {
		return age;
	}
	public void setAge(int age) {
		this.age = age;
	}
}

 

参考的解析代码:

package com.test;

import java.io.FileInputStream;
import java.io.InputStream;
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.helpers.DefaultHandler;

/**
 * @说明 SAX解析XML
 * @author cuisuqiang
 * @version 1.0
 * @since
 */
public class SaxDemo{
	public static void main(String[] args) {
		try {
			SaxDemo sd = new SaxDemo();
			String file = "C:\\p.xml"; // 文件存放位置
			sd.parserXml(file);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	public void parserXml(String fileName) throws Exception {
		SAXParserFactory saxfac = SAXParserFactory.newInstance();
		SAXParser saxparser = saxfac.newSAXParser();
		InputStream is = new FileInputStream(fileName);
		SAXHandler sh = new SAXHandler();
		saxparser.parse(is, sh);
		List<Xml> list = sh.getPersons();
		System.out.println("====输出解析到的内容====");
		for(Xml x : list){
			System.out.println(x.getName() + "\t" + x.getSex() + "\t" + x.getAge());
		}
	}
}
class SAXHandler extends DefaultHandler {
	private List<Xml> list = null;
	private Xml xml = null;
	private String str = null;
	public List<Xml> getPersons() {
		return list;
	}
	public void startDocument() throws SAXException {
		list = new ArrayList<Xml>();
		System.out.println("XML解析开始");
	}
	public void endDocument() throws SAXException {
		System.out.println("XML解析结束");
	}
	public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
		if("person".equals(qName)){
			xml = new Xml();
			System.out.println("开始实体解析");
		}
	}
	public void endElement(String uri, String localName, String qName) throws SAXException {
		if("name".equals(qName)){
			xml.setName(str);
		}
		if("sex".equals(qName)){
			xml.setSex(str);		
		}
		if("age".equals(qName)){
			xml.setAge(Integer.parseInt(str));
		}
		if("person".equals(qName)){
			list.add(xml);
			System.out.println("实体解析结束");
		}
	}
	// XML节点的内容会进入此方法
	public void characters(char[] ch, int start, int length) throws SAXException {
		str = new String(ch, start, length);
	}
}

 

请您到ITEYE网站看原创,谢谢!

http://cuisuqiang.iteye.com/ ! 

自建博客地址:http://www.javacui.com/ ,内容与ITEYE同步!