2012-07-07 75 views
1

我有一个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; 
+0

强烈建议**不要**做同步ajax请求(即'false'作为'open'的第三个参数使其同步);改为使用*异步*请求和'onreadystatechangehandler'回调。同步ajax请求会导致糟糕的用户体验。 – 2012-07-07 07:40:12

回答

0

两个可能的答案的节点列表的长度:

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; 
    

如果你解决这些,它的工作原理:Live working copy | source

+0

感谢工作:) – Ameya 2012-07-07 07:45:57