Yahoo Weather Rss Reading with ASP.NET MVC?



我想在此处解析yahoo yahoo天气rss feed xml:http://developer.yahoo.com/weather/

我的RSS项目

public class YahooWeatherRssItem
{
    public string Title { get; set; }
    public string Link { get; set; }
    public string Description { get; set; }
    public string City { get; set; }
    public string Country { get; set; }
    // temp, wind, etc...
}

我的RSS Manager

public static IEnumerable<YahooWeatherRssItem> GetYahooWeatherRssItems(string rssUrl)
{
    XDocument rssXml = XDocument.Load(rssUrl);
    var feeds = from feed in rssXml.Descendants("item")
                select new YahooWeatherRssItem
                {
                    I can get following values
                    Title = feed.Element("title").Value,
                    Link = feed.Element("link").Value,
                    Description = feed.Element("description").Value,
                    // I dont know, How can I parse these.
                    Text = ?
                    Temp = ?
                    Code = ?
                };
        return feeds;
    }

我不知道,如何按照XML线进行解析:

<yweather:condition  text="Mostly Cloudy"  code="28"  temp="50"  date="Fri, 18 Dec 2009 9:38 am PST" />
<yweather:location city="Sunnyvale" region="CA"   country="United States"/>
<yweather:units temperature="F" distance="mi" pressure="in" speed="mph"/>
<yweather:wind chill="50"   direction="0"   speed="0" />
<yweather:atmosphere humidity="94"  visibility="3"  pressure="30.27"  rising="1" />
<yweather:astronomy sunrise="7:17 am"   sunset="4:52 pm"/>

问题是yweather:<string>。可能有关于XML解析的文章,例如这种结构。或代码示例?

谢谢。

以下表达式应起作用,首先引用ycweather名称空间;

XNamespace yWeatherNS = "http://xml.weather.yahoo.com/ns/rss/1.0";

然后您以这种方式获得属性值:

Text = feed.Element(yWeatherNS + "condition").Attribute("text").Value

问题是您的条件元素在另一个命名空间中,因此您必须在该名称空间的上下文中选择此节点。

您可以通过C#

中的MSDN文章名称空间阅读有关XML名称空间的更多信息。

使用名称空间并使用Attribute

获取数据
XNamespace ns = "http://xml.weather.yahoo.com/ns/rss/1.0";
var feeds = from feed in rssXml.Descendants("item")
            select new YahooWeatherRssItem
            {
                Title = feed.Element("title").Value,
                Link = feed.Element("link").Value,
                Description = feed.Element("description").Value,
                Code=feed.Element(ns+"condition").Attribute("code").Value       
                //like above line, you can get other items 
            };

这将起作用。测试:)

您需要读取这些值的XML属性。基于此处的问题(使用Xdocument通过属性找到元素),您可以尝试这样的事情:

Temp = feed.Attribute("temp");

最新更新