Error Reading RSS Feed using LINQ to XML

2019-03-04 18:39发布

问题:

In referencing this article I am receiving a NullReferenceException stating Object reference is not set to an instance of an object. I'm not sure how to fix this solution as I've followed the steps in my reference article.

Models

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;

    }
}

ViewModel

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

Controller

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

Index

<div class="row">
<div class="col-md-8">
<h4>Feed</h4>

    @foreach (var item in Model.RssFeed)
    {
        @item.Title <br />
        @item.Description <br/>

    }

</div>

回答1:

You have two layers of tags. First the channel and then the items. See code below.

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();

        }

    }
}