我如何使用DOM XML解析器
问题描述:
parese XML文档有一个XML文档看起来是这样的:我如何使用DOM 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文件。但我失败了。
我经历的所有<顶点>标签与此:
NodeList nList = doc.getElementsByTagName("vertex");
for (int i = 0; i < nList.getLength(); i++)
{
但HOWTO得到所有<边缘>这些<顶点>标签中的元素?
谢谢!
答
只是做另一个选择使用的每个节点在结果列表
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());
}
}
答
可能
for(..){
NodeList edges = nList.get(i).getElementsByTagName("edge");
for(Node edge: edges){
// do something with the edge
}
}
未经测试,但它应该是这样的