4

I am trying to iterate through the xml with jquery and posting it on html. For some reason the each function in authors is appending duplicates. For example, I will get James McgovernPer BothnerKurt BothernerKurt CagleJames Linn Valiyanathan Nagarjan, James McgovernPer BothnerKurt BothernerKurt CagleJames Linn Valiyanathan Nagarjan. I was wondering how can I fix this? Thanks!

<book category="web">
<title lang="en">XQuery Kick Start</title>
<author>James McGovern</author>
<author>Per Bothner</author>
<author>Kurt Cagle</author>
<author>James Linn</author>
<author>Vaidyanathan Nagarajan</author>

$(document).ready(function() {
$.ajax({

     url: "books.xml",
     dataType: "xml",
     success: function(data) {

        $(data).find('book').each(function(){
        var category = $(this).attr('category');
        var title = $(this).find('title').text();
        var year = $(this).find('year').text();
        var price = $(this).find('price').text();
        var author = $(this).find('author').text();

        $(this).find('author').each(function(){
            author += $(this).text();
            author += ',';
        });

        var r = '<tr>';
        r += '<td>' + title + '</td>';
        r += '<td>' + author + '</td>';
        r += '<td>' + year + '</td>';
        r += '<td>' + price + '</td>';
        r += '<td>' + category + '</td>';

        $('table').append(r);
        });

     },
     error: function() { alert("error loading!");  }
 });

});

2 Answers 2

2

You are first setting auther to $(this).find('author').text(), and THEN appending the rows in the each. This causes the list to be repeated.

You should probably just replace the first assignment with a var author = ''.

Sign up to request clarification or add additional context in comments.

Comments

2

need to replace

var author = $(this).find('author').text();

with

var author ='';

the first one will concatenate the text of all of those elements without any spaces ... and then you are looping over the elements individually and adding to it.

To get rid of the trailing comma in author can change to:

var author =[];
$(this).find('author').each(function(){
    author.push( $(this).text());
});    
author = author.join(', ');

// or

var author = $(this).find('author').map(function(){
      return $(this).text();
}).get().join(', ');

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.