这是我的xml
<body>
<map>
<key1>
value1
</key1>
<key2>
value2
</key2>
....
</map>
<body>
我有:
Document xPacket;
XPath xPath = XPathFactory.newInstance().newXPath();
Map<Integer, String> temp = new HashMap<Integer, String>();
Object rawMap = xPath.compile("//body/map/").evaluate(xPacket, XPathConstants.NODESET);
NodeList mapNodeList = (NodeList) rawMap;
但是如何遍历NodeList
并填充地图中的值?
答案 0 :(得分:1)
由于您没有另外指定,我假设您正在使用标准Java库的类。
NodeList
对象有item(int)
方法。您可以使用该方法遍历NodeList
:
Map<Integer, String> map = new HashMap();
for (int i = 0; i < aNodeList.getLength(); i++) {
Node item = aNodeList.item(i);
map.put(Integer.valueOf(item.getTextContent()), item.getLocalName());
}
这里我假设您希望将XML关键节点的文本内容映射到节点的名称(因为您的地图的类型参数)。