How to read WordPress feeds in a C# MVC .Net application

This is a very easy method you could use to read XML data from a feed and instantiate the object you need with that information. For the following example, I am using an MVC .Net Application code.

First you need to create the Model to store the posts information.

 public partial class BlogPost
 {
    public string Name { get; set; }
    public string URL { get; set; }
    public string Description { get; set; }
    public System.DateTime Date { get; set; }
 }

The following step is used to read the XML data, I have created a helper class with a static method.

public class BlogPostsLookUp
 {
    public static IEnumerable<BlogPost> GetBlogPosts()
    {
      XDocument feedXML = XDocument.Load("http://clarifycoder.com/feed/");

      var feeds = from feed in feedXML.Descendants("item")
            select new BlogPost
            {
              Name = feed.Element("title").Value,
              URL = feed.Element("link").Value,
              Date = DateTime.Parse(feed.Element("pubDate").Value),
              Description = feed.Element("description").Value,
             };

       return feeds;
    }
 }

Once you have the list of blog post you can use it in the View for displaying the information

<ol class="blog-home">
    @foreach (var blog in BlogPostsLookUp.GetBlogPosts())
     {
       <li>
           <a href="@blog.URL" target="_blank">@blog.Name <br /></a>
           <span style="color: #b8c4c4">
               posted on 
               <span style="color:#808080;font-style:italic">
                  @blog.Date.ToString("MMMM dd, yyyy")
               </span>
           </span>
      </li>
    }

</ol>
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s