我正在尝试将 XML 文件解析为列表,但是它只获取 XML 文件中的最后一个条目。我在下面有一个样本
<?xml version="1.0"?>
<stops>
<stop>
<number>stop_code</number>
<lat>stop_lat</lat>
<lon>stop_lon</lon>
<name>stop_name</name>
</stop>
<stop>
<number>112112</number>
<lat> 51.060931</lat>
<lon>-114.065158</lon>
<name>"CRESCENT HEIGHTS HIGH SCHOOL"</name>
</stop>
<stop>
<number>2110</number>
<lat> 51.082803</lat>
<lon>-114.214888</lon>
<name>"EB CAN OLYMPIC RD@OLYMPIC CE ENTR"</name>
</stop>
.....
<stop>
<number>9988</number>
<lat> 51.047388</lat>
<lon>-114.067770</lon>
<name>"NB 2 ST@6 AV SW"</name>
</stop>
<stop>
<number>9998</number>
<lat> 50.997509</lat>
<lon>-114.013415</lon>
<name>"19 St @ 62 Ave SE nb ns"</name>
</stop>
我的拉解析器是
ublic class PullParser {
public static final String STOP_NAME = "name";
public static final String STOP_LAT = "lat";
public static final String STOP_LON = "lon";
public static final String NUMBER = "number";
private Stops currentStop = null;
private String currentTag= null;
List<Stops> stops = new ArrayList<Stops>();
public List<Stops> parseXML (Context context) {
try {
XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
factory.setNamespaceAware(true);
XmlPullParser xpp = factory.newPullParser();
InputStream stream = context.getResources().openRawResource(R.raw.stops_xml);
xpp.setInput(stream,null);
int eventType = xpp.getEventType();
while (eventType != XmlPullParser.END_DOCUMENT) {
if (eventType == XmlPullParser.START_TAG) {
handleStartTag(xpp.getName());
} else if (eventType == XmlPullParser.END_TAG) {
currentTag = null;
} else if (eventType == XmlPullParser.TEXT) {
handleText(xpp.getText());
}
eventType = xpp.next();
}
} catch (Resources.NotFoundException e) {
Log.d(MainActivity.TAG, e.getMessage());
} catch (XmlPullParserException e) {
Log.d(MainActivity.TAG, e.getMessage());
} catch (IOException e) {
Log.d(MainActivity.TAG, e.getMessage());
}
return stops;
}
private void handleText(String text) {
String xmlText = text;
if (currentStop != null && currentTag != null) {
if (currentTag.equals(STOP_NAME)) {
currentStop.setName(xmlText);
}
else if (currentTag.equals(STOP_LAT)) {
currentStop.setLat(xmlText);
}
else if (currentTag.equals(STOP_LON)) {
currentStop.setLon(xmlText);
}
else if (currentTag.equals(NUMBER)) {
currentStop.setNumber(xmlText);
}
}
}
private void handleStartTag(String name) {
if (name.equals("stop")) {
currentStop = new Stops();
stops.add(currentStop);
}
else {
currentTag = name;
}
}
}
当我运行它时,它只返回所有 5882 个条目的停止编号 9998(这是文件中正确的条目数)。有什么明显我失踪的吗?