繁体   English   中英

如何使用DOM XML Parser解析XML Doc

[英]How to parese XML Doc with DOM XML Parser

我有一个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());
    }
}

大概

for(..){
    NodeList edges = nList.get(i).getElementsByTagName("edge");
    for(Node edge: edges){
        // do something with the edge
    }
}

未经测试,但应该是这样的

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM