在.NET 3.5中提供了一套全新的接口来实现对RSS和ATOM这两种数据文件的读写。非常方便。下面演示一下
1. 首先要添加一个引用System.ServiceModel.Web
using System.ServiceModel.Syndication;
using System.Xml;
2. 读取RSS的代码
///
dgvResult.DataSource = items.ToArray();
}
效果如下
3. 写入RSS的代码如下
///
XmlWriter xw = XmlWriter.Create("rss.xml");
feed.SaveAsRss20(xw);
xw.Close();
}
效果如下
4. 结合ashx实现网站的RSS整合
using System;
using System.Web;
using System.Web.Services;
using System.ServiceModel.Syndication;
using System.Xml;
namespace WebApplication1
{
///
public void ProcessRequest(HttpContext context)
{
SyndicationFeed feed = new SyndicationFeed(
"我的博客",
"陈希章的博客",
new Uri("http://www.xizhang.com/"),
new[]{
new SyndicationItem("测试博客标题", "博客内容", new Uri("http://www.xizhang.com/test.aspx")),
new SyndicationItem("测试博客标题", "博客内容", new Uri("http://www.xizhang.com/test.aspx")),
new SyndicationItem("测试博客标题", "博客内容", new Uri("http://www.xizhang.com/test.aspx"))
}
);
XmlWriter xw = XmlWriter.Create(context.Response.OutputStream);
feed.SaveAsRss20(xw);
xw.Close();
context.Response.End();
}
public bool IsReusable
{
get
{
return false;
}
}
}
}
5. 结合数据库的案例
using System;
using System.Web;
using System.Web.Services;
using System.ServiceModel.Syndication;
using System.Xml;
using System.Data;
using System.Linq;
namespace WebApplication1
{
///
public void ProcessRequest(HttpContext context)
{
DataTable tb = new DataTable();
tb.Columns.AddRange(
new[]{
new DataColumn("Title"),
new DataColumn("Contents"),
new DataColumn("Link")
});
//这里可以假设读取一些数据过来
var items = from DataRow row in tb.Rows
select new SyndicationItem(row.Field (0), row.Field (1), new Uri(row.Field (2)));
SyndicationFeed feed = new SyndicationFeed(
"我的博客",
"陈希章的博客",
new Uri("http://www.xizhang.com/"),
items.ToArray()
);
XmlWriter xw = XmlWriter.Create(context.Response.OutputStream);
feed.SaveAsRss20(xw);
xw.Close();
context.Response.End();
}
public bool IsReusable
{
get
{
return false;
}
}
}
}