星期一, 9月 15, 2008

(LinqToXml)抓取NBATV Top 10的Rss

因為本人很喜歡nba也有訂閱nba rss的習慣..今天就做一個簡單的範例..先看效果ㄅ..

ghjk

.aspx

<body>
<form id="form1" runat="server">
<asp:DataList ID="DataList1" runat="server">
<ItemTemplate>
<asp:Label ID="Label1" runat="server"
Text='<%# Eval("title") %>'></asp:Label><br />
<asp:HyperLink ID="HyperLink1" runat="server"
NavigateUrl='<%# Eval("link") %>'>連結</asp:HyperLink><br />
<asp:Label ID="Label3" runat="server" Text='<%# Eval("description") %>'>
</asp:Label><br />
<br />
</ItemTemplate>
</asp:DataList>
</form>
</body>

.cs

public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
string url = "http://www.nba.com/nbatvtop10/rss.xml";
DataList1.DataSource = new RssReader(url).GetRss(3);
DataList1.DataBind();
}
}

.class

public class RssReader
{
string url;
/// <summary>
/// Rss Reader
/// </summary>
/// <param name="url">塞入網址</param>
public RssReader(string url)
{
HandleUrl(url);
this.url = url;
}
/// <summary>
/// Gets the RSS.
/// </summary>
/// <param name="number">要取得多少個item</param>
/// <returns></returns>
public DataTable GetRss(int number)
{
XElement AllXElem = GetUsefulConnection();
IEnumerable<XElement> nXElems = AllXElem.Elements("channel").Elements("item").Take(number);

DataTable dt = CreateRssTable();
foreach (var xElem in nXElems)
AddRssDataRow(dt, xElem);

return dt;
}
/// <summary>
/// 建立rss table
/// </summary>
/// <returns></returns>
private DataTable CreateRssTable()
{
DataTable dt = new DataTable();
dt.Columns.Add("title");
dt.Columns.Add("link");
dt.Columns.Add("description");
dt.Columns.Add("pubDate");
return dt;
}
/// <summary>
/// 增加datarow
/// </summary>
/// <param name="dt"></param>
/// <param name="xElem"></param>
private void AddRssDataRow(DataTable dt, XElement xElem)
{
DataRow dr = dt.NewRow();
dr["title"] = xElem.Element("title").Value;
dr["link"] = xElem.Element("link").Value;
dr["description"] = xElem.Element("description").Value;
dr["pubDate"] = xElem.Element("pubDate").Value;
dt.Rows.Add(dr);
}
/// <summary>
/// 確定連線是否正確
/// </summary>
/// <returns></returns>
private XElement GetUsefulConnection()
{
try
{
return XElement.Load(this.url);
}
catch
{
throw new Exception("rss連線或檔案有問題");
}
}
/// <summary>
/// 判斷網址合不合法
/// </summary>
/// <param name="url"></param>
/// <returns></returns>
private void HandleUrl(string url)
{
//建立網址regular expression
string urlPatten = @"^http\://[a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,3}(/\S*)?$";
if (!Regex.IsMatch(url, urlPatten))
throw new Exception("網址錯誤!");
}
}

有問題在跟我說ㄅ..^_____^..

參考:

1 則留言:

williams 提到...

這個好呀,水啦...