简体   繁体   中英

jquery filter xml data by attribute value

xml code:

<area>
 <point area="54" lat="44.744081" lng="-62.790818" />
 <point area="54" lat="44.743851" lng="-62.792953" />
 <point area="54" lat="44.744439" lng="-62.794366" />
 <point area="55" lat="44.786528" lng="-62.835136" />
 <point area="55" lat="44.787447" lng="-62.835955" />
 <point area="55" lat="44.786528" lng="-62.835136" />
 <point area="56" lat="44.746209" lng="-62.83688" />
 <point area="56" lat="44.745966" lng="-62.836843" />
 <point area="56" lat="44.746246" lng="-62.836481" />
 <point area="56" lat="44.746209" lng="-62.83688" />
</area>

I would like to retrieve filtered information by the area number. in my jQuery code, I have:

$(xml).find('point').each(function(){
  var area = $(this).attr('area');
  if(area == 56){
    var alat=$(this).attr('lat');
    var alng=$(this).attr('lng');
    string += 'lat= ' + alat + ', lng=' + alng;
    }       
  });

I saw some suggestions online and thought I could do it this way:

$(xml).find("point[area='56']").each(function(){
    var alat=$(this).attr('lat');
    var alng=$(this).attr('lng');
    string += 'lat= ' + alat + ', lng=' + alng;      
  });

So how I can streamline my code well so I can use loop through xml files to get each area for different arrangements?

You could use a selector like this:

$(xml).find("[area][area!=]")

which will find all elements in the xml text that have an area attribute that isn't empty

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM