I have a Xml file which I iterate like this:
List<String> list = new ArrayList<>();
for (int i = 0; i < nList.getLength(); i++) {
Node nNode = nList.item(i);
System.out.println("\nCurrent Element: " + nNode.getNodeName());
if (nNode.getNodeType() == Node.ELEMENT_NODE) {
Element elem = (Element) nNode;
Node id = elem.getElementsByTagName("id").item(0);
Node key = elem.getElementsByTagName("key").item(0);
if (id.getTextContent().length() > 0) {
String identifier = id.getTextContent();
String key2 = key.getTextContent();
System.out.println("id: " + identifier);
System.out.println("key: " + key2);
list.add(identifier);
list.add(key2);
}
}
}
That works and as you can see, I can add the values to a list of Strings but that's not what I want to do. I want to make a list of objects from those string values, lke this:
[{"id": identifier, "key": key2}]
.
I've tried many ways but nothing seems to work, there must be some simple way in Java also to add those strings as a key-value pairs in a list?
Here:
List<String> list = new ArrayList<>();
If you dont want to collect Strings , then say so:
List<Map<String, String>> list = new ArrayList<>();
And then, instead of adding strings:
list.add(identifier);
list.add(key2)
You could do:
list.add(Collections.singletonMap(identifier, key2);
or something alike.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.