我正在解析 xml,其中包含员工的特定名称列表...所以在解析时我使用 hashmap 来存储值。我继续在 arraylist 中添加人员数据,当我找到结束元素标记时,我将该 arraylist 对象放入 HashMap 并清除 Arraylist 以存储下一个数据。
但是当我打印 hashmap 时,我发现 hashmap 中只有键,根本没有 arraylist ......
如果我在将arraylist放入hashmap后不清除arraylist,则在hashmap中找到值......但所有值都聚集在一起......所以我必须在将arraylist放入hashmap后清除arraylist......
**HERE IS MY CODE OF XML PARSING**
package com.example;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
public class StaffXmlHandler extends DefaultHandler
{
static int totalSection=0;
static HashMap<String,ArrayList<Staff>> staffListWithDesignation=new HashMap<String,ArrayList<Staff>>();
ArrayList<Staff> staffList=new ArrayList<Staff>();
String designationName;
public static HashMap<String,ArrayList<Staff>> getStaffListWithDesignation()
{
return staffListWithDesignation;
}
public void startElement(String uri, String localName, String qName,
Attributes attributes) throws SAXException
{
if(localName.equals("designation"))
{
designationName= attributes.getValue("name");
System.out.println("=====================>>>>Designation="+designationName);
}
else if (localName.equals("staff"))
{
//System.out.println("======>>>>fetching data from staff");
String employeeName = attributes.getValue("name");
String employeeEmail=attributes.getValue("email");
String employeePost=attributes.getValue("designation");
String employeePhone=attributes.getValue("phone");
Staff s=new Staff();
s.setEmployeeName(employeeName);
s.setEmployeeEmail(employeeEmail);
s.setEmployeePhone(employeePhone);
s.setEmployeePost(employeePost);
staffList.add(s);
}
}
@Override
public void endElement(String uri, String localName, String qName)
throws SAXException
{
/** set value */
if (localName.equalsIgnoreCase("designation"))
{
// Staff[] s=new Staff[staffList.size()];
// System.out.println("=========================="+designationName+"=======================");
// for(int i=0;i<staffList.size();i++)
// {
// System.out.println("=====Record "+(i+1)+"=====");
// s[i]=new Staff();
// s[i]=staffList.get(i);
// System.out.println("Name:"+s[i].getEmployeeName());
// System.out.println("email:"+s[i].getEmployeeEmail());
//
//
// }
ArrayList<Staff> temp=staffList;
staffListWithDesignation.put(designationName, temp);
staffList.clear();
designationName=null;
}
}
public void endDocument ()
{
System.out.println("==================End Element tag");
Iterator<String> iterator =staffListWithDesignation.keySet().iterator();
while (iterator.hasNext())
{
String key = (String) iterator.next();
System.out.println("=====> " + key + "======" + StaffXmlHandler.staffListWithDesignation.get(key));
}
}
@Override
public void characters(char[] ch, int start, int length)throws SAXException
{
}
}
在上面的代码中,在注释行中,如果我检查数组列表是否包含 DAA,那么它会向我显示数据但不知道为什么它不存储在 HASHMAP 中......
请给我一些解决方案...
提前致谢