我有一个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文件。但我失败了。
我经历了所有&lt;顶点&gt;标签:
NodeList nList = doc.getElementsByTagName("vertex");
for (int i = 0; i < nList.getLength(); i++)
{
但如何得到所有&lt;边缘&gt;这些中的元素&lt;顶点&gt;标签
谢谢!
答案 0 :(得分:1)
使用结果列表中的每个节点再做一次选择
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());
}
}
答案 1 :(得分:0)
可能
for(..){
NodeList edges = nList.get(i).getElementsByTagName("edge");
for(Node edge: edges){
// do something with the edge
}
}
未经测试,但它应该是这样的