0

我目前正在编写一个非常基本的程序,它将首先通过网站的 html 代码查找所有 RSS 链接,然后将 RSS 链接放入一个数组并将链接的每个内容解析为现有的 XML 文件。

但是,我仍在学习 C#,而且我对所有课程还不是很熟悉。我已经在 PHP 中通过使用 get_file_contents() 编写自己的类来完成所有这些工作,并且还使用 cURL 来完成这项工作。我也设法用 Java 解决了这个问题。无论如何,我试图通过使用 C# 来完成相同的结果,但我认为我在这里做错了。

TLDR;编写正则表达式以查找网站上所有 RSS 链接的最佳方法是什么?

到目前为止,我的代码如下所示:

        private List<string> getRSSLinks(string websiteUrl)
    {
        List<string> links = new List<string>();
        MatchCollection collection = Regex.Matches(websiteUrl, @"(<link.*?>.*?</link>)", RegexOptions.Singleline);

        foreach (Match singleMatch in collection)
        {
            string text = singleMatch.Groups[1].Value;
            Match matchRSSLink = Regex.Match(text, @"type=\""(application/rss+xml)\""", RegexOptions.Singleline);
            if (matchRSSLink.Success)
            {
                links.Add(text);
            }
        }

        return links;
    }
4

1 回答 1

0

不要使用正则表达式来解析 html。改用 html 解析器查看此链接以获取解释

我更喜欢HtmlAgilityPack来解析 html

using (var client = new WebClient())
{
    HtmlAgilityPack.HtmlDocument doc = new HtmlAgilityPack.HtmlDocument();
    doc.LoadHtml(client.DownloadString("http://www.xul.fr/en-xml-rss.html"));

    var rssLinks = doc.DocumentNode.Descendants("link")
        .Where(n => n.Attributes["type"] != null && n.Attributes["type"].Value == "application/rss+xml")
        .Select(n => n.Attributes["href"].Value)
        .ToArray();
}
于 2012-05-27T17:00:03.523 回答