本文介绍了错误读取使用LINQ to XML RSS订阅的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在引用我收到一个<$ C此文章$ C>的NullReferenceException 说明对象引用未设置到对象的实例。
我不知道如何为我解决这个问题的解决方案已经跟随我的文章引用的步骤。
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.
模式
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>
推荐答案
您有标签两层。第一信道,然后将物品。请参见下面code。
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();
}
}
}
这篇关于错误读取使用LINQ to XML RSS订阅的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!