gpt4 book ai didi

java - 如何使用 DOM XML 解析器解析 XML 文档

转载 作者:行者123 更新时间:2023-12-01 13:41:58 27 4
gpt4 key购买 nike

我有一个 xml 文档,如下所示:

<travellingSalesmanProblemInstance>
<name>blabla</name>
<source>TSPLIBRARY</source>
<description>52 locations in Nowhere</description>
<doublePrecision>15</doublePrecision>
<ignoredDigits>5</ignoredDigits>

<graph>
<vertex>
<edge cost="6.661080993352356e+02">1</edge>
<edge cost="2.811138559374119e+02">2</edge>
<edge cost="3.956008088970497e+02">3</edge>
<edge cost="2.912043955712207e+02">4</edge>
</vertex>
<vertex>
<edge cost="2.561080993352356e+02">0</edge>
<edge cost="2.711138559374119e+02">2</edge>
<edge cost="6.556008088970497e+02">3</edge>
<edge cost="7.9112043955712207e+02">4</edge>
</vertex>
...
</graph>
</travellingSalesmanProblemInstance>

我尝试读取此 xml 文件。但我失败了。

我用这个浏览所有 < vertex > 标签:

NodeList nList = doc.getElementsByTagName("vertex");
for (int i = 0; i < nList.getLength(); i++)
{

但是如何获取这些 标签内的所有 元素呢?

谢谢!!

最佳答案

只需使用结果列表中的每个节点进行另一次选择

NodeList nList = doc.getElementsByTagName("vertex");
NodeList edgeList;

// For each vertex, get all "edge" children
for (int i = 0; i < nList.getLength(); i++) {
edgeList = ((Element)nList.item(i)).getElementsByTagName("edge");

// For each edge under this vertex, do something
for (int j = 0; j < edgeList.getLength(); j++) {

// test that it works
System.out.println(edgeList.item(j).getTextContent());
}
}

关于java - 如何使用 DOM XML 解析器解析 XML 文档,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20665543/

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