如何正确排序从XML文件返回的数据?

时间:2019-02-18 13:28:50

标签: javascript ajax sorting

我想在此Ajax调用后的DATE之前按升序排序

function parseXML(xml){

    var weatherArray = [];
    var weatherElement = xml.getElementsByTagName("forecast")[0];
    weatherArray.queryTime = weatherElement.getAttribute("queryTime");
    weatherArray.queryLocation = weatherElement.getAttribute("queryLocation");
    weatherArray.weatherList = [];


    function s(a,b){
        return parseInt(a.getElementsByTagName("date")[0].childNodes[0].nodeValue) - parseInt(b.getElementsByTagName("date")[0].childNodes[0].nodeValue);
        }
        var weatherElements = weatherElement.getElementsByTagName("weather");
        weatherElements=weatherElements.sort(s);

    for(var i=0; i< weatherElements.length; i++){
        var weather = {};
        weather.year = Number(weatherElements[i].getElementsByTagName("year")[0].childNodes[0].nodeValue);
        weather.month = Number(weatherElements[i].getElementsByTagName("month")[0].childNodes[0].nodeValue);
        weather.date = Number(weatherElements[i].getElementsByTagName("date")[0].childNodes[0].nodeValue);
        weather.dayOfWeek = weatherElements[i].getElementsByTagName("dayOfWeek")[0].childNodes[0].nodeValue;
        weather.overall = weatherElements[i].getElementsByTagName("overall")[0].childNodes[0].nodeValue;
        weather.overallCode = weatherElements[i].getElementsByTagName("overallCode")[0].childNodes[0].nodeValue;
        weather.highest = Number(weatherElements[i].getElementsByTagName("highest")[0].childNodes[0].nodeValue);
        weather.lowest = Number(weatherElements[i].getElementsByTagName("lowest")[0].childNodes[0].nodeValue);
        weatherArray.weatherList.push(weather);
    }
    return weatherArray;
}

因此,当数据出现在浏览器中时,它从显示DATE 26开始的数据行开始,然后是27秒和28 ..... xml中有更多重复数据,我在这里没有包含所有数据。

我在做什么错?

1 个答案:

答案 0 :(得分:0)

这是一个可行的解决方案:

var weatherElements = [];
var weatherElementsArr = weatherElement.getElementsByTagName("weather");

for (var i in weatherElementsArr) {
    if (weatherElementsArr[i].nodeType == 1) {
        weatherElements.push(weatherElementsArr[i]);
    }
}

weatherElements.sort(s);

问题出在这里

var weatherElements = weatherElement.getElementsByTagName("weather");
    weatherElements=weatherElements.sort(s);

weatherElements的值是一个HTMLCollection,您不能对其进行排序,因为它不是本机javascript数组。它是HTML元素的集合。

通过创建带有节点元素的数组,您现在可以按最初的期望对它们进行排序。