我正在尝试在 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/