Reputation: 121
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.
Upvotes: 2
Views: 13178
Reputation: 15606
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.
Upvotes: 3
Reputation: 1701
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...
Upvotes: 0