使用js读取Xml

时间:2011-02-17 13:57:52

标签: javascript xml

我正在阅读yahoo weather xml文件

    <rss version="2.0" xmlns:yweather="http://xml.weather.yahoo.com/ns/rss/1.0" xmlns:geo="http://www.w3.org/2003/01/geo/wgs84_pos#">
            <channel>

<title>Yahoo! Weather - Sunnyvale, CA</title>
<link>http://us.rd.yahoo.com/dailynews/rss/weather/Sunnyvale__CA/*http://weather.yahoo.com/forecast/USCA1116_f.html</link>
<description>Yahoo! Weather for Sunnyvale, CA</description>
<language>en-us</language>
<lastBuildDate>Thu, 17 Feb 2011 3:55 am PST</lastBuildDate>
<ttl>60</ttl>

<yweather:location city="Sunnyvale" region="CA"   country="United States"/>
<yweather:units temperature="F" distance="mi" pressure="in" speed="mph"/>
<yweather:wind chill="41"   direction="150"   speed="7" />
<yweather:atmosphere humidity="86"  visibility="10"  pressure="29.96"  rising="2" />
<yweather:astronomy sunrise="6:54 am"   sunset="5:49 pm"/>
<image>
<title>Yahoo! Weather</title>
<width>142</width>
<height>18</height>
<link>http://weather.yahoo.com</link>
<url>http://l.yimg.com/a/i/brand/purplelogo//uh/us/news-wea.gif</url>
</image>

<item>
<title>Conditions for Sunnyvale, CA at 3:55 am PST</title>
<geo:lat>37.37</geo:lat>
<geo:long>-122.04</geo:long>
<link>http://us.rd.yahoo.com/dailynews/rss/weather/Sunnyvale__CA/*http://weather.yahoo.com/forecast/USCA1116_f.html</link>
<pubDate>Thu, 17 Feb 2011 3:55 am PST</pubDate>
<yweather:condition  text="Cloudy"  code="26"  temp="45"  date="Thu, 17 Feb 2011 3:55 am PST" />
<description><![CDATA[
<img src="http://l.yimg.com/a/i/us/we/52/26.gif"/><br />
<b>Current Conditions:</b><br />
Cloudy, 45 F<BR />
<BR /><b>Forecast:</b><BR />
Thu - Rain. High: 54 Low: 44<br />
Fri - Rain. High: 53 Low: 39<br />
<br />
<a href="http://us.rd.yahoo.com/dailynews/rss/weather/Sunnyvale__CA/*http://weather.yahoo.com/forecast/USCA1116_f.html">Full Forecast at Yahoo! Weather</a><BR/><BR/>
(provided by <a href="http://www.weather.com" >The Weather Channel</a>)<br/>
]]></description>
<yweather:forecast day="Thu" date="17 Feb 2011" low="44" high="54" text="Rain" code="12" />
<yweather:forecast day="Fri" date="18 Feb 2011" low="39" high="53" text="Rain" code="12" />
<guid isPermaLink="false">USCA1116_2011_02_17_3_55_PST</guid>

</item>
</channel>
</rss>

使用以下js代码

var channel = xml.documentElement.getElementsByTagName("channel");
var c = channel.item(0).getElementsByTagName("ttl").item(0).text;

我得到var值的60值。如何从yweather:atmosphere标记

获取“humidity =”86“属性

1 个答案:

答案 0 :(得分:0)

这应该适合你:

var atmoNode = document.getElementByTagname("yweather:atmosphere").item(0);
var humidity_string = atmoNode.attributes.humidity.value;

您想通过attributes属性访问湿度。