private void WriteRSS()
{
var doc = new XmlDocument();
// 1. XML 宣告
var decl = doc.CreateXmlDeclaration("1.0", "utf-8", "yes");
doc.AppendChild(decl);
// 2. 樣式表指令 (可選)
var pi = doc.CreateProcessingInstruction("xml-stylesheet", "type=\"text/xsl\" href=\"rss.xsl\"");
doc.AppendChild(pi);
// 3. 根元素
var rss = doc.CreateElement("rss");
rss.SetAttribute("version", "2.0");
doc.AppendChild(rss);
// 4.
var channel = doc.CreateElement("channel");
rss.AppendChild(channel);
// 5. Channel 必要元素
AppendTextElement(channel, "title", "搜狐焦點新聞");
AppendTextElement(channel, "link", "https://www.sohu.com");
AppendCDataElement(channel, "description", "即時報道國內外時政大事,解讀環球焦點事件");
AppendTextElement(channel, "language", "zh-cn");
AppendTextElement(channel, "pubDate", DateTime.Now.ToString("r")); // RFC1123
AppendTextElement(channel, "lastBuildDate", DateTime.Now.ToString("r"));
// 6. 從資料庫讀取文章資料
DataTable dt = GetDataTable(); // 自行實作
foreach (DataRow row in dt.Rows)
{
var item = doc.CreateElement("item");
AppendTextElement(item, "title", row["Title"].ToString());
AppendTextElement(item, "link", row["Url"].ToString());
AppendCDataElement(item, "description", row["Summary"].ToString());
AppendTextElement(item, "pubDate", Convert.ToDateTime(row["PubDate"]).ToString("r"));
AppendTextElement(item, "guid", row["Guid"].ToString());
channel.AppendChild(item);
}
// 7. 輸出回應
Response.ContentType = "application/rss+xml";
Response.ContentEncoding = Encoding.UTF8;
using (var writer = new XmlTextWriter(Response.OutputStream, Encoding.UTF8))
{
writer.Formatting = Formatting.Indented;
doc.WriteTo(writer);
}
}
// 輔助方法
void AppendTextElement(XmlElement parent, string name, string text)
{
var el = parent.OwnerDocument.CreateElement(name);
el.AppendChild(parent.OwnerDocument.CreateTextNode(text));
parent.AppendChild(el);
}
void AppendCDataElement(XmlElement parent, string name, string cdata)
{
var el = parent.OwnerDocument.CreateElement(name);
el.AppendChild(parent.OwnerDocument.CreateCDataSection(cdata));
parent.AppendChild(el);
}
CreateTextNode 顯式建立文字節點,符合 DOM 模型 (文字也是節點);InnerText 屬性設定雖方便但屬於 Microsoft 延伸,非標準 DOM。建議堅持標準做法。
description 常含 HTML 標籤或 &、< 等字元,使用 CreateCDataSection 包裝,避免 XML 解析錯誤,輸出 <![CDATA[...]]>。
Formatting.Indented 產生可讀縮排RSS 規範要求 pubDate 使用 RFC 822 格式,C# ToString("r") 產出標準 ddd, dd MMM yyyy HH:mm:ss GMT (如 Sun, 15 Oct 2023 14:30:45 GMT)。
搜狐焦點新聞
https://www.sohu.com
-
文章標題
https://example.com/1
Sun, 15 Oct 2023 14:30:45 GMT
unique-id-1
<atom:link rel="self" href="..." /> 符合 RSS 最佳實務<enclosure> 提供 Podcast/附件<category> 分類標籤System.ServiceModel.Syndication (Rss20FeedFormatter) 更高階 API