gpt4 book ai didi

java - 获取所有元素

转载 作者:行者123 更新时间:2023-12-01 12:32:09 25 4
gpt4 key购买 nike

我有一个 XML 文档,如下所示(我知道,它没有意义,它只是一个示例):

<Person>
<Name>Peter</Name>
<Country>Sweden</Country>
<Param name="Sport" value="yes"/>
<Param name="Color" value="no"/>
<Person/>

它可以有无限多个元素Param
获取Country的内容我做

String country = doc.getElementsByTagName("Country").item(0).getTextContent();

获取我执行的第一个 Param 的第一个属性 name 的内容

String name = source.getElementsByTagName("Param").item(0).getAttributes().item(0).getNodeValue();

但是,在不知道 Param 存在多少个元素的情况下,如何获取 Param 的所有属性的所有值呢?

我需要类似的东西(“伪代码”):

HashMap<String, String> hm = new HashMap<String, String>();

for(int i=0; i<=source.getElementsByTagName("Param").size(); i++){
String name = source.getElementsByTagName("Param").item(i).getAttributes().item(0).getNodeValue();
String value = source.getElementsByTagName("Param").item(i).getAttributes().item(1).getNodeValue();

hm.put(name, value);
}

最佳答案

您可以通过名称来请求属性。

String attrName = source.getElementsByTagName("Param").item(i).getAttribute("name"));
String value = source.getElementsByTagName("Param").item(i).getAttribute("value"));
//you could test if the values are null
hm.put(attrName, value);

关于java - 获取所有元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25853580/

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