2012-10-04 33 views
2

爲了更好地理解textConent之間的區別的nodeValue我想找出爲什麼我的代碼使用的nodeValue是行不通的。我有以下XML字符串,它通過AJAX通過jQuery回調加載。如果您查看循環的中心,那麼如果使用nodeValue代替textContent,則該部分將生成空值。的textContent工作,但的nodeValue不

XML

<?xml version="1.0" encoding="UTF-8"?> 
    <Sensors> 
     <Sensor> 
      <id>56</id> 
      <state>false</state> 
     </Sensor> 
    </Sensors> 

我用這個函數下面解析XML。

的JavaScript

function parseSensors(data,status,xhr) { 
     var xml = xhr.responseXML; 
     var sensors = xml.documentElement.childNodes; 

     var list="<ul>";    
     for(var i=0; i < sensors.length; i++) { 
      list= list +"<li>"+sensors[i].childNodes[0].textContent+"</li>";     
     } 
     list=list+"</u>"; 
     document.getElementById("real-time_active_sensors").innerHTML=list;    
    } 
+0

我有同樣的問題是什麼烏斯曼說是corrent: http://stackoverflow.com/questions/23816032/need-help-in-parsing-this-xml-code-with-raw-javascript – ericsicons

回答

1

節點的文本部分實際上是節點本身的孩子。如果一個節點中沒有數據,比如對childNodes [0] .nodeValue的調用將失敗。在嘗試訪問它們之前,您需要檢查有多少個childNodes實際存在。否則,您需要強制執行一個協議,該協議要求創建XML數據時不能包含空標記。

相關問題