如何使用jQuery基于日期值对XML进行排序

时间:2015-03-16 06:54:14

标签: jquery sorting

我有一个XML结构和一个日期值。我需要从xml下面排序并获取最新的节点。我正在寻找基于StartDate值的xml下降排序。

<PriceList>
      <PriceInfo>
        <Timestamp>2015-02-19T06:33:10.255</Timestamp>
        <Value xsi:nil=\"true\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" >3</Value>
        <Unit>eur/kwh</Unit>
        <StartDate>2015-02-16T00:00:00</StartDate>
        <EndDate>2015-02-16T00:00:00</EndDate>
        <BaseAmount xsi:nil=\"true\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" />
        <BaseAmountUnit />
      </PriceInfo>
      <PriceInfo>
        <Timestamp>2015-02-11T06:43:10.255</Timestamp>
        <Value xsi:nil=\"true\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" />
        <Unit>eur/kwh</Unit>
        <StartDate>2015-02-11T00:00:00</StartDate>
        <EndDate>2015-02-16T00:00:00</EndDate>
        <BaseAmount xsi:nil=\"true\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" >4</BaseAmount>
        <BaseAmountUnit />
      </PriceInfo>
      <PriceInfo>
        <Timestamp>2015-02-10T06:33:10.255</Timestamp>
        <Value xsi:nil=\"true\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" >5</Value>
        <Unit>eur/kwh</Unit>
        <StartDate>2015-02-10T00:00:00</StartDate>
        <EndDate>2015-02-16T00:00:00</EndDate>
        <BaseAmount xsi:nil=\"true\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" />
        <BaseAmountUnit />
      </PriceInfo>
    </PriceList>

我写得像这样,

 var result = $(priceList).find("PriceInfo").sort(function (a, b) {
                    debugger;
                    var textA = $(a).find('StartDate').text();
                    var textB = $(b).find('StartDate').text();

                    if (textA < textB)
                        return 1;
                    if (textA > textB)
                        return -1;
                    return 0;
                });

2 个答案:

答案 0 :(得分:0)

$.get('Pricelist.xml', function(PriceList){     
  var priceInfo= $(PriceList).find('PriceInfo');

 priceInfo.sort(function(a, b){
     return $(a).data('StartDate').localeCompare( $(b).data('StartDate') );
  });

  priceInfo.each(function(i,v){
    alert($(v).attr('StartDate'));
  });
}); 

答案 1 :(得分:0)

以下是在上面的上下文中应用的Daniel Lidström回答,其中布尔< >比较用于Date对象。

var result = $xml.find("PriceInfo").sort(function (a, b) {
    //debugger;
    var textA = $(a).find('StartDate').text();
    var dateA = new Date(textA);

    var textB = $(b).find('StartDate').text();
    var dateB = new Date(textB);

    if (dateA < dateB) return +1;
    if (dateA > dateB) return -1;

    return 0;
});

Fiddle