Create and use an Rss feed on a Web site)

Source: Internet
Author: User
Document directory
  • Attribute
  • Method
  • RSS
  • Channel
  • Item

From: http://www.tracefact.net/Asp-Net/Creating-and-Consuming-Rss-Feeds-on-Your-Website.aspx

Main reference:

Creating Rss Feeds For Your Web Site
Consuming Rss Feeds On Your Web Site

Glossary

Tag: tag
Markup: Mark
Node: node
Item: Entry
Entry: entry
Rss Reed: Rss source

Introduction

Rss is a standard way to share the content of your website with others. Rss stands:Really Simple Syndication. It is just a standardized XML tag used to describe what you want to share. Therefore, Rss is a widely accepted format when your content is ready for consumption by other users. Some sample sites that use Rss include www.asp.net, weblogs.asp.net, and www.dotnetbips.com. Dotnetbips.com publishes a list of newly added content through Rss, which may be placed by other webmasters on their sites or directories.

Rss format

As I mentioned earlier, Rss is only an XML tag with some special labels. The following mark shows the document:

& Lt; rss version = "2.0" & gt;
<Channel>
<Title> DotNetBips.com Latest Articles </title>
<Link> www.dotnetbips.com </link>
<Description> DotNetBips.com Latest Articles </description>
<Copyright> Copyright (C) DotNetBips.com. All rights reserved. </copyright>
<Generator> www.dotnetbips.com RSS Generator </generator>
<Item>
<Author> Bipin Joshi </author>
<Title> Using WebRequest and WebResponse </title>
<Link> http://www.dotnetbips.com/displayarticle.aspx? Id = 239 </link>
<Description> Description here </description>
<PubDate> Sun, 25 Jan 2004 12:00:00 am gmt </pubDate>
</Item>
</Channel>
</Rss>

Let's take a closer look at each Tag:

  • <Rss>: root node, which has a version attribute. The latest version is 2.0.
  • <Channel>: the root node under rss, which can include the <channel> node again. <Channel> nodes can further include <title>, <link>, and <item> nodes.
  • <Title>: the title of the Rss source.
  • <Link>: indicates the URL of the site that provides the Rss feed.
  • <Description>: more details about the Rss feed.
  • <Copyright>: Describes the copyright information in detail.
  • <Generator>: indicates the application that generates the Rss feed.

In addition to the preceding labels, you can also have one or more <item> labels. The Item tag represents the actual entries you want to share. For example, articles and blog portals. Each <item> tag further contains the following subnodes.

  • <Title>: indicates the title of the entry. For example, the title of an article.
  • <Author>: the author of the entry. For example, the author of the article.
  • <Link>: indicates the URL of the entry. For example, the URL of an article.
  • <Description>: contains the description of this entry. For example, the abstract of the article.
  • <PubDate>: The tag contains the release date of the entry. The typical date format is: Sun 28 Dec 2003 12:00:00 am gmt.
Method used

OK. We have already learned about the Rss format, but how to use. Net to generate an Rss source ?. Net has many XML-related classes. We will use XML Text Writer from these classes to generate Rss sources. However, we should develop a general solution that can be used on any web site. This means that our code must be independent from specific database fields or tables. To achieve this goal, we will create a class library in VS. NET. The <item> labeled data source of Rss uses a Dataset, which is usually filled in the database table. This class will have the following attributes and methods.

  • Attribute
  • Outputstream: The stream object that the source delivers.
  • RssTitle: Specifies the <title> value under the <channel> tag.
  • PublisherUrl: The <link> tag under the <channel> tag.
  • Description: The <description> value under the <channel> tag.
  • Copyright: The <copyright> value under the <channel> label.
  • Generator: indicates the <generator> value under the <channel> label.
  • ItemSource: Specifies a Dataset object containing the item row.
  • ItemTitleField: Data column, which represents the <title> label under the <item> tag
  • ItemUrlField: Data column, which represents the <link> label under the <item> tag.
  • ItemDescriptionField: Data column, which represents the <description> label under the <item> tag.
  • ItemPublicationDateFiled: Data column, which represents the <pubDate> label under the <item> tag.
  • ItemAuthor: Data column, which represents the <author> label under the <item> tag.
Method
  • PublishRss: This static method writes the Rss tag to outputstream (output stream.

The complete program list of these attributes and methods is listed below. For simple and quick demonstration, I used public fields instead of attributes. In actual applications, attributes should be used.

Using System;
Using System. IO;
Using System. Data;
Using System. Xml;
Using System. Collections. Generic;
Using System. Text;

Public class Rss {
Public Stream OutputStream;
Public string RssTitle;
Public string PublisherUrl;
Public string Description;
Public string Copyright;
Public string Generator;
Public DataSet ItemSource;
Public string ItemTitleField;
Public string ItemUrlField;
Public string ItemDescriptionField;
Public string ItemPublicationDateField;
Public string ItemAuthor;

Public static void PublishRss (Rss r ){
XmlTextWriter writer = new XmlTextWriter (r. OutputStream, Encoding. UTF8 );
Writer. WriteStartDocument ();
Writer. WriteStartElement ("rss ");
Writer. WriteAttributeString ("version", "2.0 ");
Writer. WriteStartElement ("channel ");
Writer. WriteElementString ("title", r. RssTitle );
Writer. WriteElementString ("link", r. PublisherUrl );
Writer. WriteElementString ("description", r. Description );
Writer. WriteElementString ("copyright", r. Copyright );
Writer. WriteElementString ("generator", r. Generator );

Foreach (DataRow row in r. ItemSource. Tables [0]. Rows ){
Writer. WriteStartElement ("item ");
Writer. WriteElementString ("author", row [r. ItemAuthor]. ToString ());
Writer. WriteElementString ("title", row [r. ItemTitleField]. ToString ());
Writer. WriteElementString ("link", row [r. ItemUrlField]. ToString ());
Writer. WriteElementString ("description", row [r. ItemDescriptionField]. ToString ());
Writer. WriteElementString ("pubDate", Convert. ToDateTime (row [r. ItemPublicationDateField]). ToString ("dd MMM yyyy hh: mm: 00 "));
Writer. WriteEndElement ();
}

Writer. WriteEndElement ();
Writer. WriteEndElement ();
Writer. Flush ();
}
}

NOTE:The pubDate format is very important here. When you convert the pubDate format according to the code above, if the database is, then in the English operating system, it will be converted to "14 Sep 2007". This is no problem. However, in the Chinese operating system, it becomes "September 20 ". The result is that the date is not displayed when the rss source is clicked in IE7. If you do not convert the data format and simply use a ToString (), the result is still the same. Here, I wrote a method to convert the format:

//... Omitted...
Writer. WriteElementString ("pubDate", GetRssDate (row [r. ItemPublicationDateField]);
//... Omitted...

Public static string GetRssDate (Object date ){
DateTime rssDate = Convert. ToDateTime (date );
String [] monthName = {"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug ", "Sep", "Oct", "Nov", "Dec "};

StringBuilder sb = new StringBuilder ();
Sb. Append (rssDate. Day );
Sb. Append ("");
Sb. Append (monthName [Convert. ToInt32 (rssDate. Month)-1]);
Sb. Append ("");
Sb. Append (rssDate. Year );
Sb. Append ("");
Sb. Append (rssDate. ToLongTimeString ());

Return sb. ToString ();
}

I have seen that ToString () has an overloaded method that accepts a parameter of the IFormatProvider type. This should be the standard format conversion method, and the MSDN example is a bit long, no research is ongoing. If a friend has a good solution for this problem, he can reply to the comments in Thanks.

Creating properties is as easy as shown above. The PublishRss () method is the core content we care about here. We have created an instance of the System. Xml. XmlTextWriter class. This class is a quick way to write XML documents. In this example, we pass in an OutputStream object and determine the encoding (UTF-8 ). Then we start to write different parts of this document. We use the following methods of the XmlTextWriter class.

  • WriteStartDocument (): This method is written to the declaration of XML 1.0. That is:
  • <? Xml version = "1.0" encoding = "UTF-8"?>. If you do not write this statement, you can subscribe to it in FireFox, but you cannot see any entries or update them. IE7 is normal.
  • WriteStartElement: This method writes the start tag of the specified tag.
  • WriteAttributeString: This method writes attributes to the currently opened tag.
  • WriteElementString: This method writes a start tag and an end tag, as well as text between the start and end tags.
  • WriteEndElement: This method is written to the end mark of the current open flag. You do not need to specify the name of the end tag here, because each Nesting is set internally (NOTE: belongs to the underlying mechanism.
  • Flush: This method clears all cached output to the destination location.

Note that you must call the WriteStartElement () and WriteEndElement () Methods appropriately to generate well-formed XML documents.

Create an Asp. Net Web form

Now we have created a general class, which can be used in our Web form. Suppose we store the data published as an Rss source in a table (Article). The structure of this table is as follows:

  • Title-Varchar (255)
  • Description-Varchar (1000)
  • Url-Varchar (255)
  • Author-Varchar (50)
  • Pubdate-DateTime
Get Table content in DataSet format

We will create an Rss. aspx file in the Asp. Net Web application and a GetDataSet () method in CodeBehind. This method uses DataAdapter to fill in a Dataset.

Public DataSet GetDataSet (){
SqlConnection conn = new SqlConnection ("your connection string ");
String SQL = "Select * From Article Order By ArticleId Desc ";
SqlDataAdapter da = new SqlDataAdapter (SQL, conn );
DataSet ds = new DataSet ();

Da. Fill (ds, "Article ");
Return ds;
}

Next, create an Rss class instance, set its attributes, and call the GetDataSet () method to obtain the DataSet object.

Protected void Page_Load (object sender, EventArgs e ){
DataSet ds = GetDataSet ();
Rss rss = new Rss ();
Rss. OutputStream = Response. OutputStream;
Rss. RssTitle = "DotNetBips.com Latest Articles ";
Rss. PublisherUrl = Request. Url. Host;
Rss. Description = "DotNetBips.com-Applying. NET ";
Rss. Copyright = "Copyright (C) DotNetBips.com .";
Rss. Generator = "DotNetBips.com RSS Generator ";
Rss. ItemSource = ds;
Rss. ItemTitleField = "Title ";
Rss. ItemDescriptionField = "Description ";
Rss. ItemPublicationDateField = "Pubdate ";
Rss. ItemUrlField = "Url ";
Rss. ItemAuthor = "Author ";
Response. ContentEncoding = System. Text. Encoding. UTF8;
Response. ContentType = "text/xml ";
Rss. PublishRss (rss );
Response. End ();
}

After obtaining the DataSet, set the ItemSource attribute to this DataSet. In addition, we will set the ContentEncoding and ContentType attributes of the Response object. Then, call the PublishRss () method to pass the Rss class instance.

OK. Now we can browse the Rss. aspx page in IE and we can see the image as shown in:

NOTE:Note: Create the class name and Rss of the Rss source. the Page class names in aspx CodeBehind will be the same, all of them are Rss, so you need to manually modify Rss. aspx. the Page class name in cs, for example, changed to _ Rss, the Code is as follows:
Public partial class _ Rss: System. Web. UI. Page
At the same time, modify the inherints of the HTML page:
Inherits = "_ Rss"

Consume Rss feeds

After an Rss source is created, other sites can consume the Rss source. I will create a Web form that displays the latest article www.asp.net as an example.

NOTE:I think it is because for sites that publish Rss sources, the source site is a Consumer. Therefore, the word Consume is often used in English technical articles, rather than Use.

To read XML data through a URL, we can certainly use WebRequest and WebResponse objects (refer to my article Using WebRequest and WebResponse ). However, there is a simpler method-DataSet.

The DataSet class has a method called ReadXml () that reads XML data from files or URLs on the hard disk. This method reads data and automatically generates the required able for us.

DataSet ds = new DataSet ();
Ds. ReadXml ("http: // 127.0.1.1/rss. aspx ");

Here, we create a DataSet instance and call the ReadXml () method by passing URL parameters. You can change the URL parameter as needed.

NOTE:My house is not connected to the Internet at the moment, so I used the local Rss source created earlier as a demonstration.

The table generated by the ReadXml () method

If you expect the ReadXml () method to generate a DataTable containing a list of links, you will be surprised to find that three DataTable will actually be generated. In the XML tag of the RSS format section, we can see that the tag is nested, and DataSet will automatically create related tables when reading data. It also creates ID fields for each able so that they can be linked to each other.

In this example, you will get the following structured DataTable:

RSS
  • Rss_Id
  • Version
Channel
  • Title
  • Link
  • Description
  • Language
  • Generator
  • Channel_Id
  • Rss_Id
Item
  • Creator
  • Title
  • Link
  • PubDate
  • Guid
  • Description
  • Channel_Id

Note that some fields, such as Creator and Guid, do not appear in the Rss tag. In addition, note how to add fields such as Rss_Id and Channel_Id in DataSet to associate the data table.

Now that we know the table structure, let's write some code to display the data in the GridView.

Display Data in the GridView

According to the details obtained from the Rss feed, the third table is the most important because it contains the actual link data. Here we bind our GridView to the third able.

GridView1.DataSource = ds. Tables [2]. DefaultView;
GridView1.DataBind ();

Once you call this code in the PageLoad event, you can see a screen similar to the following:

Add browser support

Both IE7 and FireFox provide Rss support. In order for the browser to provide Rss support, you must first tell them that your site has created an Rss source. You only need to add the following code to the

<Link rel = "alternate" type = "application/rss + xml" title = "Your Web Site's RSS Feed Title" href = "http://www.yourdomain.net/rss.aspx"/>

Then open the page that joins the above <link> and you will find that the RSS icon of IE7 has changed from Gray to bright orange.

Summary

In this article, we learned what RSS is and how to generate an RSS feed for your site. We use the XmlTextWriter class to create an Rss tag. We have created a common class so that it can be used in any Web application.

Then we learned how to use DataSet to consume Rss feeds. The Rss source is a Nested XML tag, and DataSet automatically creates DataTable related to each other. The third table (ITem) contains the core data of the Rss source.

I hope this article will help you.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.