簡體   English   中英

使用JavaScript在HTML中顯示XML數據

[英]Using javascript to display XML data in HTML

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

在這里,我已經為您修復了解析邏輯。

而且,這是發生魔術的地方:

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表結構。

我正在獲取值...(但是未定義,因為它們內部沒有任何文本)。

檢查所有拼寫錯誤。 並且我修改了document.write(x[i].getElementsByTagName("ResourcesInfo")[0].childNodes[0].nodeValue);

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

順便說一句,您的預期輸出是多少? 這是我的截圖...

在此處輸入圖片說明

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM