I have what I think should be a straightforward question; let me quickly explain:
In my JavaScript, food.xml
is read in with:
getMenuXml.ope
It's a good idea to use a Javascript library to get ready-made functions w.r.t Node List operations such as re-ordering, sorting, foreach etc. I would recommend YUI-3, please refer YUI-3 NodeList .
You can order the elements of the NodeList, if you convert them to an array first:
var foods = xmlDoc.getElementsByTagName("food");
var foodsArray = Array.prototype.slice.call(foods, 0);
Then you can use the sort
method:
foodsArray.sort(function(a,b) {
var aCat = a.getElementsByTagName("category")[0].childNodes[0].nodeValue;
var bCat = b.getElementsByTagName("category")[0].childNodes[0].nodeValue;
if (aCat > bCat) return 1;
if (aCat < bCat) return -1;
return 0;
});
This is highly dependent on your XML schema though - if, for example, you had foods which were in more than one category they would only be sorted by the first category in the code above.
Take a look at this: Xml, xsl Javascript sorting. Worst case scenario, you transform the data into precisely the same xml, but sorted. As long as you're paying the transformation penalty, you might consider transforming it into a form more useful for whatever the next step is.