我在将数据存储在从本地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