使用LINQ查询XML并在没有数据时返回空字符串

时间:2011-03-08 15:56:25

标签: asp.net xml vb.net linq rss

我要做的是编写一个通用的rss阅读器,我插入任何URL,如果Feed具有所有通用属性,则无需担心。例如,在下面的示例中,我正在寻找 pubDate ,但如果xml中不存在 pubDate ,我想返回当前日期。我似乎无法正确地获得语法。有什么建议吗?

Dim xmldoc As New XDocument
xmldoc = XDocument.Load(url)

Dim feeds = From feed In xmldoc.Descendants("item") Select New With { _
    Key .Title = feed.Element("title").Value, _
    Key .Link = feed.Element("link").Value, _
    Key .Description = feed.Element("description").Value, _
    Key .PubDate = If(feed.Element("pubDate").Value Is Nothing, Date.Now.ToString, feed.Element("pubDate").Value)}

For Each item In feeds
    Response.Write("<a href=""" & item.Link & """ target=""_blank"">" & item.Title & "</a> - " & item.PubDate & "<br />")
    Response.Write(item.Description & "<hr />")
Next

2 个答案:

答案 0 :(得分:1)

试试这个

 Key .PubDate = IIf(feed.Element("pubDate") Is Nothing, Date.Now.ToString, feed.Element("pubDate").Value)

答案 1 :(得分:0)

而不是feed.Element("pubDate").Value Is Nothingfeed.Element("pubDate") Is Nothing