使用 LINQ 查询 XML,如果不存在数据则返回空字符串
我想做的是编写一个通用的 rss 阅读器,我可以将任何 URL 插入其中,而不必担心提要是否具有所有常见属性。例如,在下面的示例中,我正在查找 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
What I'm trying to do is to write a generic rss reader that I plug in any URL into without worry if the feed has all the common properties. For instance in my example below I'm looking for pubDate, however if no pubDate exists in the xml I'd like to return the current Date. I cannot seem to get the syntax right though. Any suggestions?
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
试试这个
Try this
而不是
feed.Element("pubDate").Value Is Nothing
写成feed.Element("pubDate") Is Nothing
!instead of
feed.Element("pubDate").Value Is Nothing
writefeed.Element("pubDate") Is Nothing
!