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

标签 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>

最佳答案

我会将您的代码更改为如下所示:

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 中的任何 XSS 攻击。对输出进行 HTML 转义。

关于jquery - 如何在 jQuery 中选择 xml 子节点?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4661542/

相关文章:

javascript - AJAX 刷新延迟/不一致

javascript - [对象对象]是什么意思? (JavaScript)

javascript - 滚动 jQuery

android - 在 Seekbar Android 中使用 rotation = 270 时无法正确指定高度和宽度

java - Android ActionBar - 项目图标不断变化?

javascript - Rails 的远程表单 `disable_with` 功能完成后如何执行 Javascript?

javascript - 如何仅使用 CSS 动态更改与父宽度相关的元素宽度?

javascript - 在按钮上单击显示信息向上滑动并使用 jQuery 向上插入按钮

sql-server - 使用基于连接的当前节点值从辅助表更新 xml 节点值

javascript - 将字母数字变量传递给 JQuery Ajax