首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> C語言 >> 關於C語言

C# 動態產生 RSS 2.0:XmlDocument DOM 建構完整實作

     編輯:關於C語言

動態產生 RSS 兩大流派

  • 字串拼接:簡單但易產生格式錯誤、編碼問題、效能差
  • XmlDocument DOM:符合 W3C DOM 標準、自動處理逸出/編碼、結構清晰、效能佳 (本文採用)

完整產生流程


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);
}

關鍵技術點解析

1. CreateTextNode vs InnerText

CreateTextNode 顯式建立文字節點,符合 DOM 模型 (文字也是節點);InnerText 屬性設定雖方便但屬於 Microsoft 延伸,非標準 DOM。建議堅持標準做法。

2. CDATA 區段處理 HTML/特殊字元

description 常含 HTML 標籤或 &、< 等字元,使用 CreateCDataSection 包裝,避免 XML 解析錯誤,輸出 <![CDATA[...]]>。

3. XmlTextWriter 輸出優勢

  • 串流輸出,記憶體效率高
  • Formatting.Indented 產生可讀縮排
  • 自動處理編碼宣告與實體逸出

4. 日期格式:RFC 822 / RFC 1123

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
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved