PULL 解析xml

public class PullXMLTools {

	public static List<Person> parseXML(InputStream inputStream,String encode)throws Exception{
		List<Person> list=null;
		Person person=null;
		
		//创建一个xml解析工厂
		 XmlPullParserFactory factory= XmlPullParserFactory.newInstance();
		//获得解析类的引用
		XmlPullParser parser=factory.newPullParser();
		parser.setInput(inputStream, encode);
		
		int eventType=parser.getEventType();
		while(eventType!=XmlPullParser.END_DOCUMENT){
			switch (eventType) {
			case XmlPullParser.START_DOCUMENT:
				list=new ArrayList<Person>();
			break;
			case XmlPullParser.START_TAG:
				if("person".equals(parser.getName())){
					person=new Person();
					int id=Integer.parseInt(parser.getAttributeValue(0));
					person.setId(id);
				}else if("name".equals(parser.getName())){
					String name=parser.nextText();
					person.setName(name);
					
				}else if("age".equals(parser.getName())){
				Short age=Short.parseShort(parser.nextText());
				person.setAge(age);
				}
				break;

			case XmlPullParser.END_TAG:
				if("person".equals(parser.getName())){
					list.add(person);
					person=null;
				}
				break;
			}
			eventType=parser.next();
		}
		
		return list;}
}

你可能感兴趣的:(PULL 解析xml)