You are better off using Linq to XML. First, create a class as a container for each feed item:
using System;
public class RssItem
{
public string Title {get;set;}
public string Description {get;set;}
public string Link {get;set;}
public DateTime PubDate {get;set;}
}
Then you can load the feed into an XDocument object and query it:
@using System.Xml.Linq;
@{
var rss = new List<RssItem>();
var feed = XDocument.Load("http://localhost:34321/GenerateXml.cshtml");
var items = feed.Descendants("item");
foreach(var item in items){
rss.Add(new RssItem{
Title = (string)item.Element("title"),
Description = (string)item.Element("description"),
Link = (string)item.Element("link"),
PubDate = (DateTime)item.Element("pubDate")
});
}
var mostRecent = rss.OrderByDescending(r => r.PubDate).Take(5);
}
I have used Argotic Syndication Framework to achieve this in one of my projects. It was very easy to setup, first install it by searching nuget for 'argotic' and installing the core package which also installs the
dependencies. Then all you need are a few lines to do what you want. This is what I achieved in my case:
@using Argotic.Syndication;
@{
RssFeed feed = RssFeed.Create(new Uri("URL TO RSS HERE"));
}
<ul class="newsSide">
@foreach(var item in feed.Channel.Items)
{
String title = item.Title; //RSS item Title
String desc = item.Description; //RSS item Description
var link = item.Link; //RSS item Link
<text><li><a href="@link" title="@title">@title</a> <p class="desc">@desc</p></li></text>
}
</ul>
Member
414 Points
518 Posts
read XML file (RSS), but only 5 recent posts
Aug 10, 2013 03:18 PM|CriticalError|LINK
I got an RSS file with a usual strucutre like this;
<item>
<title></title>
<description></description>
<link></link>
<pubDate></pubDate>
</item>
I want to get the values of title, des, link and I want the posts organised the by published date. I got this code, but does not work as expected.
There must be a better way where I can use foreachs statement to get the node innertext..?
All-Star
194009 Points
28028 Posts
Moderator
Re: read XML file (RSS), but only 5 recent posts
Aug 10, 2013 05:47 PM|Mikesdotnetting|LINK
You are better off using Linq to XML. First, create a class as a container for each feed item:
Then you can load the feed into an XDocument object and query it:
Member
445 Points
176 Posts
Re: read XML file (RSS), but only 5 recent posts
Aug 11, 2013 07:43 AM|mhcodner|LINK
I have used Argotic Syndication Framework to achieve this in one of my projects. It was very easy to setup, first install it by searching nuget for 'argotic' and installing the core package which also installs the dependencies. Then all you need are a few lines to do what you want. This is what I achieved in my case:
It is automatically organised by date