gpt4 book ai didi

javascript - 使用 javascript 在 HTML 中显示 XML 数据

转载 作者:行者123 更新时间:2023-11-30 17:41:40 25 4
gpt4 key购买 nike

您好,目前我有以下 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>

谁能帮忙??我按照 w3school 中的示例并尝试将其写出来,但它告诉我以下错误。

TypeError: x[i].getElementsByTagName(ResourcesInfo)[0].childNodes[0] 未定义。

最佳答案

Here我已经为您修复了解析逻辑。

神奇的地方就在这里:

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>");
}

摆弄代码以解析和创建所需的 HTML 表格结构。

关于javascript - 使用 javascript 在 HTML 中显示 XML 数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20944156/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com