简体   繁体   中英

Using javascript to display XML data in HTML

Hi currently I have the following XML file and my script.

<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.

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.

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); to

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

BTW What is your expected output ? Here is a screenshot of mine...

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM