c# - XPath 不返回结果 - YouTube 提要

标签 c# asp.net-mvc-3 xpath

我正在尝试在 C# 中使用 XPath 来获取 YouTube most popular Atom feed 处的 节点的 href 值.

根据我在网上阅读的文档,这个过程会相对简单,大致如下:

XmlDocument xml = new XmlDocument();
xml.Load("http://gdata.youtube.com/feeds/api/standardfeeds/most_popular");
XmlNodeList linkNodes;
linkNodes = xml.SelectNodes("/feed/entry/link[@rel='alternate']");

但这不起作用,我没有得到任何结果。我试过使用 XmlNamespaceManager 添加 namespace ,但这也无济于事。

如能及时回复,将不胜感激!谢谢!

最佳答案

我确信正确添加 namespace 有所帮助,因为我确信这就是问题所在。不过,就我个人而言,我会改用 LINQ to XML。示例代码:

using System;
using System.Linq;
using System.Xml.Linq;

public class Test
{
    static void Main()
    {
        string url =
             "http://gdata.youtube.com/feeds/api/standardfeeds/most_popular";
        var doc = XDocument.Load(url);
        XNamespace ns = "http://www.w3.org/2005/Atom";
        var links = doc.Root
                       .Elements(ns + "entry")
                       .Elements(ns + "link")
                       .Where(x => (string) x.Attribute("rel") == "alternate");

        Console.WriteLine(links.Count()); // 25
    }
}

关于c# - XPath 不返回结果 - YouTube 提要,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10166203/

相关文章:

c# - LinqToSql 预编译查询有什么好处?

c# - 同一个 RelativeLayout 中的多个 ListView

c# - (为什么)作为扩展方法调用是首选...方式?

asp.net-mvc-3 - 添加属性以选择列表选项

javascript - ASP.NET MVC 3 : Client IP addres Using Javascript

sql - 如何在 Oracle 中通过 XPath 获取第一个元素

c# - 连接共享服务器上的 MySQL 数据库问题

使用 KnockoutJS 和 Jquery 对话框时 jQuery 验证失败

javascript - 基于span标签的div的Xpath

Selenium WebDriver- WebElement.FindElements 返回比预期更多的元素