tags:

views:

154

answers:

1

I'm getting data back from the server in XML format. The data looks like:

<items>
   <item>
       <field1>10</field1>
       <field2>11</field2>
       <field3>12</field3>
   </item>
   <item>
       <field1>10</field1>
       <field2>11</field2>
       <field3>11</field3>
   </item>
</items>

Is there a way to write a jQuery statement to return only the XML objects where field2 equals field3? I currently use jQuery to filter xml objects that meet certain criteria (using jQuery find and contains, e.g. $("field2:contains(11)")) but I can't come up with the statement to filter the xml where two of the xml fields are equal. I can always convert the XML to javascript arrays and look for equal fields and then return the javascript array as a jQuery object. There just seems like there should be a way to do it with a jQuery statement.

A: 

Try this out:

var xmlData = $('<items>.........');
xmlData.find('item').each(function ()  {
     if($(this).find('field2').text() == $(this).find('field3').text()) {
         alert('Field 2 and Field 3 are equal');
         $(this).find('field3').remove(); //for example, to remove the dupe
     }
});
//then convert it back to a string
//for IE 
if (window.ActiveXObject) {
    var string = xmlData.xml;
    alert(string);
 }
// code for Mozilla, Firefox, Opera, etc.
else {
   var string = (new XMLSerializer()).serializeToString(xmlData);
   alert(string);
}
karim79
Good idea. I want to filter out the xml where the two fields are not equal. This works (although not the way I want):var xml = '<items>.........';$(xml).find('item').each(function () { if($(this).find('field2').text() != $(this).find('field3').text()) { alert('Field 2 and Field 3 are NOT equal'); $(this).empty(); // Empties the contents of <item> }});I tried doing "$(this).remove()" to remove the <item> from the list but that did not work. Not sure why.
MarkS
@MarkS - does the alert work as expected? is it just the remove method?
karim79
Alert works. The remove method does not remove the <item> from the xml list of <items> which is what I was trying to do.
MarkS
@MarkS - I think that is because we were'nt modifying the original variable. Try it out now.
karim79
Thats it. I posted your solution above in the question.
MarkS
@karim79 - Thanks for your help.
MarkS
@MarkS - I removed it from the question because someone will complain otherwise (if I don't, someone else will anyway) but glad you got it working :)
karim79