获取 nodeValue 时输出为 null

Output is null, when getting the nodeValue

我正在通过 javascript、

中的这段代码获取节点的值
function show(){
        var x = document.getElementsByTagName("allowance")[0];
        var y = x.nodeValue;
        alert(y);
    }

来自 html 中的 xml。

<xml style="display: none">
        <students id="lul">
            <student>
                <name>Mark Fajardo</name>
                <allowance>9999</allowance>
            </student>
            <student>
                <name>Rencie Macale</name>
                <allowance>20</allowance>
            </student>
        </students>
    </xml>

但是警报项目的输出只是空的。帮助

您应该使用 textContent 从 XML 标签中获取文本,因为 nodeValue 只有 returns 文本的文本值XML 中的节点,在元素 节点上,nodeValue 属性 总是null.

function show() {
  var x = document.getElementsByTagName("allowance")[0];
  var y = x.textContent;
  console.log(y);
}

show()
<xml style="display: none">
  <students id="lul">
    <student>
      <name>Mark Fajardo</name>
      <allowance>9999</allowance>
    </student>
    <student>
      <name>Arabella Raymundo</name>
      <allowance>20</allowance>
    </student>
  </students>
</xml>

你也可以像这样使用innerHTML

y = document.getElementsByTagName("allowance")[0].innerHTML;
alert(y);