简体   繁体   中英

How to parese XML Doc with DOM XML Parser

i have an xml document what looks like this:

<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>

I tried to read this xml-file. But i fail.

I go through all < vertex > tags with this:

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

but howto get all the < edge > elements within these < vertex > tags?

Thanks!!

Just do another select using each node in your result list

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());
    }
}

probably

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

untested but it should be something like this

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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