简体   繁体   English

用javascript解析xml到html

[英]parse xml with javascript for html

I am trying to get some information from the Yahoo Console for weather conditions. 我正在尝试从Yahoo Console获取有关天气情况的一些信息。 The xml result tree from Yahoo looks like this: result tree Yahoo的xml结果树如下所示: 结果树

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. 我的变量“ beta”用于标题,效果很好。 The second variable is 'alpha' which will not work. 第二个变量是'alpha',它将不起作用。 I believe it has to do with how I call for it 'item.condition.temp' and with the node values. 我相信这与我如何称呼它为“ item.condition.temp”以及节点值有关。

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: 我建议将&format = json添加到您的URL中以使其达到此目的:

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. 然后解析生成的JSON,这是一种更JavaScript的方式。

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

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