次の方法で共有


Adding an RSS feed to a site or how to use the XMLDataSource and a Repeater

I’ve been working on my demo site for wanted to add a feed to my blog from MSDN. I knew that Linq to XML can do processing of rss data (it is after all just XML, right?) and that I could create some queries in code to iterate thru the feed. But in the Visual Studio toolbox there are a couple controls that can make creating this feed much easier, namely the Data Repeater and the XMLDataSource. Using these two controls its quick to setup and run a page that shows a feed.

To start with, create a page and add the Data Repeater to your page where you want it to display. In VS2010 the repeater designer requires adding an item template in the source view. This is fairly straightforward, the code I added includes an item template that takes the blog post title and displays it as a link.

 
    <h1>Benko Blog</h1>
        <br />
        <asp:Repeater ID="Repeater1" runat="server" >
            <ItemTemplate>
                <a target="_blank" href='<%# XPath("link") %>'>
                    <%# System.Web.HttpUtility.HtmlEncode(XPath("title").ToString())%>                 </a>
                <br />
            </ItemTemplate>
        </asp:Repeater>

On the control we can create and configure a data source to act as the feed we’ll use…From the design view hover over the smart tag and select a data source:

image

From there use the XML Data Source as the type and then we configure it to know how to pull from our blog.

image

Next we add an XML data source to the repeater and configure the feed. In RSS 2.0 the feed includes a few elements of interest, including

  • “link” – The url to the feed
  • “title” – The title of the post
  • “pubDate” – Date published
  • “description” – The actual content of the post

The XPath expression to iterate thru all the posts for RSS 2.0 is “rss/channel/item”.

image

This resulted in a list of posts, quick and easy. Of course as soon as you finish something like this you want to tweak it to customize the results. One customization I wanted to do is to filter the return set to only return the last 5 posts. I found some references online that go thru XPath syntax and found that if I changed my XPath expression to include an operator I could filter the results to what I wanted. The XPath expression looked like this:

 rss/channel/item[position()<6]

If I wanted to filter for posts where the content were specific to a given search term, for example all posts that are related to webcasts then the XPath expression looked like this:

 rss/channel/item[contains(title,’Webcasts’)]

Obviously I’m only scratching the surface of what you can do, but this accomplished what I needed. There are some great examples online, and I’m including the references I used below. happy Coding!

References