2016-11-25 208 views
0

我是新來的HTML和JavaScript。我一直試圖通過JavaScript代碼解析和訪問XML文件的數據。目前它顯示爲空。我在下面發佈我的代碼。請看看,並幫助。Xml Dom解析返回null

Html code: 

     <!DOCTYPE html> 
    <html> 
    <meta http-equiv="content-type" content="text/html; charset=utf-8" /> 
    <body> 

    <p id="demo"></p> 

    <script> 
    var xhttp; 
    xhttp = new XMLHttpRequest(); 
    xhttp.onreadystatechange = function() { 
     if (this.readyState == 4 && this.status == 200) { 
      myFunction(this); 
     } 
    }; 
    xhttp.open("GET", "http://10.21.64.222/LoadBreakSwitch/LBS_Commands.xml", true); 
    xhttp.send(); 

    function myFunction(xml) { 
     var x, i, txt, xmlDoc; 
     xmlDoc = xml.responseXML; 
     txt = ""; 
     x = xmlDoc.getElementsByTagName("Ping"); 
     for (i = 0; i < x.length; i++) { 
      txt += x[i].childNodes[0].nodeValue + "<br>"; 
     } 
     document.getElementById("demo").innerHTML = txt; 
    } 
    </script> 
    </body> 
    </html> 

The xml file: 

    <?xml version="1.0" encoding="utf-8"?> 

<LBSCommands> 
    <Ping Commkey="A3070000AA00A4" Value="A309008001043101A4"/> 
    <Frequency Commkey="A3070300AD00A4" CommValue="A309038001013101A4"/> 
    <SwitchStatus Commkey="A3071D01C800A4" CommValue="A3091D8101014C01A4"/> 

</LBSCommands> 
+1

你的代碼看起來很好。您正在訪問「」Ping「的nodeValue,該值爲null。您可能想要執行'getAttribute(「Commkey」)'或'getAttribute(「Value」)'而不是'nodeValue'。如果你想獲得nodeValue,你的Ping應該是''Ping Commkey =「A3070000AA00A4」Value =「A309008001043101A4」> my ping',那麼nodeValue就會是我的ping。 – phoa

+0

@ phoa-謝謝你的回覆。但即使在使用getAttribute之後,也會出現錯誤。 –

+0

我的意思是'txt + = x [i] .getAttribute('Value')+「
」' – phoa

回答

0

我不知道究竟你的「它顯示空」的意思,但也許改變你的代碼使用onload回調將有助於:

var xhttp; 
xhttp = new XMLHttpRequest(); 
xhttp.onload = function() { 
    myFunction(this); 
}; 

另外,該線路:txt += x[i].childNodes[0].nodeValue + "<br>";會拋出異常,因爲childNodes[0]undefined在您的XML文檔中。

編輯:

爲了x[i].childNodes[0]非空,則必須將所需的屬性是子元素的文本值。舉例來說,如果你更換:

<Ping Commkey="A3070000AA00A4" Value="A309008001043101A4"/> 

有:

<Ping> 
    <Commkey key="A3070000AA00A4"> 
     A309008001043101A4 
    <Commkey/> 
<Ping/> 

(做同樣的元素的其餘部分),那麼你就會有類似:

<p id="demo"> 
     A309008001043101A4<br> 
     A309038001013101A4<br> 
     A3091D8101014C01A4<br> 
</p> 

作爲你的HTML。

如果這不是您想要的確切HTML結果,請顯示一個示例HTML,以便我能夠提供幫助。

+0

@ Elist-有什麼辦法可以讓childNodes [0]在這裏有效嗎? –