1

ここで yahoo weather 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マネージャー

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 解析に関する記事があるかもしれません。またはコード例?

ありがとう。

4

3 に答える 3

2

次の式が機能するはずです。最初にycweather名前空間を参照します。

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

次に、次の方法で属性値を取得します。

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

問題は、条件要素が別の名前空間にあるため、 XNamespaceを介してその名前空間のコンテキストでこのノードを選択する必要があることです。

XML 名前空間の詳細については、MSDN の記事Namespaces in C# を参照してください。

于 2012-10-18T14:03:51.793 に答える
1

名前空間を使用し、次を使用してデータを取得します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 
            };

これは機能します。テスト済み:)

于 2012-10-18T14:06:05.163 に答える
0

これらの値の XML 属性を読み取る必要があります。ここでの質問に基づいて ( Find Elements by Attribute using XDocument )、次のようなことを試すことができます。

Temp = feed.Attribute("temp");
于 2012-10-18T13:41:14.453 に答える