Reputation: 1108
I'm just wondering if it is possible to remove a node from XML with Jquery without having to replace the whole file every time? For example, if i have an xml file
<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>
Would it be possible to just remove the below so there will just be 2 nodes?
<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>
I am thinking of doing this on a bigger scale so would like to learn ho to do it.
Thanks
Upvotes: 1
Views: 874
Reputation: 74738
You can create a virtual element in your code as in the answer below, document.createElement()
or jQuery('<tag>', {options})
will do. You can put the xml
data in it then just use a each loop to find the desired text and remov the parent xml tag which holds it.
You can use this:
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>
As per your comment:
I'm loading the xml through Ajax, its in another file
You can call the same action in your ajax success callback:
$.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.
}
});
Upvotes: 1
Reputation: 2204
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();
}
});
}
});
Upvotes: 0