2009-06-28 43 views
2

我正在編寫一個通用類來讀取來自各種源的RSS提要,併合併到VB.net中的一個對象集合中。當節點不存在時將LINQ轉換爲XML

基本上,使用LINQ to XML的函數工作正常,但當我嘗試讀取的RSS源不包含節點之一(如您所知,其中許多是可選的)時,我遇到問題。我會返回值是一個空字符串或什麼也沒有,但相反,我得到一個運行時錯誤。 我在網上搜索了同樣的問題,我發現這個帖子http://forums.asp.net/p/1351226/2762834.aspx#2762834顯然解釋了一種解決方法,但它不適用於我的代碼。

我也通過我發現這個問題的資源很少感到驚訝,所以我現在想知道如果我甚至把問題在正確的條件...

以下你可以找到的代碼:

Dim PostsEnum = From BlogPost In XMLSource.Descendants("item") 
    Order By DateTime.Parse(BlogPost.Element("pubDate").Value) Descending 
    Select New Post() With { 
     .Title = BlogPost.Element("title").Value, 
     .Link = BlogPost.Element("link").Value, 
     .Description = BlogPost.Element("description").Value, 
     .AuthorText = BlogPost.Element("author").Value, 
     .Category = (From tag In BlogPost.Descendants("category") 
      Select cat = tag.FirstNode.ToString).ToList, 
     .PubDate = DateTime.Parse(BlogPost.Element("pubDate").Value), 
     .GUID = BlogPost.Element("guid").Value 
    } 

我想這對http://neatlydoc.codeplex.com/Project/ProjectRss.aspx和它的工作,但下面的代碼會產生異常:

Dim PostsEnum = From BlogPost In XMLSource.Descendants("item") 
    Order By DateTime.Parse(BlogPost.Element("pubDate").Value) Descending 
    Select New Post() With { 
     .Title = BlogPost.Element("title").Value, 
     .Link = BlogPost.Element("link").Value, 
     .Description = BlogPost.Element("description").Value, 
     .AuthorText = BlogPost.Element("author").Value, 
     .Category = (From tag In BlogPost.Descendants("category") 
      Select cat = tag.FirstNode.ToString).ToList, 
     .PubDate = DateTime.Parse(BlogPost.Element("pubDate").Value), 
     .GUID = BlogPost.Element("guid").Value, 
     .Source = CType(BlogPost.Element("source").Value, String) 
    } 

任何幫助將是APPR eciated。

感謝

盧卡

+0

查看更新...找到並修復... – 2009-06-28 11:38:19

+0

非常感謝。 – lucamauri 2009-06-28 16:04:40

回答

3

如果試圖評估。價值(等等) - 然後是的,這將打破 - 但是,你可以嘗試鑄造(apols,但我的例子是C# - 你會可以想像VB):

select new { 
     Name = (string)el.Element("abc") 
     ... 
    } 

顯式靜態轉換操作符接受空節點,並適當地返回空值。對於更復雜的情況,只是測試它:

 let child = el.Element("SomeChild") 
     select new { 
     Name = child == null ? (string)null : (string)child.Attribute("Name") 
     ... 
     } 

難是沒有先例的XML /代碼更具體的...


重新編輯您的更新;問題在於你還在讀.Value;它更改爲:

.Source = CType(BlogPost.Element("source"), String) 

有從XElementstring轉換算子;你不需要看.Value