So I'm a beginner in XML DOM and JavaScript but I've run into an issue. I'm using the script to display my XML data in a table on an existing site. The problem comes in nesting a loop in my JavaScript code.
Here is my XML:
<?xml version="1.0" encoding="utf-8"?>
<book_list>
<author>
<first_name>Mary</first_name>
<last_name>Abbott Hess</last_name>
<books>
<title>The Healthy Gourmet Cookbook</title>
</books>
</author>
<author>
<first_name>Beverly</first_name>
<last_name>Bare Bueher</last_name>
<books>
<title>Cary Grant: A Bio-Bibliography</title>
<title>Japanese Films</title>
</books>
</author>
<author>
<first_name>James P.</first_name>
<last_name>Bateman</last_name>
<books>
<title>Illinois Land Use Law</title>
</books>
</author>
</book_list>
I then use this JavaScript code to read and display the data:
> <script type="text/javascript"> if
> (window.XMLHttpRequest) {
> xhttp=new XMLHttpRequest(); } else
> // Internet Explorer 5/6 {
> xhttp=new
> ActiveXObject("Microsoft.XMLHTTP");
> } xhttp.open("GET","books.xml",false);
> xhttp.send("");
> xmlDoc=xhttp.responseXML;
>
> document.write("<table>"); var
> x=xmlDoc.getElementsByTagName("author");
> for (i=0;i<x.length;i++) {
> document.write("<tr><td>");
> document.write(x[i].getElementsByTagName("first_name")[0].childNodes[0].nodeValue);
> document.write(" ");
> document.write(x[i].getElementsByTagName("last_name")[0].childNodes[0].nodeValue);
> document.write("</td><td>");
> document.write(x[i].getElementsByTagName("title")[0].childNodes[0].nodeValue);
> document.write("</td></tr>"); }
> document.write("</table>"); </script>
The code works well except it only returns the first title element of each author. I somewhat understand why it's doing that, but I don't know how to nest another loop so when the script runs it displays all the titles for an author, not just the first. Whenever I try to nest a loop it breaks the entire script.