使用jquery从xml中选择一个属性

Select an attribute from xml using jquery

本文关键字:一个 属性 选择 jquery xml 使用      更新时间:2023-09-26

正如标题所示,我正试图从在线检索的xml中的一个属性返回一个特定值(第一次预测的分钟数)。

这是xml:

<?xml version="1.0" encoding="utf-8" ?> 
<body copyright="All data copyright Societe de transport de Laval 2016.">
<predictions agencyTitle="Societe de transport de Laval" routeTitle="33Direction M&#233;tro Montmorency" routeTag="33N" stopTitle="De Villars / De Mexico [43246]" stopTag="CP43246">
 <direction title="Nord">
  <prediction epochTime="1459297620000" seconds="575" minutes="9" isDeparture="true" affectedByLayover="true" dirTag="33N_1_var0" vehicle="0307" block="L269" tripTag="33N2L26920420047" />
  <prediction epochTime="1459301100000" seconds="4055" minutes="67" isDeparture="true" affectedByLayover="true" dirTag="33N_1_var0" vehicle="virtualVehicle_L268" block="L268" tripTag="33N2L26821400049" />
  </direction>
  </predictions>
</body>

下面是我基于另一个响应检索它的代码:使用JQuery/Javascript从简单XML获取属性值。

            $(document).ready(function(){ 
            var url = "http://webservices.nextbus.com/service/publicXMLFeed?command=predictions&a=stl&stopId=43246";
        //ajax way of getting data
                $.ajax({
                    type: "GET",
                    url: url,
                    dataType: "xml",
                    success: function(xml) {
                        var string = xml;
                        //console.log(string);
                        var $doc = $.parseXML(string);
                         console.log($($doc).find('prediction').attr('minutes'));
                    }
                });
            });
        </script>

作为对上一个console.log的响应,我当前未定义,我想我需要选择一个特定的<prediction minute=">,但我不确定怎么做

您的AJAX调用返回的是XML,而不是字符串。您不需要解析字符串,而是需要像$(xml)一样将xml对象包装在jQuery对象中。

然后,要获得第一次预测的分钟数,需要指定哪个预测。请参见.eq()$xml.find('prediction').eq(0).attr("minutes");

$(document).ready(function() {
  var url = "http://webservices.nextbus.com/service/publicXMLFeed?command=predictions&a=stl&stopId=43246";
  //ajax way of getting data
  $.ajax({
    type: "GET",
    url: url,
    dataType: "xml",
    success: function(xml) {
      $xml = $(xml); // wrap xml in jQuery object
      console.log($xml.find('prediction').eq(0).attr("minutes")); // specify the 1st prediction
    }
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>