[英]Using javascript to display XML data in HTML
Hi currently I have the following XML file and my script. 您好,目前我有以下XML文件和脚本。
<ResourcesList>
<ResourceGroup type = "HUMANS">
<ResourcesInfo JobPosition = "Station Manager" OnDuty = "40" OnLeave_Local = "1" OnLeave_Oversea = "1" MC = "2" />
<ResourcesInfo JobPosition = "Deputy Station Manager" OnDuty = "82" OnLeave_Local = "5" OnLeave_Oversea = "5" MC = "2" />
</ResourceGroup>
<ResourceGroup type = "MACHINES">
<ResourcesInfo MachineName = "Leopard 2SG" MachineID = "SB1420J" MachineType = "Battle Tank" Available = "15" NotAvailable = "2" />
<ResourcesInfo MachineName = "M113A2 ULTRA OWS" MachineID = "SS4020J" MachineType = "Transport Vechicle" Available = "50" NotAvailable = "21" />
</ResourceGroup>
</ResourcesList>
<script>
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.open("GET","ResourceList.xml",false);
xmlhttp.send();
xmlDoc=xmlhttp.responseXML;
document.write("<table border='1'>");
var x=xmlDoc.getElementsByTagName("ResourceGroup");
for (i=0;i<x.length;i++)
{
document.write("<tr><td>");
document.write(x[i].getElementsByTagName("ResourcesInfo")[0].childNodes[0].nodeValue);
}
document.write("</table>");
</script>
Anybody can help?? 有人可以帮忙吗? I followed the example in w3school and tried writing it out but it tells me the following error.
我按照w3school中的示例进行操作,并尝试将其写出,但是它告诉我以下错误。
TypeError: x[i].getElementsByTagName(ResourcesInfo)[0].childNodes[0] is undefined.
TypeError:
x[i].getElementsByTagName(ResourcesInfo)[0].childNodes[0] is undefined.
Here I've fixed the parsing logic for you. 在这里,我已经为您修复了解析逻辑。
And, here's where magic happens: 而且,这是发生魔术的地方:
document.write("<table border='1'>");
var x = xmlDoc.getElementsByTagName("ResourceGroup");
for (i = 0; i < x.length; i++) {
document.write("<tr>");
var y = x[i].getElementsByTagName("ResourcesInfo");
for (j = 0; j < y.length; j++) {
if (x[i].getAttribute("type") == "HUMANS") {
document.write("<td>" + y[j].getAttribute('JobPosition') + "</td>");
} else {
document.write("<td>" +y[j].getAttribute('MachineName') + "</td>");
}
}
document.write("</tr>");
}
document.write("</table>");
}
Fiddle with the code to parse and create the desired HTML table structure. 摆弄代码以解析和创建所需的HTML表结构。
I am getting the values... (undefined though, as they don't have any text inside). 我正在获取值...(但是未定义,因为它们内部没有任何文本)。
Check any spelling mistakes. 检查所有拼写错误。 And I have modified
document.write(x[i].getElementsByTagName("ResourcesInfo")[0].childNodes[0].nodeValue);
并且我修改了
document.write(x[i].getElementsByTagName("ResourcesInfo")[0].childNodes[0].nodeValue);
to 至
document.write(x[i].getElementsByTagName("ResourcesInfo")[0].childNodes[0]);
. 。
BTW What is your expected output ? 顺便说一句,您的预期输出是多少? Here is a screenshot of mine...
这是我的截图...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.