Search code examples
jqueryxmlweather-api

How to extract/get a xml attribute values to display


I am trying to integrate open weather api in my application and I have invoked weather api and it's returned xml response. But when I am trying to get the values it's throwing error like unknown error.

My code is:

js code:

<script type="application/javascript">

        jQuery(document).ready(function(){
            $.ajax({
                type: "GET",
                url: "http://api.openweathermap.org/data/2.5/forecast/daily?q=Hyderabad,IN&mode=xml&appid=c9d49310f8023ee2617a7634de23c2aa",
                dataType: "xml",
                success: function(data) {
                    /* handle data here */
                    console.log(data);

                    //$('<p>Text</p>').appendTo('#weather_report');

                    /*var wrapper = $("#weather_report");
                     wrapper.empty();
                     wrapper.append("<div class='city'> <p>Place: " + data.city.name + "</p><p>Country: " + data.city.country + "</p></div>");
                     wrapper.append("<div class='day_1'> <p>Place: " + data.city.name + "</p><p>Country: " + data.city.country + "</p></div>");*/

                },
                error: function(xhr, status) {
                    /* handle error here */
                }
            });
        });

    </script>

above code returning below format:

enter image description here

Could you please suggest me how to get the xml values to display?


Solution

  • You could create a hidden div on the page, then use the JQuery.load method to insert the XML elements into the div. Once you've done that, you can traverse and modify it as you would with HTML. See below code:

    $('#hiddenDivId').load('xmlURL');

    This will insert the XML into the hiddenDiv.

    For example, if you have this XML:

    <foos>
      <foo>
        <prop1>Test</prop1>
        <prop2>Test1</prop2>
      </foo>
    </foos>
    

    And you then do $('#hiddenDivId').load('foos.xml');

    The HTML element 'hiddenDivId' would look like this:

    <div id="hiddenDivId">
      <foos>
        <foo>
          <prop1>Test</prop1>
          <prop2>Test1</prop2>
        </foo>
      </foos>
    </div>
    

    After that, you can iterate through the element of 'foo' like this:

    $('#hiddenDivId foos foo').each(function(){
      //you can then do whatever you want with the current 'foo'.
      //to access it from the loop, use the $(this) keyword
      //you can access the properties using $(this).children('property name')
      //and it will treat it like a HTML element
    })