Android采用SAX解析XML文档

package com.cn.service;

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;

import com.cn.domain.Persion;
/****
 * 采用SAX解析XML
 * 
 * ****/
public class SAXPersionService {
	
	public List<Persion> getPersino(InputStream is)throws Exception{
		SAXParserFactory factory = SAXParserFactory.newInstance();  
		SAXParser parser = factory.newSAXParser();
		PersionHandler handler = new PersionHandler();
		parser.parse(is, handler);
		return handler.getList();
	}
	
	private final class PersionHandler extends DefaultHandler{
		private List<Persion> list = null;
		private Persion persion;
		private String tag;
		
		public List<Persion> getList() {
			return list;
		}
		@Override
		public void startDocument() throws SAXException {
			list = new ArrayList<Persion>();
		}
		@Override
		public void startElement(String uri, String localName, String qName,Attributes attributes) throws SAXException {
			if("person".equals(localName)){
				persion = new Persion();
				persion.setId(Integer.parseInt(attributes.getValue(0)));
			}
			tag = localName;
		}
		@Override
		public void characters(char[] ch, int start, int length)throws SAXException {
			if(tag != null){
				String textdata = new String(ch,start,length);
				if("name".equals(tag)){
					persion.setName(textdata);
				}else if("age".equals(tag)){
					persion.setAge(Short.parseShort(textdata));
				}
			}
		}
		@Override
		public void endElement(String uri, String localName, String qName)throws SAXException {
			tag = null;
			if("person".equals(localName)){
				list.add(persion);
				persion = null;
			}
		}
		
	}
}

下面是类Persion的定义:


package com.cn.domain;

public class Persion {
	private int id;
	private String name;
	private short age;
	
	public Persion(){
		
	}
	
	public Persion(int id, String name, short age) {
		super();
		this.id = id;
		this.name = name;
		this.age = age;
	}
	public int getId() {
		return id;
	}
	public void setId(int id) {
		this.id = id;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public short getAge() {
		return age;
	}
	public void setAge(short age) {
		this.age = age;
	}
	@Override
	public String toString() {
		return "Persion [age=" + age + ", id=" + id + ", name=" + name + "]";
	}
}
 

你可能感兴趣的:(xml,android)