2009-12-09 31 views
1
<channel> 
     <title>Best Web Gallery - Flash + CSS Gallery</title> 
     <link>http://bestwebgallery.com</link> 
     <description>Featuring the world best web design</description> 
     <pubDate>09 Dec 2009</pubDate>  
     <generator>http://wordpress.org/?v=2.3.2</generator> 
     <language>en</language> 
</channel> 


<channel> 
     <title>Best Web Gallery - Flash + CSS Gallery</title> 
     <link>http://bestwebgallery.com</link> 
     <description>Featuring the world best web design</description> 

      // pubDate missing 

     <generator>http://wordpress.org/?v=2.3.2</generator> 
     <language>en</language> 
</channel> 




    XDocument rssFeed = XDocument.Load(url); 

        var feedResources = from details in rssFeed.Descendants("channel") 
            select new feedResource 
            { 
             Title = details.Element("title").Value, 
             Host = details.Element("link").Value, 
             Description = details.Element("description").Value, 

             PublishedOn = DateTime.Parse(details.Element("pubDate").Value), 
             Generator = details.Element("generator").Value, 
             Language = details.Element("language").Value 
            }; 

我們如何在嘗試獲取元素「pubDate」或其他元素之前檢查此處,因爲如果未檢查,則會拋出空引用異常?c#LINQ to XML查詢表達式爲elemennt exhist?

回答

3

不要使用Parse等; xml通常使用不同的字符串表示,而不是它接受的;只投(注意沒有.Value):

select new FeedResource 
{ 
    Title = (string)details.Element("title"), 
    Host = (string)details.Element("link"), 
    Description = (string)details.Element("description"), 
    PublishedOn = (DateTime?)details.Element("pubDate"), 
    Generator = (string)details.Element("generator"), 
    Language = (string)details.Element("language") 
} 

XElement具有轉換操作符來完成所有的工作,返回相應的值。

+0

哦DateTime.Now,這很酷。我不知道。 +1 – Zooba 2009-12-09 20:43:49

+0

感謝隊友,出色的工作 – 2009-12-09 21:48:47

2

我個人的偏好是兩種拓方法添加到的XElement:

public static string ValueOrDefault(this XElement xml) 
{ 
    if (xml == null) return null; // or String.Empty, if you prefer 
    return xml.Value 
} 

public static string ValueOrDefault(this XElement xml, string defaultValue) 
{ 
    if (xml == null) return defaultValue; 
    return xml.Value 
} 

現在你的代碼看起來是這樣的:

select new feedResource 
{ 
    Title = details.Element("title").ValueOrDefault(), 
    Host = details.Element("link").ValueOrDefault(), 
    Description = details.Element("description").ValueOrDefault(), 

    PublishedOn = DateTime.Parse(details.Element("pubDate").ValueOrDefault(DateTime.Now.ToString())), 
    Generator = details.Element("generator").ValueOrDefault(), 
    Language = details.Element("language").ValueOrDefault() 
}; 
-1

只需更改行:

PublishedOn = DateTime.Parse(details.Element("pubDate").Value), 

爲:

PublishedOn = details.Element("pubDate") != null? DateTime.Parse(details.Element("pubDate").Value) : DateTime.Now, 

你可以改變任何你想要的