Select an attribute from xml using jquery

as the title suggests I'm trying to return a specific value (the minutes for the first prediction) from an attribute in an xml retrieved from online.

Here is the 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>

And here is my code to retrieve it, based on another response: Get Attribute Value From Simple XML Using JQuery / Javascript.

            $(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>

I'm currently getting undefined as a response to my last console.log, I think i need to select a specific < prediction minute ="" >, but I'm not sure how?

Answers 1

  • Your AJAX call is returning XML, not a string. Instead of parsing a string, you need to wrap the xml object inside a jQuery object like so $(xml).

    Then, to get the minutes of the first prediction, you need to specify which prediction. See .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>


Related Articles