我是新来的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>
你的代码看起来很好。您正在访问“”Ping“的nodeValue,该值为null。您可能想要执行'getAttribute(“Commkey”)'或'getAttribute(“Value”)'而不是'nodeValue'。如果你想获得nodeValue,你的Ping应该是''Ping Commkey =“A3070000AA00A4”Value =“A309008001043101A4”> my ping',那么nodeValue就会是我的ping。 – phoa
@ phoa-谢谢你的回复。但即使在使用getAttribute之后,也会出现错误。 –
我的意思是'txt + = x [i] .getAttribute('Value')+“
”' – phoa