0

I am working on a project where I'm able to use just jQuery, Javascript and HTML CSS. So, XML response that I copied is below, and I want to sort this XML response on the basis of number of stars given to every location, with the highest number of stars on the top.

<Locations>
  <Location>
    <Id>790</Id>
    <Name>DHA Office</Name>
    <Latitude>31.4737</Latitude>
    <Longitude>74.3771</Longitude>
    <Distance>0.74</Distance>
    <Address>Sector Y</Address>
    <City>Lahore </City>
    <Subcategory>Convenience Store</Subcategory>
    <Appid>1</Appid>
    <Stars></Stars>
    <Options>2,,,,,,,,,,</Options>
  </Location>
  <Location>
    <Id>729</Id>
    <Name>McDonald's</Name>
    <Latitude>31.4749</Latitude>
    <Longitude>74.3772</Longitude>
    <Distance>0.67</Distance>
    <Address>486/ B</Address>
    <City>Lahore </City>
    <Subcategory>Convenience Store</Subcategory>
    <Appid>1</Appid>
    <Stars>5</Stars>
    <Options>3,,,,,,,,,,</Options>
  </Location>
  <Location>
    <Id>732</Id>
    <Name>Lahore Zoo</Name>
    <Latitude>31.5563</Latitude>
    <Longitude>74.3261</Longitude>
    <Distance>4.79</Distance>
    <Address>92 Mall Road</Address>
    <City>Lahore </City>
    <Subcategory>Convenience Store</Subcategory>
    <Appid>1</Appid>
    <Stars>3</Stars>
    <Options>6,7,,,,,,,,,</Options>
  </Location>
</Locations>
4

3 回答 3

1

不确定这是否是您想要的,您可以将此 XML 转换为对象数组,然后根据您所需的条件对该数组进行排序。然后,您可以显示来自这个排序的对象数组的信息。通常您不需要已排序的 XML,而只需对信息进行排序。

看看这篇关于如何转换XMLassociative array.

然后,您可以将 JavaScript 排序函数与您定义的比较函数一起应用。

于 2013-07-12T21:16:58.567 回答
0

一个插件来解析 xml 怎么样:https ://code.google.com/p/jquery-xml2json-plugin/

然后...

var locations = $.xml2json(response);
console.log(locations)
locations.Location.sort(function(a,b){
    return parseInt(a.Stars || "0") > parseInt(b.Stars || "0");
});

$.each(locations.Location,function(k,v){console.log(v.Stars);});

输出到控制台:3 5

http://jsfiddle.net/5Cbvc/

于 2013-07-12T21:49:21.460 回答
0

您可以在 jQuery 中使用普通的 XML。

var l = $(yourXmlString).find('Location');
l.sort(function(a, b) {
  return (
    parseInt($(b).children('Stars').first().text()) - 
    parseInt($(a).children('Stars').first().text()));
});
于 2013-07-12T21:51:10.567 回答