The error is pretty obvious: both loops are limited to
x.length
iterations.
What is
x
? It's the child nodes of the first book element.
The first book element contains four child nodes. As a result, you attempt to read four book elements - that
happens to be the right number, but only accidentally - and you attempt to read four child elements of each book node. Books 1, 2 and 4 have four child elements, but book 3 has eight child elements.
Fix your loops and the code will work properly, regardless of how many books there are, and how many child elements they have:
xmlDoc = xmlhttp.responseXML;
var z = xmlDoc.getElementsByTagName("book");
for (var k = 0; k < z.length; k++) {
var x = z[k].childNodes;
for (var i = 0; i < x.length; i++) {
var y = x[i];
if (y.nodeType == 1) {
document.write(y.nodeName + ":" + y.firstChild.nodeValue + "<br />");
}
}
document.write("-------------------<br/>");
}