從資料庫讀取最新文章,以 text/xml 回應,無需實體 .xml 檔案。LINQ to XML 的函數式建構讓 RSS 產生邏輯極其簡潔。
public void CreateRss() {
// 1. 從資料庫取得資料 (Entity Framework / LINQ to SQL)
var db = new MyDataContext();
var articles = from p in db.News
orderby p.ID descending
select new { p.ID, p.Title, p.Content, p.PublishDate, p.Category };
// 2. 函數式建構 RSS XML
XElement rss = new XElement("rss", new XAttribute("version", "2.0"),
new XElement("channel",
new XElement("title", "我的技術部落格"),
new XElement("link", "https://example.com"),
new XElement("description", "C#, LINQ, .NET 技術分享"),
new XElement("language", "zh-TW"),
new XElement("copyright", "Copyright 2024 Example"),
new XElement("webMaster", "admin@example.com"),
// 3. 迴圈注入 item
from a in articles
select new XElement("item",
new XElement("title", a.Title),
new XElement("link", $"https://example.com/news/{a.ID}"),
new XElement("description", a.Content),
new XElement("category", a.Category),
new XElement("pubDate", a.PublishDate.ToString("R")) // RFC 1123 格式
)
)
);
// 4. 直接輸出至 Response Stream
Response.ContentType = "text/xml";
Response.ContentEncoding = Encoding.UTF8;
using (XmlWriter writer = XmlWriter.Create(Response.OutputStream, new XmlWriterSettings { Encoding = Encoding.UTF8 })) {
rss.WriteTo(writer);
}
Response.End();
}
from a in articles select new XElement(...) 產生 IEnumerable<XElement>,XElement 建構子自動展開為子節點。WriteTo(XmlWriter) 直接串流輸出,效能最佳。ToString("R") 符合標準。<atom:link rel="self" href="..."/> 符合 RSS 最佳實務。If-Modified-Since / ETag 條件式 GET 減少頻寬。OutputCache 快取熱門 Feed。瀏覽器開啟頁面應顯示格式化 XML;可用 W3C Feed Validator 驗證合規性。