简体   繁体   中英

parse xml with javascript for html

I am trying to get some information from the Yahoo Console for weather conditions. The xml result tree from Yahoo looks like this: result tree

I am able to get things that are only one level deep with the code I have. My variable 'beta' is for the title which works beautifully. The second variable is 'alpha' which will not work. I believe it has to do with how I call for it 'item.condition.temp' and with the node values.

I am very new to this so please list any sources you use as it will help me going forward.

<!DOCTYPE html>
<html>
<head>
<p id="alpha"></p>
<p id="beta"></p>

<script>
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function () {
    if (xhttp.readyState == 4 && xhttp.status == 200) {
        myFunction(xhttp);
    }
};
xhttp.open('GET', 'https://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20weather.forecast%20where%20woeid%3D2444827&diagnostics=true', true);
xhttp.send();

function myFunction(xml) {
    var xmlDoc = xml.responseXML;
    document.getElementById('beta').innerHTML = 
    xmlDoc.getElementsByTagName('title')[0].childNodes[0].nodeValue;
    document.getElementById('alpha').innerHTML = 
    xmlDoc.getElementsByTagName('item.condition.temp')[0].childNodes[0].nodeValue;
}
</script>

I would suggest adding &format=json to your URL to make it this:

https://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20weather.forecast%20where%20woeid%3D2444827&diagnostics=true&format=json

Then parse the resulting JSON which is a more JavaScript way of doing it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM