使用 .NET Syndication 命名空间创建 RSS 2.0 Feed






4.50/5 (2投票s)
一篇 .NET 编程文章,包含代码,展示如何使用 .NET Syndication 命名空间创建符合标准的 RSS 2.0 Feed。
概述
在我的上一篇帖子中,我演示了如何使用 XML Document 创建 RSS Feed。
这引起了一些关注,有人指出我可以使用 .NET Syndication 类来实现相同的结果。因此,我创建了这篇编程文章,其中包含一个替代版本的类,它不再使用 XMLDocument
操作,而是使用这些 Syndication 类。
与 .NET Framework 中的任何默认命名空间和类一样,它们暴露了很多对我简单的 新闻 或 文章 RSS Feed 来说根本不需要的东西,所以我像上次一样将它们封装到一个工具类中,以便您可以快速轻松地创建您的 Feed。
Using the Code
代码可供下载这里,只需将其放入您的项目中,并添加对 yourprojectnamespace.Syndication 的引用。使用代码非常简单,请参阅此示例
'Create your feed
Dim rssfeed As New RSSFeed("Your RSS Feed Title",
"The description of your feed",
"The URL to the feed",
"A unique identifier for your feed",
Now,
"en-GB")
'Add a category to the main channel
rssfeed.AddFeedCategory("CodeProject", "https://codeproject.org.cn", "CodeProject")
'Add an item
dim item = rssfeed.AddItem("Item Title",
"Item Description",
"Item Body",
"Item URL",
"A unique identifier for your item",
Now,
"The author name")
'Add a category to the item
item.Categories.Add(New SyndicationCategory("CodeProject","https://codeproject.org.cn","CodeProject"))
'Output the result
Return Content(rssfeed.ToString(rssfeed.OutputType.RSS2), "text/xml")
注释
由于我们现在使用 syndication 提供程序,您可以通过更改 ToString
方法中的参数来选择输出为 RSS2 或 Atom1。
这利用了之前的辅助类,以确保 XML 文档为 UTF8,生成的 XML 通过 RSS Feed Validator 验证,并且与 Code Project 完美配合。
如有任何问题,请随时提问。