使用javascript在HTML中显示XML数据

使用javascript在HTML中显示XML数据,javascript,html,xml,nodes,Javascript,Html,Xml,Nodes,您好,目前我有以下XML文件和脚本 <ResourcesList> <ResourceGroup type = "HUMANS"> <ResourcesInfo JobPosition = "Station Manager" OnDuty = "40" OnLeave_Local = "1" OnLeave_Oversea = "1" MC = "2" /> <ResourcesInfo

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

if(window.XMLHttpRequest)
{//IE7+、Firefox、Chrome、Opera、Safari的代码
xmlhttp=新的XMLHttpRequest();
}
其他的
{//IE6、IE5的代码
xmlhttp=新的ActiveXObject(“Microsoft.xmlhttp”);
}
open(“GET”,“ResourceList.xml”,false);
xmlhttp.send();
xmlDoc=xmlhttp.responseXML;
文件。填写(“”);
var x=xmlDoc.getElementsByTagName(“资源组”);

对于(i=0;i我得到的是值…(虽然没有定义,因为里面没有任何文本)

检查拼写错误。我已经修改了
document.write(x[i].getElementsByTagName(“ResourcesInfo”)[0].childNodes[0].nodeValue);
to

document.write(x[i].getElementsByTagName(“ResourcesInfo”)[0].childNodes[0]);

顺便问一下,你的预期输出是什么?这是我的截图

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

这里是魔法发生的地方:

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>");
}
document.write(“”);
var x=xmlDoc.getElementsByTagName(“资源组”);
对于(i=0;i

修改代码以解析和创建所需的HTML表结构。

您可以使用XSLT显示XML数据。这可能比使用javascript解析XML更快。