Java XML getElementsByTagName() function

Alexus48 picture Alexus48 · Apr 10, 2011 · Viewed 11.3k times · Source

Lets say i have this XML file:

<attributes>
  <units>
    <civilians>
      <unit>
        <name>Settler</name>
        <stats>
          <attack>26</attack>
          <defence>7</defence>
        </stats>
        <costs>
          <lumber/>
          <iron/>
        </costs>
      </unit>
      <unit>
        <name>Infantry</name>
        <stats>
          <attack>33</attack>
          <defence>7</defence>
        </stats>
        <costs>
          <lumber/>
          <iron/>
        </costs>
      </unit>
    </civilians>
  </units>
</attributes>

Does getElementsByTagName("attack") on the node attributes return a NodeList with the attack element containing 26 at first position and the attack element containing 33 at second position?

I've been thinking this is the case but it doesn't seem to work.

If it isn't as simple as this; what is a good way to grab all attack values from the XML file? Maybe the XML file itself is badly structured?

Edit: Ah. I get the nodes now, and .getTextContent() rather than .getNodeValue() solved my problems. Sorry for the inconvenience.

Answer

Alohci picture Alohci · Apr 10, 2011

Dom Core 2 Spec says:

getElementsByTagName

Returns a NodeList of all descendant Elements with a given tag name, in the order in which they are encountered in a preorder traversal of this Element tree.

And Dom Core 3 Spec says:

getElementsByTagName

Returns a NodeList of all descendant Elements with a given tag name, in document order.

So your expectations for the function are correct. If that's not what you're getting it would be a bug in your code or in the library you're using.