如何在jQuery中选择xml子节点?

时间:2011-01-11 19:04:53

标签: jquery xml ajax siblings

现在这段代码很好地解析了XML文件,但是,在我有多个作者节点的XML文件中,我希望能够在每个作者之间加上逗号。 XML从一个到一个到四个不等。提前谢谢你。

/* 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>

1 个答案:

答案 0 :(得分:1)

我会将您的代码更改为以下内容:

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');
  });
}

它的优点是它可以像你想要的那样使用逗号分隔的作者,但它也可以通过使用jQuery's text function对HTML输出来阻止生成的HTML中的任何XSS攻击。

相关问题