使用Jquery从XML中删除节点

时间:2015-12-18 09:42:57

标签: jquery xml

我只是想知道是否可以使用Jquery从XML中删除节点而不必每次都替换整个文件?例如,如果我有一个xml文件

<ArrivingFlights>
<flight>
    <to>Michelle</to>
    <from>Brianna xx</from>
    <imagepath>0001.jpg</imagepath>
    <templateStyle>template1</templateStyle>
    <time>17:00</time>
    <date>18/12/15</date>
</flight>
 <flight>
    <to>Ger</to>
    <from>Mammy xx</from>
    <imagepath>0002.jpg</imagepath>
    <templateStyle>template1</templateStyle>
    <time>08:00</time>
    <date>21/12/15</date>
</flight>
<flight>
    <to>Ciara</to>
    <from>Vikki xx</from>
    <imagepath>0003.jpg</imagepath>
    <templateStyle>template1</templateStyle>
    <time>11:00</time>
    <date>17/12/15</date>
</flight>
</ArrivingFlights>

是否可以删除下面的内容以便只有2个节点?

<flight>
    <to>Michelle</to>
    <from>Brianna xx</from>
    <imagepath>0001.jpg</imagepath>
    <templateStyle>template1</templateStyle>
    <time>17:00</time>
    <date>18/12/15</date>
</flight>

我正在考虑更大规模地这样做,所以想学习这样做。

由于

2 个答案:

答案 0 :(得分:1)

您可以在代码中创建虚拟元素,如下面的答案所示,document.createElement()jQuery('<tag>', {options})即可。您可以将xml数据放入其中,然后只使用每个循环来查找所需的文本,并删除保存它的父xml标记。

您可以使用:

var xmlData = '<ArrivingFlights><flight><to>Michelle</to> <from>Brianna xx</from>    <imagepath>0001.jpg</imagepath>    <templateStyle>template1</templateStyle>    <time>17:00</time>    <date>18/12/15</date></flight> <flight>    <to>Ger</to>    <from>Mammy xx</from>    <imagepath>0002.jpg</imagepath>    <templateStyle>template1</templateStyle>    <time>08:00</time>    <date>21/12/15</date></flight><flight>    <to>Ciara</to>    <from>Vikki xx</from>    <imagepath>0003.jpg</imagepath>    <templateStyle>template1</templateStyle>    <time>11:00</time>    <date>17/12/15</date></flight></ArrivingFlights>';
var xml = $('<div>', {
  html: xmlData
});

$(xml).find('flight').each(function() {
  if ($('to', this).text() === "Michelle") {
    $(this).remove();
  }
});

$('pre').text(xml.html());
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<pre><code></code></pre>

根据你的评论:

我正在通过Ajax加载xml,它在另一个文件

您可以在ajax成功回调中调用相同的操作:

$.ajax({
  /// other options
   success:function(xmlData){
       var xml = $('<div>', { html: xmlData  });  // create a virtual element
       $(xml).find('flight').each(function() {  // loop through the parent elems
           if ($('to', this).text() === "Michelle") { // check the text
               $(this).remove(); // now remove it.
           }
       });

       // here you can do anything with the var xml.

   }
});

答案 1 :(得分:0)

Try this out:

  $(document).ready(function() {
      $.ajax({
        url: xml_url,
        success: function(data) {
          var $flights = $('flight', data);
          $flights.each(function() {
            if ($('to', this).text() == "Michelle") {
              $(this).remove();
            }
          });
        }
      });