如何在我的ASP.NET站点中显示其他站点RSS提要?

时间:2013-11-01 22:02:16

标签: c# html asp.net

我在SharePoint中很容易做到这一点,但我似乎无法弄清楚如何在ASP.NET中这样做。我只想在Weather.com(http://www.weather.com/rss/national/rss_nwf_rss.xml?cm_ven=NWF&cm_cat=rss&par=NWF_rss)等网站上显示一些简单的RSS源。在每个例子中,我都看到他们继续连接数据库并添加所有这些看似无聊的额外内容。当然,必须有一种简单的方法来添加您的URL并绑定到Listview / Gridview来显示数据。你能救我吗?

1 个答案:

答案 0 :(得分:1)

我会添加一个转发器来填充RSS中的项目,并使用Syndication(System.ServiceModel.Syndication)。我选择了中继器,因为它具有非常灵活的布局。如果您愿意,可以使用ListView或GridView。我的标记看起来像这样:

<asp:Repeater ID="rptRSS" runat="server" OnItemDataBound="rptRSS_ItemDataBound">
    <HeaderTemplate>
        <table class="tablerss">
    </HeaderTemplate>
    <ItemTemplate>
        <tr>
            <td class="rsstitle">
                <asp:Label ID="lblRSSTitle" runat="server" CssClass="rsshead"></asp:Label>
            </td>
        </tr>
        <tr>
            <td>
                <asp:HyperLink ID="lnkArticle" runat="server"></asp:HyperLink>
            </td>
        </tr>
        <tr>
            <td class="rssdescription">
                <asp:Label ID="lblDescription" runat="server"></asp:Label>
            </td>
        </tr>
    </ItemTemplate>
    <FooterTemplate>
        </table>
                    <br />
    </FooterTemplate>
</asp:Repeater>

在我的代码中,我有:

protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
        LoadRSS();
    }
}
protected void rptRSS_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
    if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
    {
        HyperLink lnkArticle = (HyperLink)e.Item.FindControl("lnkArticle");
        Label lblDescription = (Label)e.Item.FindControl("lblDescription");
        Label lblRSSTitle = (Label)e.Item.FindControl("lblRSSTitle");
        SyndicationItem item = (SyndicationItem)e.Item.DataItem;

        lnkArticle.Text = item.Title.Text;
        lnkArticle.NavigateUrl = item.Links[0].Uri.ToString(); ;
        lblRSSTitle.Text = item.Title.Text;
        lblDescription.Text = item.Summary.Text;
    }
}

private void LoadRSS()
{                
    List<SyndicationItem> lstSynItem = new List<SyndicationItem>();
    string uri = "http://www.weather.com/rss/national/rss_nwf_rss.xml?cm_ven=NWF&cm_cat=rss&par=NWF_rss";
    SyndicationFeed myRss = SyndicationFeed.Load(XmlReader.Create(uri));

    foreach (SyndicationItem item in myRss.Items)
    {
        lstSynItem.Add(item);
    }
    rptRSS.DataSource = lstSynItem;
    rptRSS.DataBind();
}

Scott Michell有一些很好的文章,虽然它们没有更新,但仍然有助于开始探索RSS!