我正在尝试显示所有记录,但它只显示最后一条记录,因为它的值每次都会被覆盖。如何解决这个问题?
File fXmlFile = new File("d:/formdata.xml");
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(fXmlFile);
doc.getDocumentElement().normalize();
System.out.println("Root element :" + doc.getDocumentElement().getNodeName());
NodeList nList = doc.getElementsByTagName("record");
System.out.println("----------------------------");
for (int temp = 0; temp < nList.getLength(); temp++) {
Map<String, Object> map = new HashMap<String, Object>();
Node nNode = nList.item(temp);
if (nNode.getNodeType() == Node.ELEMENT_NODE) {
Element eElement = (Element) nNode;
map.put("Item No", eElement.getElementsByTagName("item_no").item(0).getTextContent());
map.put("Description", eElement.getElementsByTagName("description").item(0).getTextContent());
map.put("price", eElement.getElementsByTagName("price").item(0).getTextContent());
map.put("base qty", eElement.getElementsByTagName("base_qty").item(0).getTextContent());
map.put("Var qty", eElement.getElementsByTagName("var_qty").item(0).getTextContent());
generateCsvFile("E:\\testCSV.csv", map);
}
}
当调用 generateCSVfile()
private static void generateCsvFile(String sFilename, Map<String, Object> test) {
try {
FileWriter writer = new FileWriter(sFilename,true);
Iterator iterator = test.entrySet().iterator();
while (iterator.hasNext()) {
Map.Entry mapEntry = (Map.Entry) iterator.next();
System.out.println("key: " + mapEntry.getKey() + ", value:" + mapEntry.getValue());
writer.append(mapEntry.getKey() + " = " + mapEntry.getValue());
writer.append(",");
iterator.remove();
}
writer.flush();
writer.close();
}
我们如何将所有值存储在 Map 中?