Add an RSS Feed to your site
RSS feeds can be a useful way of letting your visitors see new content from your site.
To create this on your site, add a new page entitled "rssfeed.aspx" and add this to the Page Load event:
- ' Declarations
- Dim dtList As New DataTable
- Dim intCount As Integer = 10 ' Number of records to show
-
- ' Set the content attributes
- Response.ContentType = "text/xml"
- Response.ContentEncoding = Encoding.UTF8
-
- ' Use an XmlTextWriter to write the XML data to a string...
- Dim sw As New StringWriter
- Dim writer As New XmlTextWriter(sw)
-
- ' write out the rss and version
- writer.WriteStartElement("rss")
- writer.WriteAttributeString("version", "2.0")
-
- ' write out <channel>
- writer.WriteStartElement("channel")
-
- ' write out <channel>-level elements
- writer.WriteElementString("title", "ASP.NET Library - Articles")
- writer.WriteElementString("link", "http://aspnetlibrary.com")
- writer.WriteElementString("description", "A list of articles from the ASP.NET Library")
- writer.WriteElementString("ttl", "60")
-
- ' Insert your code here to get the data
- dtList = ...
-
- ' write out an <item> element for each result
- For i As Integer = 0 To (intCount - 1)
-
- ' write out the start <item> element
- writer.WriteStartElement("item")
-
- writer.WriteElementString("title", dtList.Rows(i).Item("MyTitleField").ToString)
- writer.WriteElementString("link", "http://aspnetlibrary.com/articledetails.aspx?articleid=" & dtList.Rows(i).Item("MyIDField").ToString)
- writer.WriteElementString("description", dtList.Rows(i).Item("MyDescriptionField").ToString)
- writer.WriteElementString("author", "Mark Smith")
- writer.WriteElementString("posted", dtList.Rows(i).Item("MyCreatedOnField").ToString)
-
- ' write out closing </item> element
- writer.WriteEndElement()
-
- Next
-
- ' write out closing </channel> element
- writer.WriteEndElement()
-
- ' write out closing </rss> element
- writer.WriteEndElement()
-
- ' close the writer
- writer.Close()
-
- ' write out the xml directives and the rss feed string
- Response.Write("<?xml version=""1.0"" encoding=""ISO-8859-1""?>")
- ' You can also specify an xsl sheet if needed
- ' Response.Write("<?xml-stylesheet type=""text/xsl"" href=""~/stylesheets/rssTemplate.xsl""?>")
- Response.Write(sw.ToString())
-
- ' Clean Up
- writer = Nothing
- sw = Nothing
As I mentioned above, you can see this in action
here so to get a working example on your site, you'll need to:
- Add the code that you use to connect to your database (in the section with the comment "Insert your code here to get the data").
- Customise the sections where I have referenced my site and set the database fields in the "item element" loop.
- Make sure you import the System.IO, System.Xml and System.Data classes.