A Simple RSS Feed using XmlTextWriter
7/15/2008
ASP.net, C#
(0)
RSS is a beautiful thing. No website should be without at least a basic RSS feed. For many of my sites, I use a CreateXML() function that will write an XML
file (using the XMLTextWriter) which allows you to share your latest news with the world. Since most of my sites only have occassional updates (like this
blog for example, which is rarely updated more than once a day), I like to setup the CreateXML() function to run anytime and update is made to one of my
blogs (insert, update, delete).
Below is the code that I use. It's pretty basic, but it creates a nice RSS feed that is pretty easy to integrate into your site.
private void CreateXML()
{
String CurrentDate = GetRfc822Date(DateTime.Now);
XmlTextWriter writer = new XmlTextWriter(HttpContext.Current.Server.MapPath("/myfeed.xml"),
null);
writer.WriteStartDocument();
writer.WriteStartElement("rss");
writer.WriteAttributeString("version", "2.0");
writer.WriteStartElement("channel");
// Start of channel items
writer.WriteStartElement("title");
writer.WriteString("KrisSteele.net");
writer.WriteEndElement();
writer.WriteStartElement("link");
writer.WriteString("http://www.krissteele.net/");
writer.WriteEndElement();
writer.WriteStartElement("description");
writer.WriteString("The official blog of Kris Steele");
writer.WriteEndElement();
writer.WriteStartElement("language");
writer.WriteString("en-us");
writer.WriteEndElement();
writer.WriteStartElement("pubDate");
writer.WriteString(CurrentDate);
writer.WriteEndElement();
writer.WriteStartElement("lastBuildDate");
writer.WriteString(CurrentDate);
writer.WriteEndElement();
writer.WriteStartElement("docs");
writer.WriteString("http://www.krissteele.net");
writer.WriteEndElement();
writer.WriteStartElement("generator");
writer.WriteString("ASP.net XML Writer");
writer.WriteEndElement();
writer.WriteStartElement("managingEditor");
writer.WriteString("kriswd40@yahoo.com (Kris Steele)");
writer.WriteEndElement();
writer.WriteStartElement("webMaster");
writer.WriteString("kriswd40@yahoo.com (Kris Steele)");
writer.WriteEndElement();
string sqlString = "SELECT TOP 10 * FROM MyBlog ORDER BY BlogID DESC";
int loopCount = 0;
SqlConnection MyConnection = new SqlConnection("WouldntYouLikeToKnowThisInfo");
SqlCommand objCmd = new SqlCommand(sqlString, MyConnection);
objCmd.Connection.Open();
SqlDataReader MyReader;
MyReader = objCmd.ExecuteReader(CommandBehavior.CloseConnection);
while (MyReader.Read())
{
writer.WriteStartElement(-->
This article has been view 1155 times.
|