想着闲的没事的时候重构一下朋友圈的项目,打算改成前后端分离的架构,前端使用Blazor webassembly 后端使用ASP.NET Core Web Api。先写一个简单的Rss和atom订阅解析功能~
using System.Xml;
using Moment.Shared.DBModel;
namespace Moment.Core;
/// <summary>
/// 核心模块
/// </summary>
public static class Core
{
/// <summary>
/// 获取Atom的订阅内容
/// </summary>
/// <param name="url">链接</param>
/// <returns></returns>
public static async Task<List<FeedItem>> Atom(string url)
{
var feedItems = new List<FeedItem>();
var httpClient = new HttpClient();
var feed = await httpClient.GetStringAsync(url);
var xmlDoc = new XmlDocument();
xmlDoc.LoadXml(feed);
var nsManager = new XmlNamespaceManager(xmlDoc.NameTable);
nsManager.AddNamespace("atom", "http://www.w3.org/2005/Atom");
var entries = xmlDoc.SelectNodes("//atom:entry", nsManager);
foreach (XmlNode entry in entries!)
{
var title = entry.SelectSingleNode("atom:title", nsManager)?.InnerText;
var link = entry.SelectSingleNode("atom:link", nsManager)?.Attributes!["href"]!.Value;
var summary = entry.SelectSingleNode("atom:summary", nsManager)?.InnerText;
var content = entry.SelectSingleNode("atom:content", nsManager)?.InnerText;
var published = entry.SelectSingleNode("atom:published", nsManager)?.InnerText;
feedItems.Add(new FeedItem
{
Title = title, Link = link, Content = content, Summary = summary, Published = published
});
}
return feedItems;
}
/// <summary>
/// 获取Rss2.0的订阅内容
/// </summary>
/// <param name="url">链接</param>
/// <returns></returns>
public static async Task<List<FeedItem>> Rss(string url)
{
var feedItems = new List<FeedItem>();
var httpClient = new HttpClient();
var feed = await httpClient.GetStringAsync(url);
var xmlDoc = new XmlDocument();
xmlDoc.LoadXml(feed);
var nsManager = new XmlNamespaceManager(xmlDoc.NameTable);
nsManager.AddNamespace("rss", "http://rss2.org/schema/");
nsManager.AddNamespace("content", "http://purl.org/rss/1.0/modules/content/");
var entries = xmlDoc.SelectNodes("//rss/channel/item", nsManager);
foreach (XmlNode entry in entries!)
{
var title = entry.SelectSingleNode("./title", nsManager)?.InnerText;
var link = entry.SelectSingleNode("./link", nsManager)?.InnerText;
var summary = entry.SelectSingleNode("./description", nsManager)?.InnerText;
var content = entry.SelectSingleNode("./content:encoded", nsManager)?.InnerText;
var published = entry.SelectSingleNode("./pubDate", nsManager)?.InnerText; // Added line to ge
feedItems.Add(new FeedItem
{
Title = title, Link = link, Content = content, Summary = summary, Published = published
});
}
return feedItems;
}
}
发表回复