65.9K
CodeProject 正在变化。 阅读更多。
Home

C# 中的简单 RSS 阅读器

starIconstarIconstarIcon
emptyStarIcon
starIcon
emptyStarIcon

3.29/5 (7投票s)

2007年8月7日

CPOL
viewsIcon

145023

downloadIcon

4914

使用 XSL 在 C# 中实现简单 RSS 阅读器

Screenshot - Sample_Page.jpg

引言

这是一种使用 C# 和 XSL 读取 RSS 源的简单方法。

Using the Code

这个解决方案主要有两个部分。一个是请求和渲染源的页面,另一个是转换 XML 源的 XSL。

首先是 default.aspx.cs。我们需要先导入以下引用

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

然后让我们进入有趣的部分

// 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;
}

然后是格式化源的 XSL。 这就是页面看起来的样子,default.aspx 只是渲染它

<?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> 

历史

  • 2007 年 8 月 7 日:初始发布
© . All rights reserved.