我正在尝试开发我的第一个RSS新闻聚合器。我可以轻松地从RSSItem对象中提取链接,标题,发布日期。但是,我很难从Feed项中提取图像。不幸的是,由于我的SO声誉很低,我无法上传图片,所以请告诉我如何获取href attr的值,而不是帮我提取<img>
的src属性的值。 <a>
标记。高度评价!!
这是字符串
<div style="text-align: center;"
<a href="http://www.engadget.com/2011/07/10/element5s-mini-l-solarbag-brings-eco-friendly-energy-protectio/"></a>
</div>
编辑:
也许整个标题都错了。有没有办法可以使用XPath找到值?
答案 0 :(得分:2)
使用HTMLAgilityPack,如本文所述:
How can I get values from Html Tags?
更多信息:
Html可能格式不正确,因此我们需要另一个更容错的解析器(除了.net中提供的XML之外)。这就是HTMLAgilityPack的用武之地。
入门:
创建新的控制台应用程序
右键单击引用/管理nuget包(如果没有,请安装NuGet)。
添加html敏捷性
一个工作示例:
using System;
using System.IO;
using System.Text;
using HtmlAgilityPack;
namespace ConsoleApplication4
{
class Program
{
private const string html =
@"<?xml version=""1.0"" encoding=""ISO-8859-1""?>
<div class='linkProduct' id='link' anattribute='abc'/>
<bookstore>
<book>
<title lang=""eng"">Harry Potter</title>
<price>29.99</price>
</book>
<book>
<title lang=""eng"">Learning XML</title>
<price>39.95</price>
</book>
</bookstore>
";
static void Main(string[] args)
{
HtmlDocument doc = new HtmlDocument();
byte[] byteArray = Encoding.ASCII.GetBytes(html); MemoryStream stream = new MemoryStream(byteArray);
var ts = new MemoryStream(byteArray);
doc.Load(ts);
var root = doc.DocumentNode;
var tag = root.SelectSingleNode("/div");
var attrib = tag.Attributes["anattribute"];
Console.WriteLine(attrib.Value);
}
}
}
进一步说明:
擅长XPath。这是一个很好的起点。