2011-01-11 7 views
2

Maintenant, ce code analyse correctement le fichier XML, cependant, dans le fichier XML que j'ai plusieurs nœuds auteur, j'aimerais pouvoir mettre une virgule entre chaque auteur. Le XML varie d'un à un à quatre auteurs. Merci d'avance.Comment sélectionner des nœuds enfants XML dans jQuery?

/* Load XML File */ 
$.ajax({ 
    url: "xml/ajax-response-data.xml", 
    cache: false, 
    success: libraryXML 
}); 

function libraryXML (xml) { 
    $(xml).find('book').each(function(){ 

      /* Parse the XML File */ 
     var id = $(this).attr('id'); 
     var checked = $(this).attr('checked-out') 
     var title = $(this).find('title').text(); 
     var isbn = $(this).find('isbn-10').text(); 
     var authors = $(this).find('authors').text(); 


     /* Spit out some books */ 
     $('<li class="book-'+id+' checked'+checked+'"></li>').html('<span class="id">' + id + '</span><span class="title">' + title + '</span><span class="author">' + authors +'</span><span class="isbn">' + isbn + '</span>').appendTo('.library'); 

    }); 
} 

<book id="1" checked-out="1"> 
    <authors> 
    <author>David Flanagan</author> 
    </authors> 
    <title>JavaScript: The Definitive Guide</title> 
    <isbn-10>0596101996</isbn-10> 
</book> 
<book id="2" checked-out="1"> 
    <authors> 
    <author>John Resig</author> 
    </authors> 
    <title>Pro JavaScript Techniques (Pro)</title> 
    <isbn-10>1590597273</isbn-10> 
</book> 
<book id="3" checked-out="0"> 
    <authors> 
    <author>Erich Gamma</author> 
    <author>Richard Helm</author> 
    <author>Ralph Johnson</author> 
    <author>John M. Vlissides</author> 
    </authors> 
    <title>Design Patterns: Elements of Reusable Object-Oriented Software</title> 
    <isbn-10>0201633612</isbn-10> 
</book> 

Répondre

1

Je changerais votre code à quelque chose comme ceci:

function libraryXML (xml) { 
    $(xml).find('book').each(function(){ 

    /* Parse the XML File */ 
    var id = $(this).attr('id'); 
    var checked = $(this).attr('checked-out') 
    var title = $(this).find('title').text(); 
    var isbn = $(this).find('isbn-10').text(); 
    var authors = $(this).find('authors'); 

    /* Spit out some books */ 
    $('<li></li>') 
     .addClass('book-'+id).addClass('checked'+checked) 
     .append($('<span class="id"></span>').text(id)) 
     .append($('<span class="title"></span>').text(title)) 
     .append($('<span class="author"></span>').text($.map(authors, function(author){ return $(author).text() }).join(', '))) 
     .append($('<span class="isbn"></span>').text(isbn)) 
     .appendTo('.library'); 
    }); 
} 

Les avantages sont qu'il fait l'auteur séparés par des virgules, comme vous vouliez, mais il empêche également les attaques XSS dans le généré HTML en utilisant jQuery's text function pour HTML-échapper la sortie.

Questions connexes