ahsan-ali
ahsan-ali

Reputation: 133

how to sort an xml returned from webservice

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>

Upvotes: 0

Views: 409

Answers (3)

Shamim Hafiz - MSFT
Shamim Hafiz - MSFT

Reputation: 22094

Not sure if this is what you want, you could convert this XML to an array of object and then sort that array based on your desired criteria. You could then show the information from this sorted array of objects. Normally you wouldn't need the sorted XML, but only have the information sorted.

Take a look at this post on how you can convert XML to associative array.

You could then apply the JavaScript sort function with your defined compare function.

Upvotes: 1

OzrenTkalcecKrznaric
OzrenTkalcecKrznaric

Reputation: 5646

You can work with ordinary XML in jQuery.

var l = $(yourXmlString).find('Location');
l.sort(function(a, b) {
  return (
    parseInt($(b).children('Stars').first().text()) - 
    parseInt($(a).children('Stars').first().text()));
});

Upvotes: 0

bluetoft
bluetoft

Reputation: 5443

how about a plugin to parse the xml: https://code.google.com/p/jquery-xml2json-plugin/

Then...

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);});

outputs to the console: 3 5

http://jsfiddle.net/5Cbvc/

Upvotes: 0

Related Questions