Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to filter xml data using jquery?

  <Item id="419" rank="0.0000" date_added="2012-09-24T19:43:14" date_end="2012-10-15T19:43:14" uid="134333" price="  ,-" district="-1" district_text="Friend" cid="9" cid_text="Underholdning" img_height_thumb="433" />
  <Item id="418" rank="0.0000" date_added="2012-09-24T19:17:42" date_end="2012-10-15T19:17:42" uid="134332" price="  ,-" district="-1" district_text="Friend" cid="9" cid_text="Underholdning" img_height_thumb="254" />
  <Item id="405" rank="102.0000" date_added="2012-09-23T18:55:20" date_end="2012-10-14T18:55:20" uid="134331" price="  102,-" district="-1" district_text="Friend" cid="761" cid_text="Mote" img_height_thumb="280" />

This is sample xml data. And I am using this code to get xml.

 xmlDoc = xmlhttp.responseXML;
 var items = xmlDoc.getElementsByTagName("Item");

//Want to add code

for (i = 0; i < items.length && i < 40; i++) {
var bRank = items[i].getAttribute("rank");
}

//want to add code

I want to filter all data rank which is greater then 0. And I want to add filter only in this palce so my rest code won't change. So how could i filter items variable and get filter values in other variable. so the loop don't get effected. I can change the name of variables in for loop.

Please suggest me any idea for this.

First Edit

xmlDoc = xmlhttp.responseXML;
        var items1 = xmlDoc.getElementsByTagName("Item");

        var items = $(items1).filter('Item').each(function () {
            var bRank = $(this).attr('rank');
            var tempRank = bRank.replace("0000", "").replace(".", "");
            if (tempRank > 0)
                return this;
        });

alert(items.length);
        alert(items1.length);

Answer of both alert is 3.

but answer should like this for first alert 1 and for second alert 3.

but i am getting same response each alert. please check and let me know your suggestion. Thanks

like image 643
Pankaj Mishra Avatar asked May 08 '26 21:05

Pankaj Mishra


1 Answers

Try this,

Live Demo

var items = $('item').filter(function(){
  if(parseFloat($(this).attr('rank')) > 0)
      return this;
});

for (i = 0; i < items.length && i < 40; i++) {
   var bRank = items[i].getAttribute("rank");
}

You will need to add the xml to DOM to apply filter on xml. after that you can remove it.

Live Demo

$('#div1').html(xmlDoc); 
var items = $('#div1 item').filter(function(){
  if(parseFloat($(this).attr('rank')) > 0)
      return this;
});
$('#div1').remove();

for (i = 0; i < items.length && i < 40; i++) {
   var bRank = items[i].getAttribute("rank");
}
like image 190
Adil Avatar answered May 10 '26 12:05

Adil



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!