Click here to Skip to main content
Click here to Skip to main content

Simple RSS Reader in C#

By , 7 Aug 2007
 
Screenshot - Sample_Page.jpg

Introduction

This is a simple way of reading an RSS from a feed using C# and XSL.

Using the Code

There are two major parts in this solution. One is the Page that requests and renders the feed and another one will be the XSL which transforms the XML feed.

The first is the default.aspx.cs. We need to import the following references first:

using System.Xml;
using System.IO;
using System.Net;

Then let's go to the fun part:

// Declare your Variables
string xmlsrc = "http://rss.news.yahoo.com/rss/topstories";
string Password = "xxxxxx";
string UserAccount = "xxxxxx";
string DomainName = "xxxxxx";
string ProxyServer = "192.168.1.1:8080";
string xslsrc = "RSS91.xsl";

if (xmlsrc != "")
{
    // Make Remote Request
    HttpWebRequest wr = (HttpWebRequest)WebRequest.Create(xmlsrc);

    if (UserAccount != "")
    {
        wr.Credentials = new NetworkCredential(UserAccount, Password, DomainName);
    }

    // Set Proxy Server
    if (ProxyServer != "")
    {
        wr.Proxy = new WebProxy(ProxyServer, true, new string[] { }, wr.Credentials);
    }

    // Set the HTTP properties
    wr.Timeout = 10000;
    // 10 seconds

    // Read the Response
    WebResponse resp = wr.GetResponse();
    Stream stream = resp.GetResponseStream();

    // Load XML Document
    XmlTextReader reader = new XmlTextReader(stream);
    reader.XmlResolver = null;
    XmlDocument doc = new XmlDocument();

    doc.Load(reader);
    xmlRSS.Document = doc;
    }
xmlRSS.TransformSource = xslsrc;
}

Then the XSL which formats the feed visually. This is how the page will look like the default.aspx just renders it:

<?xml version="1.0"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:output method="html" indent="yes"/>
    <xsl:param name="TITLE"/>

    <xsl:template match="rss">
        <!-- Do not show channel image -->
        <xsl:for-each select="channel/item">
            <br>

                <strong>
                    <a href="{link}" target="_main">
                        <xsl:value-of select="title"/>
                    </a>
                </strong>
                <br></br>

                <!-- only display markup for description if it's present -->
                <xsl:value-of select="description" disable-output-escaping="yes"/>

            </br>
            <br></br>
        </xsl:for-each>
    </xsl:template>

    <xsl:template match="description">
        <br>
            <xsl:value-of select="."/>
        </br>
    </xsl:template>
</xsl:stylesheet> 

History

  • 7th August, 2007: Initial post

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

About the Author

Raymund Macaalay
Technical Lead
New Zealand New Zealand
Member
http://nz.linkedin.com/in/macaalay
http://anyrest.wordpress.com/

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board.
Search this forum  
    Spacing  Noise  Layout  Per page   
GeneralHere're the improvements in the codememberCuchuk Sergey21 Apr '08 - 1:10 

private static string rssRead(string link, string path)
{
// Create the XslCompiledTransform object.
XslCompiledTransform xslt = new XslCompiledTransform();
 
// Create a resolver and set the credentials to use.
XmlUrlResolver resolver = new XmlUrlResolver();
resolver.Credentials = CredentialCache.DefaultCredentials;
 
// Load the style sheet.
//xslt.Load("RSS91.xsl", XsltSettings.Default, resolver);
xslt.Load( path + @"\RSS91.xsl", XsltSettings.TrustedXslt, resolver);
 
StringBuilder builder = new StringBuilder();
// Transform the file.
XmlWriterSettings wrs = new XmlWriterSettings();
wrs.ConformanceLevel = ConformanceLevel.Auto;
using (XmlWriter writer = XmlWriter.Create(builder, wrs))
{
xslt.Transform(link, writer);
}
 
return builder.ToString();
}

 
and some changes in the form

protected void Button1_Click(object sender, EventArgs e)
{
_rezultLabel.Text = rssRead(_webLink.Text, Server.MapPath(@".\"));
}

and some changes in the form
 

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
 
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Untitled Page</title>
</head>
<body>
<form id="form1" runat="server">
&nbsp;??????? ?????:<div>
&nbsp;<asp:TextBox ID="_webLink" runat="server" Width="626px"></asp:TextBox>
<asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Process" Width="130px" /><br />
<asp:Label ID="_rezultLabel" runat="server" Height="505px" Text="??????" Width="780px"></asp:Label></div>
</form>
</body>
</html>

QuestionThe remote server returned an error: (502) Bad Gateway.memberMember 1646461 Apr '08 - 2:27 
Confused | :confused: Can you tell me the reason for the {"The remote server returned an error: (502) Bad Gateway."}, after including the code you mentioned for RSS Reader with my web application.
 
Can you please suggest some fixes for the mentioned problem?
Thanks.
GeneralRe: The remote server returned an error: (502) Bad Gateway.memberNiteShade13 Apr '08 - 22:59 
Did you set your own Proxy Address or remove it, if there is no Proxy?
 
This is were you should modify.
string ProxyServer = "192.168.1.1:8080";
 
Hope this helps,
Andrew
GeneralRe: The remote server returned an error: (502) Bad Gateway.memberMember 844439423 Jan '13 - 0:03 
I am getting the error on project run:
 
No connection could be made because the target machine actively refused it 192.168.1.1:8080
GeneralRefactor into classmemberBen Daniel7 Aug '07 - 13:43 
Neat. Was just wondering if you could turn your RSS code it into a class? RssFeed or something?
 
Thanks,
Ben Smile | :)

GeneralRe: Refactor into classmemberRaymund Macaalay7 Aug '07 - 15:07 
Do you mean like this?
 
using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Xml;
using System.IO;
using System.Net;
/// <summary>
/// Summary description for RSSFeed
/// </summary>
public class RSSFeed
{
      private string _XMLSrc = "";
      private string _Password = "";
      private string _UserAccount = "";
      private string _DomainName = "";
      private string _ProxyServer = "";
 
      public string XMLSrc
      {
            get { return _XMLSrc; }
            set { _XMLSrc = value; }
      }
      public string Password
      {
            get { return _Password; }
            set { _Password = value; }
      }
      public string UserAccount
      {
            get { return _UserAccount; }
            set { _UserAccount = value; }
      }
      public string DomainName
      {
            get { return _DomainName; }
            set { _DomainName = value; }
      }
      public string ProxyServer
      {
            get { return _ProxyServer; }
            set { _ProxyServer = value; }
      }
 
      public XmlDocument Feed()
     {
            // make remote request
            HttpWebRequest wr = (HttpWebRequest)WebRequest.Create(_XMLSrc);
            if (UserAccount != "")
            {
                  wr.Credentials = new NetworkCredential(_UserAccount, _Password, _DomainName);
            }
            // set proxy server
            if (ProxyServer != "")
            {
                  wr.Proxy = new WebProxy(_ProxyServer, true, new string[] { }, wr.Credentials);
            }
 
            // set the HTTP properties
            wr.Timeout = 10000;
            // 10 seconds
 
            // read the response
            WebResponse resp = wr.GetResponse();
            Stream stream = resp.GetResponseStream();
 
            // load XML document
            XmlTextReader reader = new XmlTextReader(stream);
            reader.XmlResolver = null;
            XmlDocument doc = new XmlDocument();
 
            doc.Load(reader);
            return doc;
 
     }
}
 

and to consume it
 
RSSFeed myFeed = new RSSFeed();
myFeed.XMLSrc = xmlsrc;
myFeed.Password = Password;
myFeed.UserAccount = UserAccount;
myFeed.DomainName = DomainName;
myFeed.ProxyServer = ProxyServer;
xmlRSS.Document = myFeed.Feed();
 
xmlRSS.TransformSource = xslsrc;
 
I hope this answers your question

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Permalink | Advertise | Privacy | Mobile
Web02 | 2.6.130523.1 | Last Updated 7 Aug 2007
Article Copyright 2007 by Raymund Macaalay
Everything else Copyright © CodeProject, 1999-2013
Terms of Use
Layout: fixed | fluid