答案:C#可通过System.ServiceModel.Syndication命名空间创建和解析RSS。使用SyndicationFeed构建内容,Rss20FeedFormatter输出XML,可生成或读取rss.xml文件,适用于博客订阅、抓取文章等场景。

RSS(Really Simple Syndication)是一种用于发布和订阅网站内容(如新闻、博客文章等)的标准格式,通常以XML形式呈现。在C#中,你可以使用 System.ServiceModel.Syndication 命名空间来轻松创建、解析和处理RSS或Atom格式的聚合内容。
System.ServiceModel.Syndication 简介
这个命名空间是 .NET Framework 和 .NET Core/.NET 5+ 中的一部分(在较新版本中需通过 NuGet 包引入),提供了处理 syndication(聚合内容)的类,比如 SyndicationFeed、SyndicationItem 等,支持生成和读取 RSS 2.0 和 Atom 1.0 格式。
如何添加依赖(.NET 5 及以上)
如果你使用的是 .NET 5 或更高版本,需要手动安装以下 NuGet 包:
- System.ServiceModel.Syndication
可通过命令行安装:
dotnet add package System.ServiceModel.Syndication
创建 RSS Feed
使用 SyndicationFeed 和 Rss20FeedFormatter 可以创建标准的 RSS 2.0 输出。
示例代码:
using System; using System.Collections.Generic; using System.IO; using System.ServiceModel.Syndication; using System.Xml;var feed = new SyndicationFeed( "我的博客", "这是我的技术博客", new Uri("https://www.php.cn/link/1c009f16f2815685be7824a01ace7350"), "blog-feed-id", DateTime.Now );
// 添加作者信息 feed.Authors.Add(new SyndicationPerson("mailto:me@example.com", "开发者", "https://www.php.cn/link/b05edd78c294dcf6d960190bf5bde635"));
// 添加分类 feed.Categories.Add(new SyndicationCategory("技术"));
// 添加链接 feed.Links.Add(new SyndicationLink(new Uri("https://www.php.cn/link/1c009f16f2815685be7824a01ace7350"), "alternate", "访问博客"));
// 创建几篇文章(items) var items = new List
(); var item = new SyndicationItem( "第一篇文章标题", "这是文章的详细内容。", new Uri("https://www.php.cn/link/1c009f16f2815685be7824a01ace7350/post1"), "post-1", DateTime.Now );
item.PublishDate = DateTime.Now; item.LastUpdatedTime = DateTime.Now; item.Summary = new TextSyndicationContent("简要描述...");
items.Add(item); feed.Items = items;
// 输出为 RSS XML using (var writer = XmlWriter.Create("rss.xml", new XmlWriterSettings { Indent = true })) { feed.SaveAsRss20(writer); } Console.WriteLine("RSS 已生成:rss.xml");
解析 RSS Feed
你可以从一个 RSS XML 源(本地文件或网络 URL)加载并解析内容。
示例代码:
using System; using System.IO; using System.ServiceModel.Syndication; using System.Xml;// 从文件读取 RSS using (var reader = XmlReader.Create("rss.xml")) { var rssFormatter = new Rss20FeedFormatter(); if (rssFormatter.CanRead(reader)) { rssFormatter.ReadFrom(reader); SyndicationFeed feed = rssFormatter.Feed;
Console.WriteLine($"标题: {feed.Title.Text}"); Console.WriteLine($"描述: {feed.Description.Text}"); Console.WriteLine($"链接: {feed.Links[0].Uri}"); foreach (var item in feed.Items) { Console.WriteLine($"文章: {item.Title.Text}"); Console.WriteLine($"链接: {item.Links[0].Uri}"); Console.WriteLine($"发布时间: {item.PublishDate}"); Console.WriteLine("---"); } }}
常见用途
- 为博客或新闻站点生成 RSS 订阅源
- 抓取第三方 RSS 源并提取最新文章
- 集成到 ASP.NET Core Web API 中提供 RSS 接口
注意事项
- 确保正确设置 ID、发布时间和 URI 字段,避免重复或格式错误
- RSS 不支持所有 HTML 内容,建议对正文进行适当转义
- 使用 TextSyndicationContent 可指定纯文本或 HTML 类型的内容
基本上就这些。通过 SyndicationFeed 和相关类,C# 提供了简洁而强大的方式来处理 RSS 内容,无论是生成还是消费都非常直观。










