我在將數據存儲在從本地xml文件解析的Hashmap的Arraylist中時遇到問題。在數組列表中存儲Sax解析器數據爲HashMap
首先,這裏是我的xml文件,
<?xml version="1.0"?>
<organization>
<employee>
<title>Harry0</title>
<link>Smith0</link>
<date>hs0</date>
<salary>200000-0</salary>
</employee>
<employee>
<title>Harry1</title>
<link>Smith1</link>
<date>hs1</date>
<salary>300000-1</salary>
</employee>
<employee>
<title>Harry2</title>
<link>Smith2</link>
<date>hs2</date>
<salary>300000-2</salary>
</employee>
</organization>
我要存儲的Hashmap每對title
,link
和date
然後把它裏面的HashMap數組列表。
我使用SAX解析器,但我無法實現我想要做的,
這裏是我的聲明HashMap和包含HashMap的ArrayList的代碼,
ArrayList<HashMap<String, String>> xml_Array = new ArrayList<HashMap<String,String>>();
HashMap<String, String> keyValuePair = new HashMap<String, String>();
現在該怎麼辦我所做的是,
@Override
public void startElement(String uri, String localName, String qName,
Attributes attributes) throws SAXException {
startElement = localName;
}
@Override
public void characters(char[] ch, int start, int length)
throws SAXException {
elementValue = new String(ch, start, length);
}
@Override
public void endElement(String uri, String endElement, String qName)
throws SAXException {
super.endElement(uri, endElement, qName);
if (startElement == endElement){
inElements = true;
}
if (inElements == true){
if (endElement == "title"){
keyValuePair.put("title", elementValue);
}
else if (endElement == "link"){
keyValuePair.put("link", elementValue);
}
else if (endElement == "date"){
keyValuePair.put("date", elementValue);
}
inElements = false;
}
xml_Array.add(keyValuePair);
}
@Override
public void endDocument() throws SAXException {
super.endDocument();
Log.e("test",xml_Array + "");
}
在SAX解析器endElement
方法,我檢查,如果元素是title
,date
或link
,然後把它的數據一個HashMap中,並最終將其添加內部數組列表,但數據中的ArrayList,而不是追加被覆蓋,
這裏是logcat的我的輸出,
[{date=hs2, title=Harry2, link=Smith2}, {date=hs2, title=Harry2, link=Smith2}, {date=hs2, title=Harry2, link=Smith2}, {date=hs2, title=Harry2, link=Smith2}, {date=hs2, title=Harry2, link=Smith2}, {date=hs2, title=Harry2, link=Smith2}, {date=hs2, title=Harry2, link=Smith2}, {date=hs2, title=Harry2, link=Smith2}, {date=hs2, title=Harry2, link=Smith2}, {date=hs2, title=Harry2, link=Smith2}, {date=hs2, title=Harry2, link=Smith2}, {date=hs2, title=Harry2, link=Smith2}, {date=hs2, title=Harry2, link=Smith2}, {date=hs2, title=Harry2, link=Smith2}, {date=hs2, title=Harry2, link=Smith2}, {date=hs2, title=Harry2, link=Smith2}]
什麼ArrayList中僅添加了最後一名員工詳細信息多次?以及爲什麼前兩名員工的員工細節沒有顯示出來? 我在這裏做錯了什麼?
http://simple.sourceforge.net/ – 2014-10-19 13:36:10