如何将childNodes用于XML文档

How to use childNodes for XML document?

本文关键字:XML 文档 用于 childNodes      更新时间:2023-09-26

我创建了以下javascript:

<script>
    function stats(cod) {
        var th = document.getElementsByTagName("th");
        var tds = document.getElementsByClassName("pt");
        httpRequest = new XMLHttpRequest();
        httpRequest.onreadystatechange = function() {
            if (httpRequest.readyState == 4 && httpRequest.status == 200) {
                var xmlDoc = httpRequest.responseXML.documentElement;
                th[0].innerHTML = xmlDoc.getElementsByTagName('name')[0].firstChild.nodeValue;
                tds[0].innerHTML = xmlDoc.getElementsByTagName('what')[0].firstChild.nodeValue;
                tds[1].innerHTML = xmlDoc.getElementsByTagName('office')[0].firstChild.nodeValue;
                tds[2].innerHTML = xmlDoc.getElementsByTagName('www')[0].firstChild.nodeValue;
                tds[3].innerHTML = xmlDoc.getElementsByTagName('over')[0].firstChild.nodeValue;
            }
        }
        httpRequest.open("GET","getData.php?codice=" + cod, true);
        httpRequest.send(null);
    }
</script>

我确信这是读取XML内容并将其值分配给表TD的更好方法。我试图使用xmlDoc.getElementsByTagName('response').childNodes;获取包含在xmlDoc中的所有元素的数组,但结果似乎是未定义的。

编辑:

以下是XML:的示例

<response>
    <name>The name</name>
    <what>What is</what>
    <office>The office</office>
    <www>The website</www>
    <over>Yes</over>
</response>

您可以很容易地将response元素作为访问

var response = httpRequest.responseXML.documentElement;

然后,我不会尝试使用childNodes,因为它可以在元素之间包含文本节点,而使用response.children将为您提供子元素,但仅在现代浏览器中使用。在这种情况下,元素还有一个textContent属性,您可以在所有这些firstChild.nodeValue访问的情况下使用:

var childElements = response.children;
th[0].innerHTML = childElements[0].textContent;
tds[0].innerHTML = childElements[1].textContent;
...

另一方面,一旦XML中元素的顺序发生变化或某个元素被省略,您就会读出错误的数据,因此使用例如response.getElementsByTagName('www')[0].textContent来命名有一些优势。

getElementsByTagName返回一个类似数组的元素集合。

特定元素(包括集合的每个成员)可以具有childNodes。该系列本身不会。