需要解析的xml文件如下:
<girl>
<name>
raid
</name>
<age>
12
</age>
<school>
zhongkai
</school>
</girl>
解析方法如下,这里结合了网络传输给出代码:
url是xml资源所在的位置
try {
URL httpUrl = new URL(url);
HttpURLConnection conn = (HttpURLConnection) httpUrl.openConnection();
conn.setRequestMethod("GET");
conn.setReadTimeout(5000);
InputStream in = conn.getInputStream();
XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
XmlPullParser parser = factory.newPullParser();
parser.setInput(in, "UTF-8");
int eventType = parser.getEventType();
final List<Girl> list = new ArrayList<Girl>();
Girl girl = null;
while(eventType != XmlPullParser.END_DOCUMENT) {
String data = parser.getName();
switch (eventType) {
case XmlPullParser.START_TAG:
if ("girl".equals(data)) {
girl = new Girl();
}
if ("name".equals(data)) {
girl.setName(parser.nextText());
}
if ("age".equals(data)) {
girl.setAge(Integer.parseInt(parser.nextText().trim()));
}
if ("school".equals(data)) {
girl.setSchool(parser.nextText());
}
break;
case XmlPullParser.END_TAG:
if ("girl".equals(data) && girl!=null) {
list.add(girl);
}
break;
}
//必须记住要添加这个方法
eventType = parser.next();
}
handler.post(new Runnable() {
@Override
public void run() {
// TODO Auto-generated method stub
textView.setText(list.toString());
}
});
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (XmlPullParserException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}