I am currently experimenting with the HttpXMLRequest object in JS and have created a basic loop that retrieves name and age data from an XML file to display in a table. The issue I am facing is that if one of the elements is missing from a sibling, the code stops running instead of skipping it. Here is an example of the 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>
As shown in the example above, the HTML code stops after writing "Bob". I believe there needs to be some sort of error handling mechanism such as try/catch or an if statement for each name and age value, but I'm struggling to implement it effectively. Does anyone have any suggestions?
I have attempted to research this issue, but without knowing what it is called, I am not finding relevant information.
Simply inserting "<age />
or <age></age>
" as placeholders is not viable since I will be working with large XML files in the future. If necessary, I am open to creating a function that automatically adds the missing element if it does not exist.
Thank you, Hombries.