gpt4 book ai didi

java - 从 XML 解析 map

转载 作者:行者123 更新时间:2023-12-01 13:34:54 29 4
gpt4 key购买 nike

这是我的 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并在 map 中填充值?

最佳答案

由于您没有另外指定,我假设您正在使用标准 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 键节点的文本内容映射到节点的名称(因为映射的类型参数)。

关于java - 从 XML 解析 map ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21361594/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com