使用javascript以HTML格式显示XML数据

时间:2014-01-06 06:17:08

标签: javascript html xml nodes

您好我目前有以下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] is undefined.

2 个答案:

答案 0 :(得分:2)

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表结构。

答案 1 :(得分:0)

我正在获取值...(虽然未定义,因为它们内部没有任何文本)。

检查任何拼写错误。我已经修改过 document.write(x[i].getElementsByTagName("ResourcesInfo")[0].childNodes[0].nodeValue);

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

BTW您的预期产量是多少?这是我的截图...

enter image description here