HtmlAgilityPack获取<item>标签</item>

时间:2013-12-08 19:51:29

标签: c# parsing tags html-agility-pack

我正在尝试使用HTMLAgilityPack来解析html页面并获取atom:链接,其中包含项目标记。这是html的一个示例:

<item><atom:link href="http://www.nytimes.com/2013/12/09/world/asia/justice-for-abused-
    afghan-women-still-elusive-un-report-says.html?partner=rss&amp;emc=rss" 
    rel="standout" />

我尝试通过执行以下操作,仅在atom:link代码中获取item

        List<string> urlList = new List<string>();
        HtmlAgilityPack.HtmlWeb nytRssPage = new HtmlAgilityPack.HtmlWeb();
        HtmlAgilityPack.HtmlDocument nytRssDoc = new HtmlAgilityPack.HtmlDocument();
        nytRssDoc = nytRssPage.Load(rssUrl);

        var items = nytRssDoc.DocumentNode.Descendants("item").ToList();// list of <item> tags
        foreach (var item in items)
        {
            var atomLink = item.SelectSingleNode("atom:link");
            string articleUrl = atomLink.InnerText;
            urlList.Add(articleUrl);
        }

urlList是空的,我想我做错了什么。 如果有人能指出我的解决方案,那将是非常好的,谢谢你。

3 个答案:

答案 0 :(得分:2)

以下代码提取所有链接:

 var links = doc.DocumentNode.SelectNodes(@"//item/*[name()='atom:link']/@href");

如果您想从每个项目节点中获取它们,则需要使用:

 var link = item.SelectSingleNode(@"./*[name()='atom:link']/@href");

我仍然建议您使用适当的XML结构(使用Linq to XML或XPathNavigable)或使用专用的Atom库(如Atom.NETWindows feeds API或{{3)加载Atom提要}}

答案 1 :(得分:1)

var doc = new HtmlDocument();
doc.LoadHtml(
    "<item><atom:link href=\"http://www.nytimes.com/2013/12/09/world/asia/justice-for-abused-afghan-women-still-elusive-un-report-says.html?partner=rss&amp;emc=rss\" rel=\"standout\" />");

var urls = doc.DocumentNode
    .SelectNodes("//item/*[name()='atom:link']")
    .SelectMany(node => node.Attributes.AttributesWithName("href").Select(attr => attr.Value))
    .ToList();

答案 2 :(得分:1)

要解析xml,您不需要HtmlAgilityPack

var url = "http://www.nytimes.com/services/xml/rss/nyt/International.xml";
var xDoc = XDocument.Load(url);

XNamespace atom = "http://www.w3.org/2005/Atom";

var items = xDoc.Descendants("item")
            .Select(item => new
            {
                Title = (string)item.Element("title"),
                Url = item.Element(atom + "link") != null 
                          ? (string)item.Element(atom + "link").Attribute("href") 
                          : (string)item.Element("link")
            })
            .ToList();

或者,您也可以使用SyndicationFeed

var url = "http://www.nytimes.com/services/xml/rss/nyt/International.xml";
var xDoc = XDocument.Load(url);
SyndicationFeed feed = SyndicationFeed.Load(xDoc.CreateReader());

现在你可以循环feed.Items