假设,我的 student.xml 文件位于 assets 文件夹中,例如,
<students>
<student id="11">
<roll>1</roll>
<name>sachin</name>
<result>pass</result>
</student>
<student id="12">
<roll>2</roll>
<name>sehwag</name>
<result>pass</result>
</student>
<student id="13">
<roll>3</roll>
<name>rohit</name>
<result>fail</result>
</student>
</students>
写下按钮 Onclick 上的代码:
try {
XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
XmlPullParser xpp = factory.newPullParser();
xpp.setInput(getAssets().open("student.xml"), null);
int event = xpp.getEventType();
while (event != XmlPullParser.END_DOCUMENT) {
if (event == XmlPullParser.START_DOCUMENT) {
} else if (event == XmlPullParser.START_TAG) {
tname = xpp.getName();
if (tname.equalsIgnoreCase("student")) {
str += xpp.getAttributeValue(0).toString() + " : ";
}
} else if (event == XmlPullParser.END_TAG) {
} else if (event == XmlPullParser.TEXT) {
if (tname.equalsIgnoreCase("roll")) {
str += xpp.getText();
// event = xpp.next();
} else if (tname.equalsIgnoreCase("name")) {
str += xpp.getText();
// event = xpp.next();
} else if (tname.equalsIgnoreCase("result")) {
str += xpp.getText();
// event = xpp.next();
}
}
event = xpp.next();
}
} catch (XmlPullParserException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
tv.setText(str);
}