C# 如何从 RSS 提要中读取“dc:creator”元素?

C# How to read “dc:creator” element from an RSS feed?

我正在尝试在 C#(Windows 通用应用程序)中读取字段“dc:creator”,但无法正常工作。我需要帮助。请

HttpClient httpClient = new HttpClient();
var rssContent = await httpClient.GetStringAsync("http://www.talkingwindows.com.br/feed");
XElement xmlitems = XElement.Parse(rssContent);
List<XElement> elements = xmlitems.Descendants("item").ToList();

foreach (XElement rss in elements)
{
    Lista.Add(
        new Model
        {
          Titulo = rss.Element("title").Value,
          DataPublicacao = rss.Element("pubDate").Value,
          Descricao = rss.Element("description").Value,
          //Autor = rss.Element("dc:creator xmlns:dc=\"http://purl.org/dc/elements/1.1/\"").Value,
          Link = rss.Element("link").Value
        }
     );
}

对于select特定命名空间中的元素,您需要在其前面加上XNamespace前缀。在您的情况下,它应该如下所示:

XNamespace dcNamespace = "http://purl.org/dc/elements/1.1/";

foreach (XElement rss in elements)
{
    Lista.Add(
        new Model
        {
            Titulo = rss.Element("title").Value,
            DataPublicacao = rss.Element("pubDate").Value,
            Descricao = rss.Element("description").Value,
            Autor = rss.Element(dcNamespace + "creator").Value,
            Link = rss.Element("link").Value
        }
    );
}

或者如果你愿意,你可以这样做:

Autor = rss.Element("{http://purl.org/dc/elements/1.1/}creator").Value,

可在此处找到有关此内容的进一步阅读:

https://msdn.microsoft.com/en-us/library/bb387075.aspx

Windows.Web.Syndication 是用于解析 RSS 和 Atom 提要的 API。有个sample.

在这种情况下,您可以在 SyndicationItem.ElementExtensions.

中找到扩展元素 dc:creator

Dotnet 核心答案

使用 SyndicationClass 阅读 RSS 源只需要几行代码

安装包:System.ServiceModel.Syndication

 using System.Xml;
 using System.ServiceModel.Syndication;

 var reader = XmlReader.Create("https://blogs.yourdomain.com/feed");
 var feed = SyndicationFeed.Load<SyndicationFeed>(reader);

 foreach (var blog in feed.Items)
 var creator = blog.ElementExtensions.First(x => x.OuterName == "creator").GetObject<string>();