Kaj
Kaj

Reputation: 2503

Java xml parser loop

I have this xml file:

<root>
    <application>
        <interface />
        <interface />
    </application>

    <datatransmit>
        <interface />
    </datatransmit>
</root>

What I am trying to do is first do a loop through the interfaces within the <application> tags and then another loop through the interfaces withing the <datatransmit> tags.

I tried this with this Java code:

NodeList application = doc.getElementsByTagName("application");
for (int i = 0; i < application.getLength(); i++) {
    NodeList interfaces = doc.getElementsByTagName("interface");
    for (int j = 0; j < interfaces.getLength(); j++) {
        do some stuff...
    }
}

I noticed that with this loop, it goes through a loop of all the interface elements. Not just the interfaces withing the application tags but also the interfaces within datatransmit. What would be a way to solve this?

Upvotes: 1

Views: 1790

Answers (4)

NickJ
NickJ

Reputation: 9559

Nearly there.

Your problem is using doc as your root again in:

NodeList interfaces = doc.getElementsByTagName("interface");

Meaning it will search the whole document. Instead, you should use the getElementsByTagName method on the application Element, to limit the range of your search:

NodeList application = doc.getElementsByTagName("application");
for (int i = 0; i < application.getLength(); i++) {
  Element applicationElement = (Element) application.item(i);
  NodeList interfaces = applicationElement.getElementsByTagName("interface");
  for (int j = 0; j < interfaces.getLength(); j++) {
    do some stuff...
  }
}

Upvotes: 2

rbennett485
rbennett485

Reputation: 2163

See the javadoc here

getElementsByTagName() returns all descendants, and since you call doc.getElementsByTagName() you get all descendants of doc which match the element name, rather than all descendants of your application element

Upvotes: 2

Ninad Pingale
Ninad Pingale

Reputation: 7079

As you are lopping through all elements from document you are getting all elements.

doc.getElementsByTagName("interface");

You should get elements from each application tag object.

Upvotes: 1

Brian Agnew
Brian Agnew

Reputation: 272317

You need to get the list of application nodes from here:

for (int i = 0; i < application.getLength(); i++) {
   Node appNode = application.item(i);
   ....
}

and inspect the name/tag of the node via getNodeName() for the value interface.

That applies for getting interface as a child of application. If interface only occurs under application, then you can skip the first step and simply do

NodeList interfaces = doc.getElementsByTagName("interface");

Perhaps a more concise/flexible solution would be to use XPath, with a path such as /root/application/interface ?

Upvotes: 1

Related Questions