SAX解析XML简述

XML:可扩展标记语言 通常用于数据的存储格式或者是存储软件的参数:
SAX:流解析,将xml由下而下逐个读入内存解析而不是一次性读入内存(Dom解析)
例如解析如下XML数据:

<?xml version="1.0" encoding="UTF-8"?>
<persons>
	<person>
		<name>ahh</name>
		<age>18</age>
	</person>
	<person>
		<name>wll</name>
		<age>18</age>
	</person>
</persons>

首先根据xml结构,实体化Person类:

public class Person {

	private String name;
	private int age;
	
	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public int getAge() {
		return age;
	}

	public void setAge(int age) {
		this.age = age;
	}

	public Person() {

	}

	public static void main(String[] args) {

	}
	
	@Override
	public String toString() {
		
		return this.name+"--->"+this.age;
	}

}

SAX解析套路:

public class XMLTest02 {
	public static void main(String[] args) throws ParserConfigurationException, SAXException, IOException {
		// SAX解析
		// 1、获取SAX解析工厂
		SAXParserFactory factory = SAXParserFactory.newInstance();
		// 2、从解析工厂中获取解析器
		SAXParser parse = factory.newSAXParser();
		// 3、加载文档Document注册处理器
		// 4、编写处理器
		PersonHandler handler = new PersonHandler();
		// 5、解析
		parse.parse(Thread.currentThread().getContextClassLoader().getResourceAsStream("com/sxt/server/basic/p.xml"),
				handler);
		//6、获取数据
		List<Person> persons=handler.getPersons();
		
		for(Person person:persons) {
			System.out.println(person);
		}
	}
}

class PersonHandler extends DefaultHandler {
	private List<Person> persons;
	private Person person;
	private String tag;//存储操作的标签
	@Override
	public void startDocument() throws SAXException {
		persons=new ArrayList<Person>();
	}

	@Override
	public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
		if (null != qName) {
			tag = qName;// 存储标签名
			if (tag.equals("person")) {
				person = new Person();
			}
		}
	}

	@Override
	public void characters(char[] ch, int start, int length) throws SAXException {
		String contents = new String(ch, start, length).trim();
		if(null!=tag) {//处理空的问题
			if(tag.equals("name")) {
				person.setName(contents);
			}else if(tag.equals("age")){
				if(contents.length()>0) {
					person.setAge(Integer.valueOf(contents));
				}
			}
		}
	}

	@Override
	public void endElement(String uri, String localName, String qName) throws SAXException {
		if(qName!=tag) {//处理空的问题
			if(qName.equals("person")) {
				persons.add(person);
			}
		}
		tag=null;//tag丢弃,不然会导致标签值被空值覆盖
	}

	@Override
	public void endDocument() throws SAXException {
	}

	public List<Person> getPersons() {
		return persons;
	}

	public void setPersons(List<Person> persons) {
		this.persons = persons;
	}
	
	
}

你可能感兴趣的:(#,手写webserver)