Pull 解析相同Tag标签的XML文件

前端之家收集整理的这篇文章主要介绍了Pull 解析相同Tag标签的XML文件前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
需要解析的XML格式 在这里, 有两个name相同的标签
解析的时候,我们不能用 pull.next()方法,这个在4.0的时候, 并不能推到下一个标签。我们需要用pull.nextTag(),方法,他这个能往下一个标签执行。 到最后结束的时候, 我们需要在 end_document中直接退出, 按常规的,他会报 end_document is null 。 为什么会这样,不清楚。 具体解析看代码

package com.demo.thread;

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

import org.xmlpull.v1.XmlPullParser;

import android.content.Context;
import android.util.Xml;

import com.demo.R;
import com.demo.bean.School;
import com.demo.bean.Student;

public class XmlPullThread extends Thread{
private Context context;
public XmlPullThread(Context context){
this.context = context;
}
@Override
public void run() {
super.run();
InputStream in = context.getResources().openRawResource(R.raw.test);
getSchoolData(in);
}

public School getSchoolData(InputStream in){
try{
School school = null;
Student student = null;
String tageName = null;
List studenList = null;
XmlPullParser pull = Xml.newPullParser();
pull.setInput(in,"UTF-8");
int event = pull.getEventType();
String currentTage = null;
while (event != XmlPullParser.END_DOCUMENT) {
switch (event) {
case XmlPullParser.START_TAG:
tageName = pull.getName();
if ("school".equals(tageName)) {
school = new School();
studenList = new ArrayList();
currentTage = "school";
}else if ("name".equals(tageName)) {
if("school".equals(currentTage)){
school.setName(pull.nextText());
}else if("student".equals(currentTage)){
student.setName(pull.nextText());
}
}else if ("student".equals(tageName)) {
student = new Student();
currentTage = "student";
}else if ("sex".equals(tageName)) {
student.setSex(pull.nextText());
}
break;
case XmlPullParser.END_TAG:
if ("student".equals(pull.getName())) {
studenList.add(student);
student = null;
}else if("school".equals(pull.getName())){
school.setStudenList(studenList);
System.out.println(school.getStudenList().size()")
return school;
}
break;
default:
break;
}
event = pull.nextTag();// 进入下一个元素并触发相应事件,如果用next 的话,4.0并不会指到下一个标签
}
return school;
}catch(Exception e){
e.printStackTrace();
}
return null;
}
}
通过设置 当前的大的类Tag的值,来获取相同Tag中不同的值。
原文链接:https://www.f2er.com/xml/298657.html

猜你在找的XML相关文章