Java XML getElementsByTagName() 函数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5614460/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 11:55:17  来源:igfitidea点击:

Java XML getElementsByTagName() function

javaxmlgetelementsbytagname

提问by Alexus48

Lets say i have this XML file:

假设我有这个 XML 文件:

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

节点属性上的 getElementsByTagName("attack") 是否返回一个 NodeList,其中攻击元素在第一个位置包含 26,攻击元素在第二个位置包含 33?

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?

如果不是这么简单;从 XML 文件中获取所有攻击值的好方法是什么?也许 XML 文件本身的结构很糟糕?

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

编辑:啊。我现在得到了节点,并且 .getTextContent() 而不是 .getNodeValue() 解决了我的问题。带来不便敬请谅解。

回答by Alohci

Dom Core 2 Specsays:

Dom Core 2 规范说:

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.

getElementsByTagName

返回具有给定标记名称的所有后代元素的 NodeList,按照它们在此元素树的先序遍历中遇到的顺序。

And Dom Core 3 Specsays:

DOM核心3规格说:

getElementsByTagName

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

getElementsByTagName

按文档顺序返回具有给定标签名称的所有后代元素的 NodeList。

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.

所以你对这个函数的期望是正确的。如果这不是您所得到的,那将是您的代码或您正在使用的库中的错误。

回答by jt78

I've never worked with XML in Java but surely you could just for loop through the elements and check each one for the attack key.? Sorry if that's not what you're looking for, it's just what I'd do because I have no knowledge of the XML classes in Java. Hope it helps though.

我从来没有在 Java 中使用过 XML,但你肯定可以循环遍历元素并检查每个元素的攻击密钥。?抱歉,如果这不是您要找的,那正是我要做的,因为我不了解 Java 中的 XML 类。希望它有帮助。