计算节点数不起作用

counting the number of nodes is not working

本文关键字:不起作用 节点 计算      更新时间:2023-09-26

我有一个 xml 文件:

<?xml version="1.0" encoding="ISO-8859-1"?>
<food>
    <cuisine type="Chinese">
        <restaurant name = "Panda Express">
            <location id= "0"></location>
            <phone id = "1"></phone>
            <city id="2"></phone>
        </restaurant>
        <restaurant name = "Mr. Chau's">
        </restaurant>
    </cuisine>
    <cuisine type="Indian">
        <restaurant name = "Shan">
        </restaurant>
    </cuisine>
</food>

我正在尝试计算美食节点的数量,这是我拥有的代码,我知道它基本上是正确的,但是当我尝试打印出节点列表的长度时,它说它是 0

//starts talking to the xml document
        if(window.XMLHttpRequest){
            xmlhttp = new XMLHttpRequest();
        }else{
            xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
        }
        xmlhttp.open("GET","data.xml", false);
        xmlhttp.send();
        xmlData = xmlhttp.responseXML;

        //fills the first comboBox
        var sel = document.getElementById('CuisineList');
        cuisineList = xmlData.getElementsByTagName('cuisine');
        document.getElementById("test").innerHTML = cuisineList.length;

两个可能的答案:

A) XML 有错误,您需要</phone> </city>。所以你需要解决这个问题。:-)(但我猜这只是问题,而不是你的真实数据,因为如果它在你的真实数据中,你就不会得到0,我不认为;你会得到一个错误。

B) 检查您的响应标头,可能是您的服务器没有返回具有正确 MIME 类型的 XML。如果没有:

  1. 最佳答案是更正服务器配置,以便它正确提供 XML 文件。

  2. 如果出于某种原因无法执行此操作,则可以使用 overrideMimeType 强制XMLHttpRequest将响应视为 XML:

    xmlhttp.open("GET","data.xml", false);
    xmlhttp.overrideMimeType("text/xml"); // <=== The new bit
    xmlhttp.send();
    xmlData = xmlhttp.responseXML;
    

如果您修复了这些问题,它可以工作:实时工作副本 | 来源