public class Pull_xml extends Activity {
private String result = "";
private ArrayList<Beauty> beauties = new ArrayList();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_pull_xml);
try {
// 以流的形式获取src目录下的xml文件(此文件的父文件夹必须是src)
InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream("beauties.xml");
// 获取一个XmlPullParser
XmlPullParserFactory xmlPullParserFactory = XmlPullParserFactory.newInstance();
XmlPullParser parser = xmlPullParserFactory.newPullParser();
// 设置输入流已经编码方式
parser.setInput(inputStream, "UTF-8");
// 获取当前的事件类型
int eventType = parser.getEventType();
Beauty beauty = null;
while (XmlPullParser.END_DOCUMENT != eventType) {
String nodeName = parser.getName();
switch (eventType) {
case XmlPullParser.START_TAG:
if (nodeName.equals("beauty")) {
beauty = new Beauty();
}
if (nodeName.equals("name")) {
beauty.setName(parser.nextText());
}
if (nodeName.equals("age")) {
beauty.setAge(parser.nextText());
}
break;
case XmlPullParser.END_TAG:
if (nodeName.equals("beauty") && beauty != null) {
beauties.add(beauty);
}
break;
default:
break;
}
// 手动的触发下一个事件
eventType = parser.next();
Log.i("PullActivity", eventType + "");
}
for (Beauty beauty2 : beauties) {
result += "/n" + beauty2.toString();
}
// result = beauties.size()+"";
TextView textView = (TextView) findViewById(R.id.show);
textView.setText("最终结果:"+"\n" + result);
} catch (Exception e) {
e.printStackTrace();
}
}
}
读取到xml的声明返回数字0 START_DOCUMENT;
读取到xml的结束返回数字1 END_DOCUMENT ;
读取到xml的开始标签返回数字2 START_TAG
读取到xml的结束标签返回数字3 END_TAG
读取到xml的文本返回数字4 TEXT
网友评论