我解析类似的 xml 文件。这是一个例子。您需要根据需要添加错误检查。
void loadXML(XmlPullParser xpp) {
int eventType = xpp.next();
while (eventType != XmlPullParser.END_DOCUMENT) {
if (eventType == XmlPullParser.START_TAG && 0 == XML_ELEMENT_TAG.compareTo(xpp.getName())) {
loadElement(xpp);
}
eventType = xpp.next();
}
}
private void loadElement(XmlPullParser xpp) {
int eventType = xpp.getEventType();
if ( eventType == XmlPullParser.START_TAG && 0 == XML_ELEMENT_TAG.compareTo(xpp.getName()) ) {
eventType = xpp.next();
while ( eventType != XmlPullParser.END_TAG || 0 != XML_ELEMENT_TAG.compareTo(xpp.getName()) ) {
if (eventType == XmlPullParser.START_TAG && 0 == XML_ITEM_TAG.compareTo(xpp.getName())) {
loadItem(xpp);
}
eventType = xpp.next();
}
}
}
private void loadItem(XmlPullParser xpp) {
int eventType = xpp.getEventType();
if ( eventType == XmlPullParser.START_TAG && 0 == XML_ITEM_TAG.compareTo(xpp.getName()) ) {
eventType = xpp.next();
while ( eventType != XmlPullParser.END_TAG || 0 != XML_ITEM_TAG.compareTo(xpp.getName()) ) {
// Get attributes.
String attr = xpp.getAttributeValue(null, XML_MY_ATTR);
String text = null;
// Get item text if present.
eventType = xpp.next();
while ( eventType != XmlPullParser.END_TAG || 0 != XML_ITEM_TAG.compareTo(xpp.getName()) ) {
if ( eventType == XmlPullParser.TEXT ) {
text = xpp.getText();
}
eventType = xpp.next();
}
eventType = xpp.next();
}
}
}