LINQ to XML:应用XPath

有人能告诉我为什么这个程序不会枚举任何项目? 它与RDF名称空间有关吗?

using System; using System.Xml.Linq; using System.Xml.XPath; class Program { static void Main(string[] args) { var doc = XDocument.Load("http://seattle.craigslist.org/sof/index.rss"); foreach (var item in doc.XPathSelectElements("//item")) { Console.WriteLine(item.Element("link").Value); } Console.Read(); } } 

是的,这绝对是命名空间 – 尽管它是RSS命名空间,而不是RDF命名空间。 您正在尝试查找没有命名空间的项目。

在.NET中使用XPath中的命名空间有点棘手,但在这种情况下我只使用LINQ to XML Descendants方法:

 using System; using System.Linq; using System.Xml.Linq; class Test { static void Main() { var doc = XDocument.Load("http://seattle.craigslist.org/sof/index.rss"); XNamespace rss = "http://purl.org/rss/1.0/"; foreach (var item in doc.Descendants(rss + "item")) { Console.WriteLine(item.Element(rss + "link").Value); } Console.Read(); } }