2016-11-25 205 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]在这里有效吗? –