简体   繁体   中英

JavaScript and XML Dom - Nested Loop

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("&nbsp;");  
> 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.

getElementsByTagName("title")[0].childNodes[0].nodeValue

that's why. You take the first title only. Put another loop that will generate all i for getElementsByTagName("title")[i]

My tip: use jquery and write Your code in 3 lines without problems like that.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM