使用LINQ到XML读取RSS提要错误

本文关键字:错误 RSS 读取 LINQ XML 使用 | 更新日期: 2023-09-27 18:12:41

在引用本文时,我收到一个NullReferenceException,说明Object reference is not set to an instance of an object.,我不确定如何修复此解决方案,因为我遵循了参考文章中的步骤。

模型
public class RssModel
{
    public string Title { get; set; }
    public string Link { get; set; }
    public string Description { get; set; }
    public string Image { get; set; }
}
public class ReadRssModel
{
    public static List<RssModel> GetRss()
    {
        var client = new WebClient();
        var xmlData = client.DownloadString("http://finance.yahoo.com/rss/headline?s=msft,goog,aapl");
        XDocument xml = XDocument.Parse(xmlData);
        var rssData = (from item in xml.Descendants("item")
                       select new RssModel
                       {
                           Title = ((string)item.Element("title")),
                           Link = ((string)item.Element("link")),
                           Description = ((string)item.Element("description")),
                           Image = ((string)item.Element("enclosure").Attribute("url"))
                       }).Take(20).ToList();
        return rssData;
    }
}

视图模型

public class RssViewModel
{
    public List<RssModel> RssFeed { get; set; }
}
控制器

 public class HomeController : Controller
{
    public ActionResult Index()
    {
        //return View();
        RssViewModel model = new RssViewModel();
        model.RssFeed = ReadRssModel.GetRss();
        return View(model);
    }
}
指数

<div class="row">
<div class="col-md-8">
<h4>Feed</h4>
    @foreach (var item in Model.RssFeed)
    {
        @item.Title <br />
        @item.Description <br/>
    }
</div>

使用LINQ到XML读取RSS提要错误

你有两层标签。首先是渠道,然后是项目。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;
namespace ConsoleApplication47
{
    class Program
    {
        static void Main(string[] args)
        {
            XDocument xml = XDocument.Load("http://finance.yahoo.com/rss/headline?s=msft,goog,aapl");
            var results = xml.Descendants("channel").Select(x => new
            {
                Title = ((string)x.Element("title")),
                Link = ((string)x.Element("link")),
                Description = ((string)x.Element("description")),
                Image = ((string)x.Element("image").Element("url")),
                items = x.Elements("item").Take(20).Select(y => new {
                    title = (string)y.Element("title"),
                    link = (string)y.Element("link"),
                    description = (string)y.Element("description")
                }).ToList(),
            }).FirstOrDefault();
        }
    }
}