繁体   English   中英

用javascript解析xml到html

[英]parse xml with javascript for html

我正在尝试从Yahoo Console获取有关天气情况的一些信息。 Yahoo的xml结果树如下所示: 结果树

我所拥有的代码能够使我的工作深入到一个层次。 我的变量“ beta”用于标题,效果很好。 第二个变量是'alpha',它将不起作用。 我相信这与我如何称呼它为“ item.condition.temp”以及节点值有关。

我对此很陌生,因此请列出您使用的任何来源,因为这将有助于我的前进。

<!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>

我建议将&format = json添加到您的URL中以使其达到此目的:

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

然后解析生成的JSON,这是一种更JavaScript的方式。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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