Friday, 25 March 2016

XML : Function to populate drop down menu with xml data? Javascript + XML

I have this assignment I'm trying to finish for class and I'm having some difficulties getting this functionality to work and am hoping to get some insight on how to do this. The HTML page consists of a form with a button that reads "Get XML data". When that button is clicked, the xml file gets read using XML httprequest (this is all local). This xml file consists of weather data for 3 different cities.

  `<stationdata weatherdate="2015-12-30" location="Calgary">  <maxtemp>-2.7</maxtemp>  <mintemp>-18.2</mintemp>  <totalrain>0</totalrain>  <totalsnow>0</totalsnow>  </stationdata>'    

It looks like that for every day of the year for 3 different cities. I'm trying to get my program to read through the cities, and generate the drop down menu with the names of the 3 cities (Calgary, Charlottetown, Ottawa). So far I can only read one city for some reason.

Any help would be appreciated.

This is what I have so far:

     function getDoc() {     var xhttp = new XMLHttpRequest();    xhttp.onreadystatechange = function() {      if (xhttp.readyState == 4 && xhttp.status == 200)      {          alert("XML file obtained");          myFunction(xhttp);      //var   data = xhttp.responseXML;            }      };  xhttp.open("GET", "weatherdata.xml", true);  xhttp.send();    function myFunction(xml)  {  var xmlDoc = xml.responseXML;  var i = 0;  var x = xmlDoc.getElementsByTagName("stationdata")[i];  var txt = x.getAttribute("location");  document.getElementById("generatedDataDiv").innerHTML = txt;      for (i = 0; i < 1; i++)  {      document.getElementById("generatedDataDiv").innerHTML = txt;      //i++;      }      }    }    

I believe I need to loop it somehow but I'm not able to see how. The XML file contains 6000~ lines of this data, I just need to be able to get the locations from the file, then eliminate any duplicates, which should give me 3 names for the cities. I'm only getting one so far.

No comments:

Post a Comment