我正在使用 saxParser 的简单实现。在我的 endElement 方法中,我将 vo 对象存储到 ArrayList。不幸的是,当我遍历我的列表时,它只返回我的 xml 数据中的最后一项。只是想知道我做错了什么?相关代码如下:
public class MyXMLHandler extends DefaultHandler {
private StringBuffer buffer = new StringBuffer();
private Boolean currentElement = false;
private StoreDetails storeDetails = new StoreDetails(); //vo object
private ArrayList<StoreDetails> dataList = new ArrayList<StoreDetails>(); //list of vo
public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
currentElement = true;
}
@Override
public void endElement(String uri, String localName, String qName) throws SAXException {
currentElement = false;
if (localName.equals("StoreID")) {
buffer.toString().trim();
storeDetails.setStoreId(buffer.toString());
} else if (localName.equals("StoreName")) {
buffer.toString().trim();
storeDetails.setStoreName(buffer.toString());
} else if (localName.equals("StoreCategory")) {
buffer.toString().trim();
storeDetails.setStoreCategory(buffer.toString());
//add vo object to ArrayList - dataList
dataList.add(storeDetails);
}
buffer = new StringBuffer();
}
@Override
public void characters(char[] ch, int start, int length) throws SAXException {
if (currentElement) {
buffer.append(ch, start, length);
currentElement = false;
}
}
@Override
public void endDocument() throws SAXException {
Log.i("TAG", "DONE PARSING XML");
for(StoreDetails details : dataList){
//ISSUE - returning only the last row in my xml data (over and over)
Log.i("TAG", "Details ID: " + details.getStoreId());
}
}
}