我在将数据存储在 Hashmap 的 Arraylist 中时遇到问题,该数据是从本地 xml 文件解析的。
首先,这是我的 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>
我想将每对title
、link
和date
存储在Hashmap中,然后将其放入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 Parser 的 endElement
方法中,我检查了该元素是否为 title
、date
或 link
然后将其数据放入 HashMap 中并最终将其添加到数组列表中,但数据在数组列表中被覆盖而不是附加,
这是我从 Logcat 输出的内容,
[{date=hs2, title=Harry2, link=Smith2}, {date=hs2, title=Harry2, link=Smith2}, {date=hs2, title=Harry2, link=Smith2}, {日期=hs2, 标题=Harry2, 链接=Smith2}, {日期=hs2, 标题=Harry2, 链接=Smith2}, {日期=hs2, 标题=Harry2, 链接=Smith2}, {日期=hs2, 标题=Harry2,链接=史密斯2},{日期=hs2,标题=哈利2,链接=史密斯2},{日期=hs2,标题=哈利2,链接=史密斯2},{日期=hs2,标题=哈利2,链接=史密斯2},{日期= hs2,标题=Harry2,链接=Smith2},{日期=hs2,标题=Harry2,链接=Smith2},{日期=hs2,标题=Harry2,链接=Smith2},{日期=hs2,标题=Harry2,链接=史密斯2},{日期=hs2,标题=哈利2,链接=史密斯2},{日期=hs2,标题=哈利2,链接=史密斯2}]
唯一的最后一个员工详细信息被添加到 arraylist 中这么多次?为什么前两名员工的详细信息没有显示? 我在这里做错了什么?
最佳答案
你只创建一个HashMap实例
HashMap<String, String> keyValuePair = new HashMap<String, String>();
然后您继续将同一个实例添加到列表中。这就是为什么列表中的所有 map 都是同一个实例。
您必须调用keyValuePair = new HashMap<String, String>();
每次初始化要添加到列表中的新 map 之前。
关于java - 将 Sax 解析器数据作为 Hashmap 存储在数组列表中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26450886/