Java XML function getElementsByTagName ()

Suppose 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") receive node NodeList attributes with an attack element containing 26 in the first position and an attack element containing 33 in the second position?

I thought it was, but it doesn't seem to work.

If it is not as simple as that; What is a good way to capture all attack values ​​from an XML file? Maybe the XML file itself is poorly structured?

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

+4
source share
2 answers

Dom Core 2 Spec says:

getElementsByTagName

Returns the NodeList of all descendant elements with the given name tag, in the order in which they occur when traversing the order of this element tree.

And Dom Core 3 Spec says:

getElementsByTagName

Returns the NodeList of all descendant elements with the given name tag, in document order.

So, your expectations regarding the function are correct. If this is not what you get, it will be a mistake in your code or in the library that you are using.

+7
source

I have never worked with XML in Java, but of course you could just scroll through the elements and check each of them for an attack key.? Sorry if this is not what you are looking for, this is what I would do because I do not know the XML classes in Java. Hope this helps.

-2
source

Source: https://habr.com/ru/post/1347453/


All Articles