1

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?

Kaj
  • 2,445
  • 3
  • 23
  • 34
  • Replace `NodeList interfaces = doc.getElementsByTagName("interface");` with `NodeList interfaces = ((Element) application.get(i)).getElementsByTagName("interface");` – Oleg Estekhin May 21 '14 at 10:03

4 Answers4

2

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

rbennett485
  • 1,907
  • 15
  • 24
2

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...
  }
}
NickJ
  • 9,380
  • 9
  • 51
  • 74
1

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 ?

Community
  • 1
  • 1
Brian Agnew
  • 268,207
  • 37
  • 334
  • 440
1

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.

Ninad Pingale
  • 6,801
  • 5
  • 32
  • 55