如何从RSS源项目的所有可能的图像的URL?(How to get all possible ima

2019-06-25 08:06发布

我尝试用这个例子来从中获取图像的URL http://www.nydailynews.com/cmlink/NYDN.Article.rss

但没有成功

ü可以帮助我找到正确的方式通过,以获得从RSS源项目的所有可能的图像的URL SyndicationItem类?

有解决办法草案在这里 ,但我想应该更通用的解决方案。

谢谢!

 List<RssFeedItem> rssItems = new List<RssFeedItem>();
                    Stream stream = e.Result;
                    XmlReader response = XmlReader.Create(stream);
                    SyndicationFeed feeds = SyndicationFeed.Load(response);
                    foreach (SyndicationItem f in feeds.Items)
                    {
                        RssFeedItem rssItem = new RssFeedItem();

                        rssItem.Description = f.Summary.Text;
foreach (SyndicationLink enclosure in f.Links.Where<SyndicationLink>(x => x.RelationshipType == "enclosure"))
                            {
                                Uri url = enclosure.Uri;
                                long length = enclosure.Length;
                                string mediaType = enclosure.MediaType;
                                rssItem.ImageLinks.Add(url.AbsolutePath);
                            }
}

Answer 1:

我找到了解决办法。

foreach (SyndicationElementExtension extension in f.ElementExtensions)
{
    XElement element = extension.GetObject<XElement>();

    if (element.HasAttributes)
    {
        foreach (var attribute in element.Attributes())
        {
            string value = attribute.Value.ToLower();
            if (value.StartsWith("http://") && (value.EndsWith(".jpg") || value.EndsWith(".png") || value.EndsWith(".gif") ))
            {
                   rssItem.ImageLinks.Add(value); // Add here the image link to some array
             }
        }                                
    }                            
}


Answer 2:

XDocument xDoc = XDocument.Load("http://www.nydailynews.com/cmlink/NYDN.Article.rss");
XNamespace media = XNamespace.Get("http://search.yahoo.com/mrss/");

var images = xDoc.Descendants(media+"content")
    .Where(m=>m.Attribute("type").Value=="image/jpeg")
    .Select(m=>m.Attribute("url").Value)
    .ToArray();

- 编辑 -

var images = feeds.Items
     .SelectMany(i => i.ElementExtensions
                       .Select(e => e.GetObject<XElement>().Attribute("url").Value)
                )
     .ToArray();


Answer 3:

获取从字符串图像列表

var text = "your text with image links";
Regex regx = new Regex("http://([\\w+?\\.\\w+])+([a-zA-Z0-9\\~\\!\\@\\#\\$\\%\\^\\&amp;\\*\\(\\)_\\-\\=\\+\\\\\\/\\?\\.\\:\\;\\'\\,]*)?.(?:jpg|bmp|gif|png)", RegexOptions.IgnoreCase);
MatchCollection mactches = regx.Matches(text);


文章来源: How to get all possible image URLs from RSS feed item?