How do I select xml child nodes in jQuery?

旧时模样 提交于 2019-12-24 03:31:14

问题


Right now this code parses the XML file fine, however, in the XML file I have multiple author nodes, I'd like to be able to put a comma in between each author. The XML varies from one to from one to four authors. Thank you ahead of time.

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


I'd change your code to something like this:

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

The advantages are that it does the comma-separated author, like you wanted, but it also prevents any XSS attacks in the generated HTML by using jQuery's text function to HTML-escape the output.



来源:https://stackoverflow.com/questions/4661542/how-do-i-select-xml-child-nodes-in-jquery

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!