gpt4 book ai didi

Java xml解析两个同名标签

转载 作者:数据小太阳 更新时间:2023-10-29 02:56:31 26 4
gpt4 key购买 nike

我正在编写代码来解析 xml 文件。我想从中检索国家/地区标签值并将其保存到 String[]。当我尝试这样做时,它只检索一个值。但我在 xml 中重复了两次国家标签。将来它可以是三次或四次等等,这是动态的。这是我的 xml:

<?xml version="1.0"?>
<metadata>
<Country>All Countries</Country>
<Country>US - United States</Country>
</metadata>

这是我的代码:

private static String parseXml(String xmlData)
throws ParserConfigurationException, SAXException, IOException {
DocumentBuilder builder = DocumentBuilderFactory.newInstance()
.newDocumentBuilder();
InputSource src = new InputSource();
src.setCharacterStream(new StringReader(xmlData));
Document doc = builder.parse(src);
NodeList nodes = doc.getElementsByTagName("metadata");
Element line = null;
String cnt = null;
for (int i = 0; i < nodes.getLength(); i++) {
Element element = (Element) nodes.item(i);
NodeList country = element.getElementsByTagName("Country");
for (int j = 0; j < country.getLength(); j++) {
if (country != null) {
System.out.println("Country not null " + country);
line = (Element) country.item(0);
if (line != null) {
cnt = getCharacterDataFromElement(line);
}
}
}
}
return cnt;

}

public static String getCharacterDataFromElement(Element e) {
Node child = e.getFirstChild();
if (child instanceof CharacterData) {
CharacterData cd = (CharacterData) child;
if (cd != null) {
return cd.getData();
}
}
return "";
}

最佳答案

您的代码不提供在您的代码中存储国家列表的任何可能性,尽管它遍历所有国家。

以下应该有所帮助(尽管未经测试):更改 String cnt = null;List<String> = new ArrayList<String>()而不是

for (int j = 0; j < country.getLength(); j++) {
if (country != null) {
System.out.println("Country not null " + country);
line = (Element) country.item(0);
if (line != null) {
cnt = getCharacterDataFromElement(line);
}
}
}

以下内容:

if (country != null) {
System.out.println("Country not null " + country);
for (int j = 0; j < country.getLength(); j++) {
line = (Element) country.item(j);
if (line != null) {
cnt.add( getCharacterDataFromElement(line));
}
}
}

关于Java xml解析两个同名标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31275040/

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