RSS是站點與站點之間共享內容的一種簡易方式(也稱為“聚合內容”),通常被用於新聞和其他按順序排列的網站,例如Blog網站。網站提供RSS輸出,有利於讓用戶發現網站內容的更新。網站用戶可以在客戶端借助於類似新聞資訊閱讀器等支持RSS的新聞聚合工具軟件,在不打開網站內容頁面的情況下閱讀支持RSS輸出的網站內容。
RSS是基於XML的一種形式。並且所有的RSS文件都要遵守萬維網聯盟(W3C)站點發布的XML 1.0規范。具體格式可以查一下RSS 2.0規范,這裡就不再重復粘貼了。
下面是我總結的幾種RSS的技術實現代碼:
1.在線生成RSS聚合頁。
(1)創建Rss.ASPx
<%@ Page language="c#" Codebehind="Rss.ASPx.cs" AutoEventWireup="false" Inherits="LiTianPing.Rss" %>
只留下這一行,其余的都刪掉。
(2)後台代碼實現方式1;Rss.ASPx.cs
private void Page_Load(object sender, System.EventArgs e)
{
Response.ContentType="text/XML";
Response.Write(GetRSS());
}
/// <summary>
/// 取得聚合文章
/// </summary>
/// <returns></returns>
public string GetRSS()
{
News t=new News();//自己的業務類
DataSet ds=t.GetListByClass(1);//根據類別得到數據
StringBuilder strCode=new StringBuilder();
strCode.Append("<?XML version=\"1.0\" encoding=\"utf-8\" standalone=\"yes\" ?>");
strCode.Append("<rss version=''2.0'' XMLns:dc=\"http://purl.org/dc/elements/1.1/\"");
&n
$False$
bsp;strCode.Append(" XMLns:trackback=\"http://madskills.com/public/XML/rss/module/trackback/\" ");
strCode.Append(" XMLns:wfw=\"http://wellformedweb.org/CommentAPI/\" XMLns:slash=\"http://purl.org/rss/1.0/modules/slash/\">");
strCode.Append("<channel>");
strCode.Append("<title>李天平RSSDemo</title>");
strCode.Append("<link>http://"+Request.ServerVariables["SERVER_NAME"]+"</link> ");
strCode.Append("<description>天道酬勤</description> ");
strCode.Append("<copyright>Copyright 2005</copyright> ");
foreach(DataRow row in ds.Tables[0].Rows)
{
string Id=row["Id"].ToString();
string title=row["title"].ToString();
string description=row["description"].ToString();
string pubdate=row["pubdate"].ToString();
string ClassId=row["ClassId"].ToString();
//string author=row["author"].ToString();
strCode.Append("<item>");
strCode.Append("<title>"+title+"</title>");
strCode.Append("<link>http://"+Request.ServerVariables["SERVER_NAME"]+"/NewsShow.ASPx?ID="+Id+"</link>");
strCode.Append("<subject>"+description+"</subject>");
strCode.Append("<description><![CDATA["+description+"]]></description>");
strCode.Append("<PubDate>"+pubdate+"</PubDate>");
strCode.Append("<category>"+ClassId+"</category>");
strCode.Append("</item>");
}
strCode.Append("</channel>");
strCode.Append("</rss>");
return strCode.ToString();
}
(3) XMLTextWriter實現方式2;Rss.ASPx.cs
string xmlDoc="rss.XML";
private void Page_Load(object sender, System.EventArgs e)
{
xmlDoc=Server.MapPath(".")+XMLDoc;
GetRSS2();
XmlDocument doc= new XMLDocument();
doc.Load(XMLDoc);
Response.ContentType = "text/XML";
doc.Save(Response.Output);
& /// <summary>
/// 取得聚合文章
/// </summary>
/// <returns></returns>
public void GetRSS2()
{
News t=new News();
DataSet ds=t.GetListByClass(1);
XmlTextWriter writer = new XmlTextWriter(XMLDoc,Encoding.UTF8);
writer.Formatting = Formatting.Indented;
writer.WriteStartDocument(true);
writer.WriteComment("RSS頁的實現");
writer.WriteStartElement("rss");
writer.WriteAttributeString("version","2.0");
writer.WriteStartElement("channel");
writer.WriteStartElement("title");
writer.WriteString("李天平RSSDemo");
writer.WriteEndElement();
writer.WriteStartElement("link");
writer.WriteString("http://"+Request.ServerVariables["SERVER_NAME"]);
writer.WriteEndElement();
writer.WriteStartElement("description");
writer.WriteString("天道酬勤");
writer.WriteEndElement();
writer.WriteStartElement("copyright");
writer.WriteString("Copyright 2005");
writer.WriteEndElement();
writer.WriteStartElement("language");
writer.WriteString("zh-cn");
writer.WriteEndElement();
foreach(DataRow row in ds.Tables[0].Rows)
{
string Id=row["Id"].ToString();
string title=row["title"].ToString();
string description=row["description"].ToString();
string pubdate=row["pubdate"].ToString();
string ClassId=row["ClassId"].ToString();
//string author=row["author"].ToString();
writer.WriteStartElement("item");
writer.WriteStartElement("title");
writer.WriteString(title);
writer.WriteEndElement();
writer.WriteStartElement("link");
writer.WriteString("ID="+Id" href_cetemp="http://"+request.servervariables["server_name"]+"/NewsShow.ASPx?ID="+Id">http://"+Request.ServerVariables["SERVER_NAME"]+"/NewsShow.ASPx?ID="+Id) ;
writer.WriteEndElement();
writer.WriteStartElement("description");
writer.WriteCData(description);
writer.WriteEndElement();
writer.WriteStartElement("pubDate");
writer.WriteString(pubdate);
writer.WriteEndElement();
writer.WriteStartElement("category");
writer.WriteString(ClassId);
writer.WriteEndElement();
writer.WriteEndElement();
}
writer.WriteEndElement();
writer.WriteEndElement();
writer.Flush();
writer.Close();
}
2.在線RSS閱讀獲取。
頁面代碼:
<P >
Feed種子:<asp:TextBox id="FeedUrl" runat="server" Width="440px"></ASP:TextBox><BR>
顯示條數:<asp:TextBox id="Num" runat="server" Width="48px"></ASP:TextBox></P>
<P >
<asp:Button id="GetFeed" runat="server" Text="獲得RSS"></ASP:Button><BR>
<BR>
<asp:Label id="RssFeed" runat="server"></ASP:Label></P>
後台代碼:
/// <summary>
/// 獲得要顯示的Feed種子數據
/// </summary>
/// <param name="RssUrl"></param>
/// <param name="showNewsCount"></param>;
/// <returns>&>
public string LoadRSS(string RssUrl, int showNewsCount)
{
string strRssList = "";
string strMsg;
try
{
XmlDocument objXMLDoc = new XMLDocument();
objXMLDoc.Load(RssUrl);
XmlNodeList objItems = objXMLDoc.GetElementsByTagName("item");
if(showNewsCount > 30)
showNewsCount = 10;
if(showNewsCount < 1)
showNewsCount = objItems.Count;
string title="";
string link="";
int i;
if(objXMLDoc.HasChildNodes == true)
{
i = 1;
foreach(XMLNode objNode in objItems)
{
if(i<=showNewsCount)
{
if(objNode.HasChildNodes == true)
{
XMLNodeList objItemsChild = objNode.ChildNodes;
foreach(XMLNode objNodeChild in objItemsChild)
{
switch(objNodeChild.Name)
{
case "title":
title = objNodeChild.InnerText;
break;
case "link":
link = objNodeChild.InnerText;
break;
}
}
i = i+1;
strRssList += "<a href=" + link +" target=_blank>" + title + "</a><br>";
}
}
}
}
strMsg = strRssList;
}
catch
{
strMsg = "RSS Feed 源數據出錯!";
}
return strMsg;
}
//獲取按鈕,獲取指定RSS
private void GetFeed_Click(object sender, System.EventArgs e)
{
if(FeedUrl.Text == "")//RSS地址
{
RssFeed.Text = "信息源不能為空,您可刷新重試或聯系管理員!";
return ;
}
RssFeed.Text = LoadRSS(FeedUrl.Text,Convert.ToInt32(Num.Text)); //獲取指定數目
}
3.無刷新動態更新的在線RSS閱讀獲取
<%@ Page language="c#" Codebehind="XMLHttp.ASPx.cs" AutoEventWireup="false" Inherits="LiTianPing.XMLHttp" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD Html 4.0 Transitional//EN" >
<Html>
<HEAD>
<title>XMLHttp</title>
<meta name="GENERATOR" Content="Microsoft Visual Studio .Net 7.1">
<meta name="CODE_LANGUAGE" Content="C#">
<meta name="vs_defaultClIEntScript" content="JavaScript">
<meta name="vs_targetSchema" content="http://schemas.microsoft.com/intellisense/IE5">
<style>td { font-size: 9pt}
</style>
<script>
<!--
var oDiv
var xh
function getXML()
{
xh =new ActiveXObject("Microsoft.XMLHTTP");
oDiv = document.getElementById("rssitem");
oDiv.style.display= "";
try
{
//如果是本地改成下面語句直接讀取
//xh.open("GET","/Rss.ASPx",false);
.open("GET","Http://ltp.cnblogs.com/Rss.ASPx",false);
xh.send(null);
loadData(xh,oDiv);
}
catch(e)
{
error(oDiv);
}
}
function loadData(xh,oDiv)
{
if (xh.readyState == 4)
{
xml = xh.responseXML;
var i;
var nodes = XML.selectNodes("/rss/channel/item");
var bloglink = XML.selectSingleNode("/rss/channel/link").text;
oDiv.innerHtml = "";
var Html;
for(i=0;i<nodes.length;i++)
{
Html += "<div >";
Html += " <div >";
Html += " <a class=font1 href=''" +nodes[i].selectSingleNode("link").text + "'' target=''_blank''>" + nodes[i].selectSingleNode("title").text +"</a><BR><BR>";
Html += " </div>";
Html += " <div >";
Html += " " +nodes[i].selectSingleNode("description").text;
Html += " </div>"
//Html += " </div>";
Html += "</div><hr>";
}
oDiv.innerHTML = Html;
}
else
{
error(oDiv);
}
}
function error(oDiv)
{
oDiv.innerHtml = "載入失敗";
}
-->
</script>
</HEAD>
<body MS_POSITIONING="GridLayout" onload="window.setTimeout(''getXML()'',200);">
<form id="Form1" method="post" runat="server">
<div align=center>
<table cellpadding="0" cellspacing="0" border="0" width="80%">
<tr>
<td>
<di] v id="rssitem" >數據載入中...</div>
</td>
</tr>
</table>
</div>
</form>
</body>
</Html>