我有这个XML
<CurrencyExchangeMap>
<CurrencyExchangePoint>
<Address>addr 3</Address>
<Latitude>41.6940265</Latitude>
<Longitude>44.7985044</Longitude>
</CurrencyExchangePoint>
<CurrencyExchangePoint>
<Address>addr 4</Address>
<Latitude>41.7024424</Latitude>
<Longitude>44.8058617</Longitude>
</CurrencyExchangePoint>
<CurrencyExchangePoint>
<Address>addr 5</Address>
<Latitude>41.6954418</Latitude>
<Longitude>44.7046725</Longitude>
</CurrencyExchangePoint>
</CurrencyExchangeMap>
我正在使用以下方法解析它:
列出mapLTList;
private MapLT mapLT;
private String text;
public XMLPullParserHandler() {
mapLTList = new ArrayList<MapLT>();
}
public List<MapLT> getMapLT(){
return mapLTList;
}
public List<MapLT> parse(InputStream is){
XmlPullParserFactory factory = null;
XmlPullParser parser = null;
try{
factory = XmlPullParserFactory.newInstance();
factory.setNamespaceAware(true);
parser = factory.newPullParser();
parser.setInput(is, null);
int eventType = parser.getEventType();
while(eventType != XmlPullParser.END_DOCUMENT){
String tagname = parser.getName();
switch (eventType){
case XmlPullParser.START_TAG:
if(tagname.equalsIgnoreCase("CurrencyExchangeMap")){
mapLT = new MapLT();
}
break;
case XmlPullParser.TEXT:
text = parser.getText();
break;
case XmlPullParser.END_TAG:
if(tagname.equalsIgnoreCase("CurrencyExchangePoint")){
mapLTList.add(mapLT);
} else if(tagname.equalsIgnoreCase("Address")){
mapLT.setAddress(text);
} else if(tagname.equalsIgnoreCase("Latitude")){
mapLT.setLatitude(Float.parseFloat(text));
} else if(tagname.equalsIgnoreCase("Longitude")){
mapLT.setLongitude(Float.parseFloat(text));
}
break;
default:
break;
}
eventType = parser.next();
}
}catch (Exception ex){
ex.printStackTrace();
}
return mapLTList;
}
但结果中有3个地址,每个地址都是Addr 5
(最后一个元素)。怎么了?
答案 0 :(得分:3)
您的MapLit包含有关CurrencyExchangePoint
(xml中的三个项目)的信息,但您将其视为CurrencyExchangeMap
(xml中的一项)。这样,您可以反复重复使用相同的引用,覆盖其内容。变化
case XmlPullParser.START_TAG:
if(tagname.equalsIgnoreCase("CurrencyExchangeMap")){
mapLT = new MapLT();
}
与
case XmlPullParser.START_TAG:
if(tagname.equalsIgnoreCase("CurrencyExchangePoint")){
mapLT = new MapLT();
}