gpt4 book ai didi

java - 使用 Java 仅迭代一个 xml 标签

转载 作者:行者123 更新时间:2023-11-30 03:07:38 25 4
gpt4 key购买 nike

我正在迭代一个 XML 对象,但它仅获取一个 XML 标记值。请检查代码。它仅打印第一个标签值“abd5fd81-2bd6-4479-9d60-61fe533a13b7”。

public class sample {

/**
* @param args
*/
private final static String XML_DATA = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" +
"<list>" +
"<string>abd5fd81-2bd6-4479-9d60-61fe533a13b7</string>" +
"<string>e127393b-343b-433c-87fc-27289758cca8</string>" +
"<string>753f79fe-a1d2-4383-b5c9-3ec8aa6b7e65</string>" +
"<string>2c71f819-65a6-4b08-8870-e71b1c770992</string>" +
"<string>ad22d8c0-8187-4243-8189-92e94c969208</string>" +
"<string>e6e70ab9-6149-4dfd-9d88-e27ec419847e</string>" +
"<string>87d8566b-4c8a-4ef0-9fa9-c7b8805e5631</string>" +
"<string>1309a729-20b4-40bb-96c8-46c96f205e60</string>" +
"<string>5e78b822-d472-4f02-859d-de36183c5d01</string>" +
"<string>410c70fb-8b05-47ef-bfbf-29284e45c8d3</string>" +
"</list>";

public static void main(String[] args) throws SAXException, IOException, ParserConfigurationException {
// TODO Auto-generated method stub
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder;
builder = factory.newDocumentBuilder();
InputSource is = new InputSource();
is.setCharacterStream(new StringReader(XML_DATA));

Document doc = builder.parse(is);
NodeList nodes = doc.getElementsByTagName("list");
for (int i = 0; i < nodes.getLength(); i++) {
Element element = (Element) nodes.item(i);
NodeList name = element.getElementsByTagName("string");
Element line = (Element) name.item(0);
System.out.println("String: " + getCharacterDataFromElement(line));
}
}

private static String getCharacterDataFromElement(Element e) {
// TODO Auto-generated method stub
Node child = e.getFirstChild();
if (child instanceof org.w3c.dom.CharacterData) {
org.w3c.dom.CharacterData cd = (org.w3c.dom.CharacterData) child;
return cd.getData();
}
return "?";
}

}

代码中是否缺少任何内容?

最佳答案

因为我现在还没有准备好编译器,所以我不确定这是否完美。尝试一下并报告:

....
Document doc = builder.parse(is);
NodeList nodes = doc.getElementsByTagName("list");
for (int i = 0; i < nodes.getLength(); i++) {
Element element = (Element) nodes.item(i);
NodeList name = element.getElementsByTagName("string");
for (int x = 0; x < name.getLength(); x++) {
Element line = (Element) name.item(x);
System.out.println("String: " + getCharacterDataFromElement(line));
}
}
....

我认为这应该是你所追求的。

关于java - 使用 Java 仅迭代一个 xml 标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34352820/

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