Reputation: 61
I'l just trying to pick up using the HttpXMLRequest object in JS and I've got a basic loop that loads name and age from an XML file and throws it into a table. If each sibling has the same values then it loads fine, however if one of the elements is missing from a sibling it stops rather than just skips it. Heres some code.
The HTML -
(The rest of the XML parser and DTD, html, body etc is up here)
<script>
var x=xmlDoc.getElementsByTagName("person");
document.write("<table border='1'>");
for (i=0;i<x.length;i++)
{
var name = x[i].getElementsByTagName("name")[0].childNodes[0].nodeValue;
var age = x[i].getElementsByTagName("age")[0].childNodes[0].nodeValue;
document.write("<tr>");
document.write("<td>"+name+"</td>");
document.write("<td>"+age+"</td>");
document.write("</tr>");
}
document.write("</table>");
</script>
The XML -
(The DTD and stuff it up here)
<people>
<person>
<name>Jim</name>
<age>20</age>
</person>
<person>
<name>Bob</name>
</person>
<person>
<name>Tom</name>
<age>20</age>
</person>
<person>
<name>James</name>
<age>20</age>
</person>
<person>
<name>Richie</name>
<age>20</age>
</person>
</people>
From that example, the HTML will stop after writing once it gets to bob, I assume there needs to be a try/catch or an if in there for each name and age, but I can't seem to place it so it works. Anybody got any ideas?
I've tried to search but I don't know what this issue is called, and describing it doesn't come up with anything.
Simply adding "<age />
or <age></age>
" isn't an option, eventually I'll be working with massive xml files. Unless I need to write something that will automatically add it if it doesn't exist, that's acceptable I guess.
Cheers Hombries.
Upvotes: 0
Views: 401
Reputation: 14123
Check existence of element before trying to access its child nodes:
var personElem = x[i];
var ageElems = personElem.getElementsByTagName("age");
var age = ageElems.length
? ageElems[0].firstChild.nodeValue
: '';
By the way, it's typically easier to use JSON instead of XML. With JSON, your response could look like this:
{
"people": [
{
"name" : "Jim",
"age" : 20
},
{
"name" : "Bob"
}
]
}
And you could access items with dot syntax:
var age = data.people[0].age;
For example, PHP has built-in function for encoding JSON: json_encode()
.
Upvotes: 1