[英]Xml Dom parsing returning null
I am new to html and javascript. 我是html和javascript的新手。 I have been trying to parse and access the data of an xml file through the javascript code. 我一直在尝试通过javascript代码解析和访问xml文件的数据。 Presently it is showing null. 目前它显示为空。 I am posting my codes below. 我在下面发布我的代码。 Please have a look and do help. 请看看并提供帮助。
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>
I'm not sure what exactly you mean by "it is showing null", but maybe changing your code to using onload
callback would help: 我不确定“显示为空”的确切含义,但也许将代码更改为使用onload
回调会有所帮助:
var xhttp;
xhttp = new XMLHttpRequest();
xhttp.onload = function() {
myFunction(this);
};
Also, this line: txt += x[i].childNodes[0].nodeValue + "<br>";
另外,这一行: txt += x[i].childNodes[0].nodeValue + "<br>";
will throw an exception since childNodes[0]
is undefined
in your XML document. 由于XML文档中undefined
childNodes[0]
因此将引发异常。
EDIT: 编辑:
To make x[i].childNodes[0]
non-null, you must move the desired attribute to be the child element's text value. 要使x[i].childNodes[0]
不为空,必须将所需的属性移动为子元素的文本值。 For instance, if you replace: 例如,如果您替换:
<Ping Commkey="A3070000AA00A4" Value="A309008001043101A4"/>
with: 有:
<Ping>
<Commkey key="A3070000AA00A4">
A309008001043101A4
<Commkey/>
<Ping/>
(and do the same to the rest of the elements) then you'll have something like: (并对其余元素执行相同操作),那么您将得到类似以下内容的信息:
<p id="demo">
A309008001043101A4<br>
A309038001013101A4<br>
A3091D8101014C01A4<br>
</p>
as your HTML. 作为您的HTML。
If that's not the exact HTML outcome you want please show an example HTML so I'll be able to help. 如果这不是您想要的确切HTML结果,请显示HTML示例,以便我提供帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.